mirror of
https://github.com/LGUG2Z/komorebi.git
synced 2026-11-17 22:33:12 +01:00
feat(backend): reach the compositor through one trait
The window manager decides where every window goes, and asks a compositor to put it there. If it asked KWin directly, every test of its logic would have to boot a virtual machine, so everything it needs from the desktop goes through one trait, `Backend`: queries for windows, monitors, the focus and the pointer, and commands to move, focus, raise, minimize and close a window and to put the pointer somewhere. A real backend answers from a table that compositor events keep up to date, so a query never waits for the compositor; a command returns once it has been accepted, not once the client has acted. `FakeBackend` is the other implementation: an in-memory desktop that does what it is told, at once and exactly, and records every command so that a test can assert on what the window manager asked for. A test can also do what a user does without the window manager asking: move a window, close it, change the focus, turn a window into a dialog. It is strict where KWin is (a command about a window that is gone is an error) and clamps where a GTK4 client does (a minimum size). `with_backend` overrides the process-wide backend for the current thread only and puts the previous one back on drop, also on a panic, which is what keeps one test's desktop out of the next. The module is the first to have `#![deny(missing_docs)]`. The contract (what must be implemented, that a backend is `Send + Sync`) is proved by two `compile_fail` examples with their error codes, and the rules nothing checks are listed as such. docs/dev/ARCHITECTURE.md describes the trait, its roles and the layer that enforces each rule, and docs/dev/DESIGN.md has the first decisions with their reasons. Both grow with the code.
This commit is contained in:
1 parent
507c51f0c0
commit
ed6a8e96c3
8 files changed
+1109
-4
No files matched your search
Generated
+49
@@ -733,7 +733,9 @@ name = "komorebi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"color-eyre",
|
||||
"komorebi-layouts",
|
||||
"parking_lot",
|
||||
"schemars 1.2.3",
|
||||
"serde",
|
||||
"serde_json_lenient",
|
||||
@@ -820,6 +822,15 @@ version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
@@ -892,6 +903,29 @@ version = "4.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.9.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
@@ -964,6 +998,15 @@ version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ref-cast"
|
||||
version = "1.0.27"
|
||||
@@ -1052,6 +1095,12 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
|
||||
@@ -22,9 +22,10 @@ without a checkout of the toolchain.
|
||||
## Crates
|
||||
|
||||
- [`komorebi`](komorebi): the daemon, and the library behind it. The library has
|
||||
the vocabulary the window manager is written in (`core`), the `Ring` that
|
||||
holds monitors, workspaces and containers, and the lists in which some
|
||||
elements are locked in place.
|
||||
the vocabulary the window manager is written in (`core`), the `Backend` trait
|
||||
through which it reaches a compositor and the in-memory desktop the tests use
|
||||
(`backend`), the `Ring` that holds monitors, workspaces and containers, and the
|
||||
lists in which some elements are locked in place.
|
||||
- [`version`](version): the version string every binary reports.
|
||||
|
||||
The layouts, which turn a work area and a number of containers into a rectangle
|
||||
@@ -45,10 +46,20 @@ The VM tests boot NixOS with Plasma and run a real KWin. `just vm NAME` runs
|
||||
one; [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) has the details, including
|
||||
how to run them on a Mac.
|
||||
|
||||
## How it fits together
|
||||
|
||||
The daemon decides where every window goes and asks the compositor to put it
|
||||
there. Everything it needs from the compositor is behind one trait, `Backend`,
|
||||
so the window manager logic runs against a real compositor and against an
|
||||
in-memory fake desktop alike. [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
|
||||
describes the trait and where each of its rules is enforced.
|
||||
|
||||
## Documentation
|
||||
|
||||
`cargo doc --workspace --no-deps --open` builds the API documentation.
|
||||
[`CONTRIBUTING.md`](CONTRIBUTING.md) says how to work on the code, and
|
||||
[`CONTRIBUTING.md`](CONTRIBUTING.md) says how to work on the code.
|
||||
[`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md) describes the model,
|
||||
[`docs/dev/DESIGN.md`](docs/dev/DESIGN.md) says why it is built that way, and
|
||||
[`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) how the VM tests work.
|
||||
|
||||
## License
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# Architecture
|
||||
|
||||
komorebi is a tiling window manager. It decides where every window goes and asks a
|
||||
compositor to put it there. Everything it needs from the compositor is behind one trait,
|
||||
[`Backend`](../../komorebi/src/backend/mod.rs), so the window manager is written, and
|
||||
tested, without one.
|
||||
|
||||
This page describes that trait, who implements and calls it, and where each of its rules
|
||||
is enforced. It grows with the code: each part of the daemon that is added has its place
|
||||
here.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
- **Window**: a top-level surface a client has asked the compositor for, named by the
|
||||
compositor's `u32` id.
|
||||
- **Monitor**: a connected output, with its bounds and its work area (its bounds minus
|
||||
the panels).
|
||||
- **Compositor**: the program that owns the screen and the windows. On KDE Plasma it is
|
||||
KWin.
|
||||
- **Backend**: the implementation of the [`Backend`](../../komorebi/src/backend/mod.rs)
|
||||
trait that talks to a compositor.
|
||||
- **Fake**: [`FakeBackend`](../../komorebi/src/backend/fake.rs), the in-memory backend
|
||||
the tests use.
|
||||
|
||||
## Design
|
||||
|
||||
The window manager reads the desktop and changes it through [`Backend`] and through
|
||||
nothing else. A real backend answers from a table that compositor events keep up to date,
|
||||
and sends commands to the compositor. The fake answers from a table the test fills in, and
|
||||
records the commands. The window manager cannot tell them apart, which is the point:
|
||||
the same logic runs against both. The reasons are in
|
||||
[DESIGN.md](DESIGN.md#why-is-everything-the-window-manager-needs-behind-one-trait).
|
||||
|
||||
## The model
|
||||
|
||||
The desktop, as the window manager sees it, is two lists and a pointer:
|
||||
|
||||
- **Windows**, each a [`WindowInfo`]: its id, process, title, `app_id`, executable, frame,
|
||||
whether it is minimized, whether it is a normal application window (as opposed to a
|
||||
dialog, a splash screen or a dock), and whether it is alive. A window that has been
|
||||
destroyed stays in the table for a short time with `alive` false, so that the event that
|
||||
mentions it can still be logged.
|
||||
- **Monitors**, each a [`MonitorInfo`]: its id, name, an identity that survives a
|
||||
hot-plug, its bounds and its work area.
|
||||
- **The pointer**, a position if the compositor says where it is, and the **focus**, the id
|
||||
of the window that has it.
|
||||
|
||||
A command is one of: move and resize a window, focus it, raise it, minimize it or bring it
|
||||
back, close it, and put the pointer in the middle of a rectangle.
|
||||
|
||||
## The parts
|
||||
|
||||
- [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the
|
||||
process-wide handle ([`set_backend`], [`backend`], [`with_backend`]).
|
||||
- [`backend::fake`](../../komorebi/src/backend/fake.rs): the fake.
|
||||
|
||||
The handle is a process-wide singleton so that a window can be a small `Copy` value
|
||||
that carries only its id, and ask the backend for what it needs. A test replaces it for
|
||||
its own thread with [`with_backend`], which puts the previous one back when the test is
|
||||
done, also if it panics.
|
||||
|
||||
## Traits and roles
|
||||
|
||||
**[`Backend`] is the compositor.** It is implemented once for each compositor and once for
|
||||
the fake. The window manager is its only caller, through [`backend`]. The contract:
|
||||
|
||||
- Queries (`windows`, `window`, `foreground_window`, `cursor_pos`) answer from the
|
||||
backend's own table and never wait for the compositor. `monitors` may fail.
|
||||
- A command returns once the compositor has accepted it, not once the client has acted on
|
||||
it. The frame a window ends up with is what `window_rect` says afterwards, because a
|
||||
client may refuse a size.
|
||||
- A command about a window that does not exist, or is no longer alive, is an error. It
|
||||
never panics.
|
||||
- `shutdown`, `is_window`, `window_rect` and `monitor_from_point` have defaults, written in
|
||||
terms of the queries. An implementor should not need to override them, except `shutdown`
|
||||
when it created something in the compositor that has to be given up.
|
||||
|
||||
## What is guaranteed, and by what
|
||||
|
||||
| Rule | Enforced by | Proof | Escape hatch |
|
||||
|---|---|---|---|
|
||||
| A backend implements every query and command | type system: the methods have no defaults | `compile_fail,E0046` on [`Backend`] | none |
|
||||
| A backend can be shared between threads | type system: `Backend: Send + Sync + 'static` | `compile_fail,E0277` on [`Backend`] | none |
|
||||
| The window manager asks for a backend that was never installed | runtime error: [`backend`] panics, naming [`set_backend`] and [`with_backend`] | `# Panics` on [`backend`] | none |
|
||||
| A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none |
|
||||
| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error`, against the fake only | none |
|
||||
| Queries never block on the compositor | convention only | none | none |
|
||||
| Only the backend module reaches the compositor | convention only | none | none |
|
||||
|
||||
The last two rows are rules nothing checks. A real backend that waits inside a query
|
||||
breaks the first, and a module that talks to D-Bus directly breaks the second.
|
||||
|
||||
## Where to look in the code
|
||||
|
||||
- [`komorebi/src/backend/mod.rs`](../../komorebi/src/backend/mod.rs): the trait.
|
||||
- [`komorebi/src/backend/fake.rs`](../../komorebi/src/backend/fake.rs): the fake and its
|
||||
tests.
|
||||
- [`komorebi/src/core`](../../komorebi/src/core/mod.rs): the vocabulary the rest is written
|
||||
in.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Design
|
||||
|
||||
This document explains why komorebi for KDE is built the way it is, one decision at a time.
|
||||
It is opinionated: these are the reasons behind the code, and reasonable people may disagree
|
||||
with them. Where a reason was not written down, the entry says that it needs one.
|
||||
|
||||
It grows with the code: a decision is added in the commit that makes it.
|
||||
|
||||
## What is komorebi for KDE the port of?
|
||||
|
||||
komorebi has a Windows implementation, the original, and a macOS one. The Windows one is
|
||||
the reference. I used it as the reference for what to adapt, and I prefer what KDE and
|
||||
Wayland do natively over a workaround that the other two platforms need. The events the
|
||||
window manager reacts to follow the Windows ones (a window is shown, destroyed, focused,
|
||||
minimized, moved, resized), and a window is a small `Copy` handle, as there.
|
||||
|
||||
## Why is everything the window manager needs behind one trait?
|
||||
|
||||
So that the window manager can be tested without a compositor. A test that needs a real
|
||||
KWin has to boot a virtual machine, which takes a minute or more and needs QEMU with a
|
||||
hypervisor ([vm-tests.md](vm-tests.md)); a test against an in-memory desktop takes
|
||||
milliseconds and runs anywhere. The logic (which window goes where, what happens when one
|
||||
closes, how a stack cycles) is tested with the second kind, and the VM tests are kept for
|
||||
what only KWin can tell.
|
||||
|
||||
The cost is that a second implementation has to be kept honest. A fake that does what it
|
||||
is told is not KWin: a real client may refuse a size, a compositor may report an event the
|
||||
fake never raises, and a fake that is too permissive hides a bug that a compositor would
|
||||
show. The fake is therefore written to be strict where KWin is (a command about a window
|
||||
that no longer exists is an error) and to clamp where a real client does (a window with a
|
||||
minimum size keeps to it).
|
||||
|
||||
## Why is the backend a process-wide singleton?
|
||||
|
||||
So that a window can be a small `Copy` value that carries only its id. A window that
|
||||
had to hold a reference to its backend would not be `Copy`, and every function that
|
||||
moves, focuses or hides one would take a context argument as well. That is a lot of
|
||||
plumbing for a thing that never changes while the daemon runs.
|
||||
|
||||
The cost is a global. A test that wants a private desktop overrides it for its own thread
|
||||
with `with_backend`, which restores the previous one afterwards, also on a panic.
|
||||
|
||||
## Why does a backend answer from a table instead of asking the compositor?
|
||||
|
||||
A query that waits for the compositor can wait for a long time, and the window manager
|
||||
asks a lot of questions: every move of a container is followed by a look at where each
|
||||
window ended up. A backend keeps a table that the compositor's events update, so a query
|
||||
is a lookup. The trade-off is that the table can be a moment behind the compositor, which
|
||||
is why a command returns when it has been accepted and not when the client has acted, and
|
||||
why the frame a window really has is read back afterwards.
|
||||
@@ -9,6 +9,8 @@ komorebi-layouts = { workspace = true }
|
||||
version = { path = "../version" }
|
||||
|
||||
clap = { workspace = true }
|
||||
color-eyre = { workspace = true }
|
||||
parking_lot = "0.12"
|
||||
schemars = { workspace = true, optional = true }
|
||||
serde = { workspace = true }
|
||||
serde_with = { version = "3", features = ["schemars_1"] }
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
//! An in-memory desktop, so that window manager logic can be tested without a compositor.
|
||||
//!
|
||||
//! A [`FakeBackend`] does what it is told, at once and exactly: a window asked to move to a
|
||||
//! rectangle is at that rectangle, unless it was given a minimum size, which it then keeps to the
|
||||
//! way a GTK4 client does. Every command is recorded, so that a test can assert on what the window
|
||||
//! manager asked for, and a test can do what a user does (move a window, close it, change which
|
||||
//! one has the focus) without the window manager having asked.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```rust
|
||||
//! use komorebi::backend::Backend;
|
||||
//! use komorebi::backend::fake::Command;
|
||||
//! use komorebi::backend::fake::FakeBackend;
|
||||
//! use komorebi::core::Rect;
|
||||
//!
|
||||
//! let fake = FakeBackend::with_one_monitor();
|
||||
//! fake.open_window(1, "foot", "foot", "a terminal");
|
||||
//!
|
||||
//! let tile = Rect { left: 0, top: 0, right: 960, bottom: 1050 };
|
||||
//! fake.set_rect(1, &tile)?;
|
||||
//!
|
||||
//! assert_eq!(fake.rect_of(1), Some(tile));
|
||||
//! assert_eq!(fake.commands(), [Command::SetRect(1, tile)]);
|
||||
//! # Ok::<(), color_eyre::eyre::Report>(())
|
||||
//! ```
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use super::Backend;
|
||||
use super::MonitorInfo;
|
||||
use super::WindowInfo;
|
||||
use crate::core::Rect;
|
||||
use color_eyre::eyre;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A command the window manager sent to the backend.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Command {
|
||||
/// [`Backend::set_rect`]: the window and the rectangle it was asked to take.
|
||||
SetRect(u32, Rect),
|
||||
/// [`Backend::focus`]: the window, and whether the pointer was to follow.
|
||||
Focus(u32, bool),
|
||||
/// [`Backend::raise`].
|
||||
Raise(u32),
|
||||
/// [`Backend::minimize`].
|
||||
Minimize(u32),
|
||||
/// [`Backend::unminimize`].
|
||||
Unminimize(u32),
|
||||
/// [`Backend::close`].
|
||||
Close(u32),
|
||||
/// [`Backend::center_cursor_in`].
|
||||
CenterCursor(Rect),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// When set, a command about a window nobody opened creates that window first (see
|
||||
/// [`FakeBackend::permissive`]).
|
||||
permissive: bool,
|
||||
windows: HashMap<u32, WindowInfo>,
|
||||
min_sizes: HashMap<u32, (i32, i32)>,
|
||||
monitors: Vec<MonitorInfo>,
|
||||
foreground: Option<u32>,
|
||||
cursor: Option<(i32, i32)>,
|
||||
commands: Vec<Command>,
|
||||
}
|
||||
|
||||
/// An in-memory [`Backend`].
|
||||
///
|
||||
/// It has no windows and no monitors until a test adds them. The window manager reaches it through
|
||||
/// [`crate::backend::backend`], installed with [`crate::backend::with_backend`].
|
||||
#[derive(Default)]
|
||||
pub struct FakeBackend {
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
impl FakeBackend {
|
||||
/// Returns a fake with no monitors and no windows.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Returns a fake that never refuses: a command about a window nobody opened creates it.
|
||||
///
|
||||
/// The crate's own unit tests get one by default, so that a test of pure window manager logic,
|
||||
/// which moves and focuses windows it never opened, needs no set-up.
|
||||
pub fn permissive() -> Self {
|
||||
let fake = Self::with_one_monitor();
|
||||
fake.state.lock().permissive = true;
|
||||
fake
|
||||
}
|
||||
|
||||
/// Returns a fake with one 1920x1080 monitor, named `Virtual-0`, whose work area leaves 30
|
||||
/// pixels at the bottom for a panel.
|
||||
pub fn with_one_monitor() -> Self {
|
||||
let fake = Self::new();
|
||||
fake.add_monitor(
|
||||
1,
|
||||
"Virtual-0",
|
||||
Rect {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: 1920,
|
||||
bottom: 1080,
|
||||
},
|
||||
Rect {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: 1920,
|
||||
bottom: 1050,
|
||||
},
|
||||
);
|
||||
fake
|
||||
}
|
||||
|
||||
/// Adds a monitor. Its serial number identity is its name.
|
||||
pub fn add_monitor(&self, id: u32, name: &str, size: Rect, work_area: Rect) {
|
||||
self.state.lock().monitors.push(MonitorInfo {
|
||||
id,
|
||||
name: name.to_string(),
|
||||
serial_number_id: name.to_string(),
|
||||
size,
|
||||
work_area,
|
||||
});
|
||||
}
|
||||
|
||||
/// Opens a window of an application. It starts at 800x600 at (100, 100), a normal window with
|
||||
/// no focus.
|
||||
pub fn open_window(&self, id: u32, exe: &str, class: &str, title: &str) {
|
||||
self.state.lock().windows.insert(
|
||||
id,
|
||||
WindowInfo {
|
||||
id,
|
||||
pid: i32::try_from(id).unwrap_or_default() + 1000,
|
||||
title: title.to_string(),
|
||||
class: class.to_string(),
|
||||
exe: exe.to_string(),
|
||||
path: format!("/usr/bin/{exe}"),
|
||||
rect: Rect {
|
||||
left: 100,
|
||||
top: 100,
|
||||
right: 800,
|
||||
bottom: 600,
|
||||
},
|
||||
minimized: false,
|
||||
normal: true,
|
||||
alive: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Destroys a window, as the user closing it does: the window manager is not asked. If it had
|
||||
/// the focus, nothing has it now.
|
||||
pub fn close_window_now(&self, id: u32) {
|
||||
let mut state = self.state.lock();
|
||||
if let Some(window) = state.windows.get_mut(&id) {
|
||||
window.alive = false;
|
||||
}
|
||||
if state.foreground == Some(id) {
|
||||
state.foreground = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks a window as a dialog, a splash screen, a utility window or the like, or as a normal
|
||||
/// one again.
|
||||
pub fn set_normal(&self, id: u32, normal: bool) {
|
||||
if let Some(w) = self.state.lock().windows.get_mut(&id) {
|
||||
w.normal = normal;
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts a window somewhere without the window manager having asked, as a user dragging it
|
||||
/// does.
|
||||
pub fn move_window_by_user(&self, id: u32, rect: Rect) {
|
||||
if let Some(w) = self.state.lock().windows.get_mut(&id) {
|
||||
w.rect = rect;
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives a window a minimum size. A [`Backend::set_rect`] for something smaller leaves it at
|
||||
/// the minimum, which is how a GTK4 client answers.
|
||||
pub fn set_min_size(&self, id: u32, width: i32, height: i32) {
|
||||
self.state.lock().min_sizes.insert(id, (width, height));
|
||||
}
|
||||
|
||||
/// Changes a window's title.
|
||||
pub fn set_title(&self, id: u32, title: &str) {
|
||||
if let Some(w) = self.state.lock().windows.get_mut(&id) {
|
||||
w.title = title.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes which window has the focus, as the user does, without the window manager asking.
|
||||
pub fn set_foreground(&self, id: Option<u32>) {
|
||||
self.state.lock().foreground = id;
|
||||
}
|
||||
|
||||
/// Puts the pointer somewhere.
|
||||
pub fn set_cursor(&self, x: i32, y: i32) {
|
||||
self.state.lock().cursor = Some((x, y));
|
||||
}
|
||||
|
||||
/// Returns where a window is, if it was ever opened.
|
||||
pub fn rect_of(&self, id: u32) -> Option<Rect> {
|
||||
self.state.lock().windows.get(&id).map(|w| w.rect)
|
||||
}
|
||||
|
||||
/// Returns every command received so far, oldest first.
|
||||
pub fn commands(&self) -> Vec<Command> {
|
||||
self.state.lock().commands.clone()
|
||||
}
|
||||
|
||||
/// Forgets the commands received so far.
|
||||
pub fn clear_commands(&self) {
|
||||
self.state.lock().commands.clear();
|
||||
}
|
||||
|
||||
fn record<T>(
|
||||
&self,
|
||||
id: u32,
|
||||
command: Command,
|
||||
f: impl FnOnce(&mut State) -> T,
|
||||
) -> eyre::Result<T> {
|
||||
let mut state = self.state.lock();
|
||||
state.commands.push(command);
|
||||
if state.permissive && !state.windows.contains_key(&id) {
|
||||
state.windows.insert(id, permissive_window(id));
|
||||
}
|
||||
match state.windows.get(&id) {
|
||||
Some(w) if w.alive => Ok(f(&mut state)),
|
||||
_ => eyre::bail!("no such window: {id}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn permissive_window(id: u32) -> WindowInfo {
|
||||
WindowInfo {
|
||||
id,
|
||||
pid: i32::try_from(id).unwrap_or_default() + 1000,
|
||||
title: format!("window {id}"),
|
||||
class: format!("class.{id}"),
|
||||
exe: format!("exe{id}"),
|
||||
path: format!("/usr/bin/exe{id}"),
|
||||
rect: Rect::default(),
|
||||
minimized: false,
|
||||
normal: true,
|
||||
alive: true,
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for FakeBackend {
|
||||
fn windows(&self) -> Vec<WindowInfo> {
|
||||
let state = self.state.lock();
|
||||
let mut windows: Vec<_> = state
|
||||
.windows
|
||||
.values()
|
||||
.filter(|w| w.alive)
|
||||
.cloned()
|
||||
.collect();
|
||||
windows.sort_by_key(|w| w.id);
|
||||
windows
|
||||
}
|
||||
|
||||
fn window(&self, id: u32) -> Option<WindowInfo> {
|
||||
let mut state = self.state.lock();
|
||||
if state.permissive && !state.windows.contains_key(&id) {
|
||||
state.windows.insert(id, permissive_window(id));
|
||||
}
|
||||
state.windows.get(&id).cloned()
|
||||
}
|
||||
|
||||
fn foreground_window(&self) -> Option<u32> {
|
||||
self.state.lock().foreground
|
||||
}
|
||||
|
||||
fn monitors(&self) -> eyre::Result<Vec<MonitorInfo>> {
|
||||
Ok(self.state.lock().monitors.clone())
|
||||
}
|
||||
|
||||
fn cursor_pos(&self) -> Option<(i32, i32)> {
|
||||
self.state.lock().cursor
|
||||
}
|
||||
|
||||
fn set_rect(&self, id: u32, rect: &Rect) -> eyre::Result<()> {
|
||||
let rect = *rect;
|
||||
self.record(id, Command::SetRect(id, rect), |state| {
|
||||
let (min_w, min_h) = state.min_sizes.get(&id).copied().unwrap_or((0, 0));
|
||||
if let Some(w) = state.windows.get_mut(&id) {
|
||||
w.rect = Rect {
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
right: rect.right.max(min_w),
|
||||
bottom: rect.bottom.max(min_h),
|
||||
};
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn focus(&self, id: u32, mouse_follows_focus: bool) -> eyre::Result<()> {
|
||||
self.record(id, Command::Focus(id, mouse_follows_focus), |state| {
|
||||
state.foreground = Some(id);
|
||||
if mouse_follows_focus && let Some(w) = state.windows.get(&id) {
|
||||
state.cursor = Some((
|
||||
w.rect.left + w.rect.right / 2,
|
||||
w.rect.top + w.rect.bottom / 2,
|
||||
));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn raise(&self, id: u32) -> eyre::Result<()> {
|
||||
self.record(id, Command::Raise(id), |_| ())
|
||||
}
|
||||
|
||||
fn minimize(&self, id: u32) -> eyre::Result<()> {
|
||||
self.record(id, Command::Minimize(id), |state| {
|
||||
if let Some(w) = state.windows.get_mut(&id) {
|
||||
w.minimized = true;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn unminimize(&self, id: u32) -> eyre::Result<()> {
|
||||
self.record(id, Command::Unminimize(id), |state| {
|
||||
if let Some(w) = state.windows.get_mut(&id) {
|
||||
w.minimized = false;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn close(&self, id: u32) -> eyre::Result<()> {
|
||||
self.record(id, Command::Close(id), |state| {
|
||||
if let Some(w) = state.windows.get_mut(&id) {
|
||||
w.alive = false;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn center_cursor_in(&self, rect: &Rect) -> eyre::Result<()> {
|
||||
let mut state = self.state.lock();
|
||||
state.commands.push(Command::CenterCursor(*rect));
|
||||
state.cursor = Some((rect.left + rect.right / 2, rect.top + rect.bottom / 2));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tile(left: i32, width: i32) -> Rect {
|
||||
Rect {
|
||||
left,
|
||||
top: 0,
|
||||
right: width,
|
||||
bottom: 1050,
|
||||
}
|
||||
}
|
||||
|
||||
fn fake_with(ids: &[u32]) -> FakeBackend {
|
||||
let fake = FakeBackend::with_one_monitor();
|
||||
for id in ids {
|
||||
fake.open_window(*id, "foot", "foot", &format!("window {id}"));
|
||||
}
|
||||
fake
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_asked_to_move_is_where_it_was_asked() -> eyre::Result<()> {
|
||||
let fake = fake_with(&[1]);
|
||||
|
||||
fake.set_rect(1, &tile(10, 500))?;
|
||||
|
||||
assert_eq!(fake.rect_of(1), Some(tile(10, 500)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_keeps_to_its_minimum_size() -> eyre::Result<()> {
|
||||
let fake = fake_with(&[1]);
|
||||
fake.set_min_size(1, 600, 400);
|
||||
|
||||
fake.set_rect(1, &tile(0, 300))?;
|
||||
|
||||
let rect = fake.rect_of(1).expect("window 1 was opened");
|
||||
assert_eq!((rect.right, rect.bottom), (600, 1050));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_is_recorded_in_order() -> eyre::Result<()> {
|
||||
let fake = fake_with(&[1, 2]);
|
||||
|
||||
fake.focus(1, false)?;
|
||||
fake.raise(2)?;
|
||||
fake.minimize(1)?;
|
||||
fake.unminimize(1)?;
|
||||
fake.close(2)?;
|
||||
|
||||
assert_eq!(
|
||||
fake.commands(),
|
||||
[
|
||||
Command::Focus(1, false),
|
||||
Command::Raise(2),
|
||||
Command::Minimize(1),
|
||||
Command::Unminimize(1),
|
||||
Command::Close(2),
|
||||
]
|
||||
);
|
||||
fake.clear_commands();
|
||||
assert!(fake.commands().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_about_a_window_nobody_opened_is_an_error() {
|
||||
let fake = fake_with(&[1]);
|
||||
|
||||
let error = fake.focus(9, false).expect_err("window 9 does not exist");
|
||||
|
||||
assert_eq!(error.to_string(), "no such window: 9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_about_a_closed_window_is_an_error() {
|
||||
let fake = fake_with(&[1]);
|
||||
fake.close_window_now(1);
|
||||
|
||||
assert!(fake.raise(1).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_permissive_fake_creates_the_windows_it_is_asked_about() -> eyre::Result<()> {
|
||||
let fake = FakeBackend::permissive();
|
||||
|
||||
fake.focus(77, false)?;
|
||||
|
||||
assert!(fake.is_window(77));
|
||||
assert_eq!(fake.foreground_window(), Some(77));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focusing_with_the_mouse_following_puts_the_pointer_in_the_middle_of_the_window()
|
||||
-> eyre::Result<()> {
|
||||
let fake = fake_with(&[1]);
|
||||
fake.set_rect(1, &tile(100, 200))?;
|
||||
|
||||
fake.focus(1, true)?;
|
||||
|
||||
assert_eq!(fake.cursor_pos(), Some((200, 525)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focusing_without_the_mouse_following_leaves_the_pointer_alone() -> eyre::Result<()> {
|
||||
let fake = fake_with(&[1]);
|
||||
fake.set_cursor(5, 5);
|
||||
|
||||
fake.focus(1, false)?;
|
||||
|
||||
assert_eq!(fake.cursor_pos(), Some((5, 5)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_window_with_the_focus_leaves_nothing_focused() {
|
||||
let fake = fake_with(&[1]);
|
||||
fake.set_foreground(Some(1));
|
||||
|
||||
fake.close_window_now(1);
|
||||
|
||||
assert_eq!(fake.foreground_window(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_user_does_is_not_a_command() {
|
||||
let fake = fake_with(&[1]);
|
||||
|
||||
fake.move_window_by_user(1, tile(300, 300));
|
||||
fake.set_title(1, "renamed");
|
||||
fake.set_normal(1, false);
|
||||
|
||||
assert!(fake.commands().is_empty());
|
||||
assert_eq!(fake.rect_of(1), Some(tile(300, 300)));
|
||||
let window = fake.window(1).expect("window 1 was opened");
|
||||
assert_eq!(window.title, "renamed");
|
||||
assert!(!window.normal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_are_listed_by_id_and_a_destroyed_one_is_left_out() {
|
||||
let fake = fake_with(&[3, 1, 2]);
|
||||
fake.close_window_now(2);
|
||||
|
||||
let ids: Vec<_> = fake.windows().iter().map(|w| w.id).collect();
|
||||
|
||||
assert_eq!(ids, [1, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_can_be_centered_in_a_rectangle() -> eyre::Result<()> {
|
||||
let fake = FakeBackend::new();
|
||||
|
||||
fake.center_cursor_in(&tile(0, 400))?;
|
||||
|
||||
assert_eq!(fake.cursor_pos(), Some((200, 525)));
|
||||
assert_eq!(fake.commands(), [Command::CenterCursor(tile(0, 400))]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
//! Everything the window manager needs from the desktop, behind one trait.
|
||||
//!
|
||||
//! The window manager logic (windows, containers, workspaces, monitors) never talks to KWin, to
|
||||
//! `/proc` or to D-Bus. It talks to a [`Backend`]. A real backend asks the compositor; the one the
|
||||
//! tests use is [`fake::FakeBackend`], an in-memory desktop that does what it is told and records
|
||||
//! what it was asked.
|
||||
//!
|
||||
//! # The backend is process-wide
|
||||
//!
|
||||
//! The backend is a singleton, like the other globals of this crate, so that a window can be a
|
||||
//! small `Copy` handle that carries only its id: `window.set_position(..)` needs no context passed
|
||||
//! to it. [`set_backend`] installs it once at startup, and [`backend`] returns it. A test that needs
|
||||
//! a private desktop uses [`with_backend`], which overrides the backend for the current thread
|
||||
//! only and puts the previous one back afterwards, so tests cannot leak a desktop into each other.
|
||||
//!
|
||||
//! # Queries and commands
|
||||
//!
|
||||
//! Queries are answered from the backend's own table, which compositor events keep up to date, so
|
||||
//! they never wait for the compositor. A window that has just been closed stays queryable for a
|
||||
//! short time, with [`WindowInfo::alive`] false, so that the event that mentions it can still be
|
||||
//! logged. Commands return once the compositor has accepted them, not once the client has acted on
|
||||
//! them, and an implementation may batch them.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use crate::core::Rect;
|
||||
use color_eyre::eyre;
|
||||
use parking_lot::RwLock;
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub mod fake;
|
||||
|
||||
/// What the compositor currently knows about one window.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct WindowInfo {
|
||||
/// The compositor's id for the window, which is how every other part of komorebi names it.
|
||||
pub id: u32,
|
||||
/// The id of the process that owns the window.
|
||||
pub pid: i32,
|
||||
/// The window's title.
|
||||
pub title: String,
|
||||
/// The Wayland `app_id` (the X11 `WM_CLASS` for a client that runs on XWayland).
|
||||
pub class: String,
|
||||
/// The file name of the executable, read from `/proc/<pid>/exe`.
|
||||
pub exe: String,
|
||||
/// The full path of the executable.
|
||||
pub path: String,
|
||||
/// The window's frame.
|
||||
pub rect: Rect,
|
||||
/// Whether the window is minimized.
|
||||
pub minimized: bool,
|
||||
/// Whether the compositor considers this a normal application window, as opposed to a dialog,
|
||||
/// a splash screen, a utility window, a dock and so on.
|
||||
pub normal: bool,
|
||||
/// False once the window has been destroyed.
|
||||
pub alive: bool,
|
||||
}
|
||||
|
||||
/// A connected monitor, in logical pixels.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct MonitorInfo {
|
||||
/// The compositor's id for the monitor.
|
||||
pub id: u32,
|
||||
/// The name of the output (`DP-1`, `Virtual-0`).
|
||||
pub name: String,
|
||||
/// An identity for the monitor that stays the same across a hot-plug and a restart.
|
||||
pub serial_number_id: String,
|
||||
/// The monitor's bounds.
|
||||
pub size: Rect,
|
||||
/// `size` minus the panels and other areas the compositor reserves.
|
||||
pub work_area: Rect,
|
||||
}
|
||||
|
||||
/// The desktop, as the window manager sees it.
|
||||
///
|
||||
/// This is the **only** way the window manager reaches the compositor. Everything else in the crate
|
||||
/// is testable without one.
|
||||
///
|
||||
/// # Who implements it, who calls it
|
||||
///
|
||||
/// A backend is implemented once per compositor, and by the in-memory [`fake::FakeBackend`]. It is
|
||||
/// called by the window manager, through [`backend`]; nothing else should hold a reference to it.
|
||||
///
|
||||
/// # Contract
|
||||
///
|
||||
/// - Queries never block on the compositor and never fail, except [`Backend::monitors`], which may
|
||||
/// fail when the compositor cannot say.
|
||||
/// - A command about a window that does not exist, or is no longer alive, returns an error. It does
|
||||
/// not panic.
|
||||
/// - A backend is `Send + Sync`: the window manager calls it from several threads.
|
||||
///
|
||||
/// The compiler enforces the first and last parts of the contract that it can see. A backend that
|
||||
/// leaves out a method does not compile:
|
||||
///
|
||||
/// ```rust,compile_fail,E0046
|
||||
/// use komorebi::backend::Backend;
|
||||
///
|
||||
/// struct Nothing;
|
||||
///
|
||||
/// impl Backend for Nothing {}
|
||||
/// ```
|
||||
///
|
||||
/// And neither does one that cannot be shared between threads:
|
||||
///
|
||||
/// ```rust,compile_fail,E0277
|
||||
/// # use std::rc::Rc;
|
||||
/// # use color_eyre::eyre;
|
||||
/// # use komorebi::backend::{Backend, MonitorInfo, WindowInfo};
|
||||
/// # use komorebi::core::Rect;
|
||||
/// struct NotShareable(Rc<u8>);
|
||||
///
|
||||
/// # impl Backend for NotShareable {
|
||||
/// # fn windows(&self) -> Vec<WindowInfo> { vec![] }
|
||||
/// # fn window(&self, _: u32) -> Option<WindowInfo> { None }
|
||||
/// # fn foreground_window(&self) -> Option<u32> { None }
|
||||
/// # fn monitors(&self) -> eyre::Result<Vec<MonitorInfo>> { Ok(vec![]) }
|
||||
/// # fn cursor_pos(&self) -> Option<(i32, i32)> { None }
|
||||
/// # fn set_rect(&self, _: u32, _: &Rect) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn focus(&self, _: u32, _: bool) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn raise(&self, _: u32) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn minimize(&self, _: u32) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn unminimize(&self, _: u32) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn close(&self, _: u32) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn center_cursor_in(&self, _: &Rect) -> eyre::Result<()> { Ok(()) }
|
||||
/// # }
|
||||
/// ```
|
||||
pub trait Backend: Send + Sync + 'static {
|
||||
// ---- queries -------------------------------------------------------------------------------
|
||||
|
||||
/// Returns every window on the desktop that is a candidate for management, ordered by id.
|
||||
fn windows(&self) -> Vec<WindowInfo>;
|
||||
|
||||
/// Returns what is known about the window, or `None` if the compositor has never heard of it.
|
||||
fn window(&self, id: u32) -> Option<WindowInfo>;
|
||||
|
||||
/// Returns the id of the window that has the focus, if any window does.
|
||||
fn foreground_window(&self) -> Option<u32>;
|
||||
|
||||
/// Returns every connected monitor.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the compositor cannot report its outputs.
|
||||
fn monitors(&self) -> eyre::Result<Vec<MonitorInfo>>;
|
||||
|
||||
/// Returns where the pointer is, if the compositor says.
|
||||
fn cursor_pos(&self) -> Option<(i32, i32)>;
|
||||
|
||||
// ---- commands ------------------------------------------------------------------------------
|
||||
|
||||
/// Moves and resizes the window to `rect`, a position and a size.
|
||||
///
|
||||
/// A client may refuse the size (a minimum size, for one), so the frame the window ends up with
|
||||
/// is [`Backend::window_rect`], not `rect`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the window does not exist or is no longer alive.
|
||||
fn set_rect(&self, id: u32, rect: &Rect) -> eyre::Result<()>;
|
||||
|
||||
/// Gives the window the focus, and, if `mouse_follows_focus`, puts the pointer in its middle.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the window does not exist or is no longer alive.
|
||||
fn focus(&self, id: u32, mouse_follows_focus: bool) -> eyre::Result<()>;
|
||||
|
||||
/// Raises the window above the others.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the window does not exist or is no longer alive.
|
||||
fn raise(&self, id: u32) -> eyre::Result<()>;
|
||||
|
||||
/// Minimizes the window.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the window does not exist or is no longer alive.
|
||||
fn minimize(&self, id: u32) -> eyre::Result<()>;
|
||||
|
||||
/// Brings a minimized window back.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the window does not exist or is no longer alive.
|
||||
fn unminimize(&self, id: u32) -> eyre::Result<()>;
|
||||
|
||||
/// Asks the window to close.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the window does not exist or is no longer alive.
|
||||
fn close(&self, id: u32) -> eyre::Result<()>;
|
||||
|
||||
/// Puts the pointer in the middle of `rect`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the compositor refuses to move the pointer.
|
||||
fn center_cursor_in(&self, rect: &Rect) -> eyre::Result<()>;
|
||||
|
||||
// ---- provided ------------------------------------------------------------------------------
|
||||
|
||||
/// Called once as komorebi exits, after the window manager has put back what it moved, so that
|
||||
/// the backend can give up whatever it created itself.
|
||||
///
|
||||
/// The default does nothing. Implementors should not need to override it unless they created
|
||||
/// something in the compositor.
|
||||
fn shutdown(&self) {}
|
||||
|
||||
/// Returns true if and only if the compositor has a live window with this id.
|
||||
fn is_window(&self, id: u32) -> bool {
|
||||
self.window(id).is_some_and(|w| w.alive)
|
||||
}
|
||||
|
||||
/// Returns the window's frame, if the compositor knows the window.
|
||||
fn window_rect(&self, id: u32) -> Option<Rect> {
|
||||
self.window(id).map(|w| w.rect)
|
||||
}
|
||||
|
||||
/// Returns the id of the monitor whose bounds contain the point.
|
||||
fn monitor_from_point(&self, x: i32, y: i32) -> Option<u32> {
|
||||
self.monitors().ok()?.into_iter().find_map(|m| {
|
||||
let (l, t) = (m.size.left, m.size.top);
|
||||
let (r, b) = (l + m.size.right, t + m.size.bottom);
|
||||
(x >= l && x < r && y >= t && y < b).then_some(m.id)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static BACKEND: RwLock<Option<Arc<dyn Backend>>> = RwLock::new(None);
|
||||
|
||||
thread_local! {
|
||||
static OVERRIDE: RefCell<Option<Arc<dyn Backend>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Installs the process-wide backend. Called once at startup.
|
||||
pub fn set_backend(backend: Arc<dyn Backend>) {
|
||||
*BACKEND.write() = Some(backend);
|
||||
}
|
||||
|
||||
/// Returns the backend for this thread: the thread's override if there is one, else the
|
||||
/// process-wide one.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If no backend has been installed. That is a bug in the order of start-up, not a condition at
|
||||
/// run time. Install one with [`set_backend`], or with [`with_backend`] in a test.
|
||||
pub fn backend() -> Arc<dyn Backend> {
|
||||
OVERRIDE
|
||||
.with(|o| o.borrow().clone())
|
||||
.or_else(|| BACKEND.read().clone())
|
||||
.or_else(test_default)
|
||||
.expect(
|
||||
"no backend installed: call backend::set_backend (or backend::with_backend in tests)",
|
||||
)
|
||||
}
|
||||
|
||||
/// The crate's own unit tests get a private, permissive fake per thread when they install nothing,
|
||||
/// so that a test of pure window manager logic needs no set-up. Everything else gets no default.
|
||||
#[cfg(test)]
|
||||
fn test_default() -> Option<Arc<dyn Backend>> {
|
||||
OVERRIDE.with(|o| {
|
||||
let backend: Arc<dyn Backend> = Arc::new(fake::FakeBackend::permissive());
|
||||
*o.borrow_mut() = Some(backend.clone());
|
||||
Some(backend)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn test_default() -> Option<Arc<dyn Backend>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Runs `f` with `backend` as this thread's backend, and puts the previous override back
|
||||
/// afterwards, also when `f` panics.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use std::sync::Arc;
|
||||
///
|
||||
/// use komorebi::backend::Backend;
|
||||
/// use komorebi::backend::backend;
|
||||
/// use komorebi::backend::fake::FakeBackend;
|
||||
/// use komorebi::backend::with_backend;
|
||||
///
|
||||
/// let fake = Arc::new(FakeBackend::with_one_monitor());
|
||||
/// fake.open_window(7, "foot", "foot", "a terminal");
|
||||
///
|
||||
/// let titles = with_backend(fake.clone(), || {
|
||||
/// backend().windows().into_iter().map(|w| w.title).collect::<Vec<_>>()
|
||||
/// });
|
||||
///
|
||||
/// assert_eq!(titles, ["a terminal"]);
|
||||
/// ```
|
||||
pub fn with_backend<R>(backend: Arc<dyn Backend>, f: impl FnOnce() -> R) -> R {
|
||||
struct Restore(Option<Arc<dyn Backend>>);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
OVERRIDE.with(|o| *o.borrow_mut() = self.0.take());
|
||||
}
|
||||
}
|
||||
|
||||
let _restore = Restore(OVERRIDE.with(|o| o.borrow_mut().replace(backend)));
|
||||
f()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use fake::FakeBackend;
|
||||
|
||||
#[test]
|
||||
fn a_thread_that_installs_nothing_gets_a_permissive_fake_in_unit_tests() {
|
||||
let id = 41;
|
||||
|
||||
assert!(backend().window(id).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_backend_overrides_the_backend_and_puts_the_previous_one_back() {
|
||||
let outer = Arc::new(FakeBackend::with_one_monitor());
|
||||
outer.open_window(1, "outer", "outer", "outer");
|
||||
let inner = Arc::new(FakeBackend::with_one_monitor());
|
||||
inner.open_window(2, "inner", "inner", "inner");
|
||||
|
||||
with_backend(outer, || {
|
||||
with_backend(inner, || {
|
||||
assert!(backend().is_window(2));
|
||||
assert!(!backend().is_window(1));
|
||||
});
|
||||
|
||||
assert!(backend().is_window(1));
|
||||
assert!(!backend().is_window(2));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_backend_puts_the_previous_backend_back_when_the_closure_panics() {
|
||||
let outer = Arc::new(FakeBackend::with_one_monitor());
|
||||
outer.open_window(1, "outer", "outer", "outer");
|
||||
|
||||
with_backend(outer, || {
|
||||
let inner = Arc::new(FakeBackend::with_one_monitor());
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
with_backend(inner, || panic!("a test"))
|
||||
}));
|
||||
|
||||
assert!(result.is_err());
|
||||
assert!(backend().is_window(1));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_provided_methods_are_answered_from_the_queries() {
|
||||
let fake = FakeBackend::with_one_monitor();
|
||||
fake.open_window(5, "foot", "foot", "a terminal");
|
||||
|
||||
assert!(fake.is_window(5));
|
||||
assert!(!fake.is_window(6));
|
||||
assert_eq!(fake.window_rect(5), fake.rect_of(5));
|
||||
assert_eq!(fake.monitor_from_point(10, 10), Some(1));
|
||||
assert_eq!(fake.monitor_from_point(5000, 10), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destroyed_window_is_no_longer_a_window_but_can_still_be_asked_about() {
|
||||
let fake = FakeBackend::with_one_monitor();
|
||||
fake.open_window(5, "foot", "foot", "a terminal");
|
||||
|
||||
fake.close_window_now(5);
|
||||
|
||||
assert!(!fake.is_window(5));
|
||||
assert!(fake.window(5).is_some_and(|w| !w.alive));
|
||||
assert!(fake.windows().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -4,5 +4,6 @@
|
||||
#[macro_use]
|
||||
pub mod ring;
|
||||
|
||||
pub mod backend;
|
||||
pub mod core;
|
||||
pub mod lockable_sequence;
|
||||
Reference in new issue
Block a user