feat(wm): tile what the backend reports

With the model in place, the window manager can do its job: load the desktop
from the backend, tile it, and keep it tiled as the compositor reports what
happens to windows. The events are the Windows implementation's, each about one
window and carrying it: a window is shown, destroyed, given the focus, minimized
or restored. A new window gets a container of its own after the focused one, a
closed one leaves whichever workspace has it, a window the user minimizes is out
of the layout until it is restored, and every event ends with the workspace in
front tiled again.

At startup every monitor is loaded, and every open window that is normal, alive
and not minimized goes on the monitor its middle is on. An index from each
managed window to its monitor and workspace is rebuilt around every event, so
that the first event komorebi sees can be the close of a window it picked up at
startup.

Whether a window is managed is, for now, only whether the compositor calls it a
normal window and it is alive; the rules that ignore, manage or float
applications come later. When a window closes, komorebi leaves the choice of the
next focus to KWin unless KWin focuses nothing, so the two do not fight.

The daemon runs this against a backend chosen on the command line.
--fake-backend, an in-memory desktop with one monitor, is the only one, and
without it komorebi exits with a usage error instead of pretending to manage a
desktop it cannot reach.
This commit is contained in:
LGUG2Z committed 2026-10-27 14:07:28 -07:00
1 parent c0345eb0e9
commit 02231d232c
16 files changed
+1469 -13

No files matched your search

Generated
+129
View File
@@ -17,6 +17,15 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "android_system_properties"
version = "0.1.6"
@@ -115,6 +124,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block2"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
dependencies = [
"objc2",
]
[[package]]
name = "bs58"
version = "0.5.1"
@@ -148,6 +166,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chrono"
version = "0.4.45"
@@ -261,6 +285,17 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "ctrlc"
version = "3.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162"
dependencies = [
"dispatch2",
"nix",
"windows-sys",
]
[[package]]
name = "darling"
version = "0.24.1"
@@ -335,6 +370,18 @@ dependencies = [
"serde_core",
]
[[package]]
name = "dispatch2"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
"bitflags 2.13.2",
"block2",
"libc",
"objc2",
]
[[package]]
name = "displaydoc"
version = "0.2.7"
@@ -745,6 +792,7 @@ version = "0.1.0"
dependencies = [
"clap",
"color-eyre",
"ctrlc",
"komorebi-layouts",
"nanoid",
"parking_lot",
@@ -755,6 +803,7 @@ dependencies = [
"serde_with",
"strum",
"tracing",
"tracing-subscriber",
"version",
]
@@ -851,6 +900,15 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "matchers"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
dependencies = [
"regex-automata",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -875,6 +933,27 @@ dependencies = [
"rand",
]
[[package]]
name = "nix"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys",
]
[[package]]
name = "num-conv"
version = "0.2.2"
@@ -899,6 +978,21 @@ dependencies = [
"libc",
]
[[package]]
name = "objc2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "object"
version = "0.40.0"
@@ -1095,6 +1189,23 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rustc-demangle"
version = "0.1.28"
@@ -1516,15 +1627,33 @@ dependencies = [
"tracing-subscriber",
]
[[package]]
name = "tracing-log"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
dependencies = [
"log",
"once_cell",
"tracing-core",
]
[[package]]
name = "tracing-subscriber"
version = "0.3.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
dependencies = [
"matchers",
"nu-ansi-term",
"once_cell",
"regex-automata",
"sharded-slab",
"smallvec",
"thread_local",
"tracing",
"tracing-core",
"tracing-log",
]
[[package]]
+1
View File
@@ -21,6 +21,7 @@ serde = { version = "1", features = ["derive"] }
serde_json = { package = "serde_json_lenient", version = "0.2" }
shadow-rs = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[workspace.metadata.crane]
name = "komorebi-workspace"
+15 -3
View File
@@ -11,8 +11,13 @@ moving and the drawing.
```sh
nix develop
cargo run --bin komorebi --locked -- --version
cargo run --bin komorebi --locked -- --fake-backend
```
`--fake-backend` runs the window manager against an in-memory desktop with one
monitor and no windows, and logs what it does until it is stopped with Ctrl-C.
Without a backend, `komorebi` exits with a usage error.
`nix develop` provides the Rust toolchain that [`rust-toolchain.toml`](rust-toolchain.toml)
selects, a nightly `rustfmt`, and the tools `just check` and the flake's checks
use. With [direnv](https://direnv.net), the [`.envrc`](.envrc) does it on
@@ -25,8 +30,11 @@ without a checkout of the toolchain.
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 model of what it tiles (`monitor`, `workspace`, `container`,
`window`), the `Ring` that holds monitors, workspaces and containers, and the
lists in which some elements are locked in place.
`window`), the window manager that keeps the model (`window_manager`), loads
it from the backend (`desktop`) and changes it when the compositor reports an
event (`window_manager_event`, `process_event`), 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
@@ -58,7 +66,11 @@ describes the trait and where each of its rules is enforced.
The window manager models the desktop as monitors, each with a ring of
workspaces, each with a ring of containers, each with a ring of windows. A
workspace's layout gives each of its containers a tile of the monitor's work
area, and every window of a container is moved onto its tile.
area, and every window of a container is moved onto its tile. At startup the
window manager loads the monitors and the windows that are open from the
backend and tiles them; after that it changes the model when the compositor
reports that a window was shown, closed, focused, minimized or restored, and
tiles the workspace in front again.
## Documentation
+64 -2
View File
@@ -6,8 +6,9 @@ compositor to put it there. Everything it needs from the compositor is behind on
tested, without one.
This page describes that trait, who implements and calls it, where each of its rules is
enforced, and the model of the desktop the window manager tiles. It grows with the code:
each part of the daemon that is added has its place here.
enforced, the model of the desktop the window manager tiles, and how an event about a
window becomes a tile. It grows with the code: each part of the daemon that is added has
its place here.
## Vocabulary
@@ -21,6 +22,8 @@ each part of the daemon that is added has its place here.
that tile.
- **Layout**: the arrangement (BSP, columns, rows, ...) that turns a work area and a
number of containers into one rectangle, a **tile**, for each container.
- **Event**: what the compositor reports about a window: it was shown, destroyed, given
the focus, minimized or restored ([`WindowManagerEvent`]).
- **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)
@@ -74,6 +77,13 @@ area, the layout gives one tile per container, in order, each shrunk by the cont
padding, and every window of a container is asked to move onto its tile with `set_rect`. A
tile is clamped to the work area, so it cannot reach onto a neighboring monitor.
The [`WindowManager`] keeps the monitors, the windows the user minimized (they are in no
workspace until they are restored), and an index from each window it manages to the
monitor and workspace that have it. It is loaded from the backend at startup: every
monitor, and every open window that is normal, alive and not minimized, on the focused
workspace of the monitor its middle is on. After that it changes only when an event comes
in, and each event ends with the workspace in front tiled again.
## The parts
- [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the
@@ -87,6 +97,17 @@ tile is clamped to the work area, so it cannot reach onto a neighboring monitor.
- [`lockable_sequence`](../../komorebi/src/lockable_sequence.rs): inserting, removing and
swapping in a list where some elements are locked in place, which is how a workspace
changes its containers.
- [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the
operations on it (tile the workspace in front, tile every monitor, take a minimized
window out).
- [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from
the backend.
- [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and
[`process_event`](../../komorebi/src/process_event.rs): the events, and what the window
manager does with each.
- [`main.rs`](../../komorebi/src/main.rs): the daemon. It installs the backend chosen on the
command line (`--fake-backend` is the only one), loads and tiles the desktop, and waits to
be stopped.
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
@@ -119,12 +140,42 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
| 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 |
| A locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window` and `test_locked_containers_remove_window` | `containers_mut()` is the `VecDeque` itself |
| A window komorebi does not manage is never moved | framework path: `handle_event` asks [`Window::should_manage`] before it acts on any event but a destroy | `dialogs_and_other_non_normal_windows_are_left_alone` | none |
| A destroyed window leaves whichever workspace has it | framework path: the destroy is looked up in the index of managed windows, which is rebuilt at startup and before and after every event | `a_window_that_was_open_before_komorebi_started_is_removed_when_it_closes` | none |
| The daemon does not start without a backend | startup check: a usage error, exit code 2 | `without_a_backend_komorebi_exits_with_an_error_naming_the_flag` | 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.
## One event, end to end
A window is shown, and ends up on a tile:
1. The event is a [`WindowManagerEvent`]`::Show` carrying the window and the compositor
signal it came from. The end-to-end tests build it and call
[`WindowManager::process_event`], which hands it to `handle_event` and logs how long
that took.
2. `handle_event` asks [`Window::should_manage`], which asks the backend's `window(id)`
whether the window is alive and normal. If it is not, the event changes nothing.
3. The index of managed windows is rebuilt from the containers. If the workspace in front
already has the window, or the index has it on another monitor or workspace, the event
creates nothing.
4. [`Workspace::new_container_for_window`] puts the window in a new container after the
focused one, inserted through `LockableSequence` so that a locked container keeps its
index, and focuses the new container.
5. [`WindowManager::update_focused_workspace`] asks the focused [`Monitor`] to give its
focused workspace the work area, the padding and the offset ([`WorkspaceGlobals`]),
and calls [`Workspace::update`].
6. `Workspace::update` asks the layout for one tile per container, clamps each to the work
area, and calls [`Window::set_position`] for each window, which is the backend's
`set_rect`. The fake puts the window there at once; the frame a window ends up with is
what `window_rect` says afterwards.
7. If the new container is the only one, the window is given the focus with the backend's
`focus`, and the pointer follows it.
8. The index is rebuilt again, so the next event finds the window.
## Where to look in the code
- [`komorebi/src/backend/mod.rs`](../../komorebi/src/backend/mod.rs): the trait.
@@ -136,6 +187,10 @@ breaks the first, and a module that talks to D-Bus directly breaks the second.
`Workspace::update`.
- [`komorebi/src/monitor.rs`](../../komorebi/src/monitor.rs): the work area, padding and
offset a monitor gives the workspace it shows.
- [`komorebi/src/process_event.rs`](../../komorebi/src/process_event.rs): what each event
does.
- [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager
driven end to end against the fake.
[`Backend`]: ../../komorebi/src/backend/mod.rs
[`WindowInfo`]: ../../komorebi/src/backend/mod.rs
@@ -150,3 +205,10 @@ breaks the first, and a module that talks to D-Bus directly breaks the second.
[`WorkspaceGlobals`]: ../../komorebi/src/workspace.rs
[`Container`]: ../../komorebi/src/container.rs
[`Window`]: ../../komorebi/src/window.rs
[`Window::should_manage`]: ../../komorebi/src/window.rs
[`Window::set_position`]: ../../komorebi/src/window.rs
[`Workspace::new_container_for_window`]: ../../komorebi/src/workspace.rs
[`WindowManager`]: ../../komorebi/src/window_manager.rs
[`WindowManager::process_event`]: ../../komorebi/src/process_event.rs
[`WindowManager::update_focused_workspace`]: ../../komorebi/src/window_manager.rs
[`WindowManagerEvent`]: ../../komorebi/src/window_manager_event.rs
+8
View File
@@ -50,3 +50,11 @@ window ended up. A backend keeps a table that the compositor's events update, so
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.
## Why does komorebi not pick the next window to focus when one closes?
Because the compositor already has. When a window is destroyed, KWin activates the window
it considers next and reports that as a focus change, which komorebi follows. If komorebi
also focused a window of its own choosing, the two would fight over the focus. komorebi
focuses the window of its focused container only when the compositor has left nothing
focused.
+2
View File
@@ -10,6 +10,7 @@ version = { path = "../version" }
clap = { workspace = true }
color-eyre = { workspace = true }
ctrlc = { version = "3", features = ["termination"] }
nanoid = "0.4"
parking_lot = "0.12"
pastey = { workspace = true }
@@ -18,6 +19,7 @@ serde = { workspace = true }
serde_with = { version = "3", features = ["schemars_1"] }
strum = { version = "0.28", features = ["derive"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
+216
View File
@@ -0,0 +1,216 @@
//! Loads what the backend reports about the desktop (its monitors, and the windows that are
//! already open) into the window manager.
//!
//! [`WindowManager::init`] calls [`load_monitor_information`] and then
//! [`load_workspace_information`], so that starting komorebi tiles what is on screen. Both read
//! the backend installed for the calling thread ([`crate::backend::backend`]).
//!
//! # Example
//!
//! ```rust
//! use std::sync::Arc;
//!
//! use komorebi::backend::fake::FakeBackend;
//! use komorebi::backend::with_backend;
//! use komorebi::desktop::load_monitor_information;
//! use komorebi::desktop::load_workspace_information;
//! use komorebi::window_manager::WindowManager;
//!
//! let fake = Arc::new(FakeBackend::with_one_monitor());
//! fake.open_window(1, "foot", "foot", "a terminal");
//!
//! let mut wm = WindowManager::new()?;
//! with_backend(fake, || {
//! load_monitor_information(&mut wm)?;
//! load_workspace_information(&mut wm)
//! })?;
//!
//! assert_eq!(wm.monitors().len(), 1);
//! assert!(wm.focused_workspace()?.contains_window(1));
//! # Ok::<(), color_eyre::eyre::Report>(())
//! ```
#![deny(missing_docs)]
use crate::backend::backend;
use crate::container::Container;
use crate::core::Rect;
use crate::monitor::Monitor;
use crate::window::Window;
use crate::window_manager::WindowManager;
use color_eyre::eyre;
fn contains_point(area: &Rect, x: i32, y: i32) -> bool {
x >= area.left && x < area.left + area.right && y >= area.top && y < area.top + area.bottom
}
/// Returns every connected monitor, as the window manager models it, in the backend's order.
///
/// Each [`Monitor`] has the backend's id, bounds and work area, the output's name as its device,
/// the backend's identity as its serial number id, and one empty workspace.
///
/// # Errors
///
/// When the backend cannot report its monitors
/// ([`Backend::monitors`](crate::backend::Backend::monitors)).
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
///
/// use komorebi::backend::fake::FakeBackend;
/// use komorebi::backend::with_backend;
/// use komorebi::desktop::latest_monitor_information;
///
/// let fake = Arc::new(FakeBackend::with_one_monitor());
///
/// let monitors = with_backend(fake, latest_monitor_information)?;
///
/// assert_eq!(monitors.len(), 1);
/// assert_eq!(monitors[0].device, "Virtual-0");
/// assert_eq!(monitors[0].work_area_size.bottom, 1050);
/// assert_eq!(monitors[0].workspaces().len(), 1);
/// # Ok::<(), color_eyre::eyre::Report>(())
/// ```
pub fn latest_monitor_information() -> eyre::Result<Vec<Monitor>> {
Ok(backend()
.monitors()?
.into_iter()
.map(|m| Monitor::new(m.id, m.size, m.work_area, &m.name, &m.serial_number_id))
.collect())
}
/// Adds the monitors the window manager does not have yet, after the ones it has, in the
/// backend's order.
///
/// A monitor is known when the window manager has one with the same serial number id, so
/// loading twice adds nothing the second time, and a known monitor keeps its workspaces.
///
/// # Errors
///
/// When the backend cannot report its monitors
/// ([`Backend::monitors`](crate::backend::Backend::monitors)).
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
///
/// use komorebi::backend::fake::FakeBackend;
/// use komorebi::backend::with_backend;
/// use komorebi::desktop::load_monitor_information;
/// use komorebi::window_manager::WindowManager;
///
/// let fake = Arc::new(FakeBackend::with_one_monitor());
/// let mut wm = WindowManager::new()?;
///
/// with_backend(fake, || {
/// load_monitor_information(&mut wm)?;
/// load_monitor_information(&mut wm)
/// })?;
///
/// assert_eq!(wm.monitors().len(), 1);
/// # Ok::<(), color_eyre::eyre::Report>(())
/// ```
#[tracing::instrument(skip_all)]
pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> {
let all_devices = latest_monitor_information()?;
let monitors = &mut wm.monitors;
'read: for device in all_devices {
for monitor in monitors.elements() {
if device.serial_number_id.eq(&monitor.serial_number_id) {
continue 'read;
}
}
monitors.elements_mut().push_back(device);
}
Ok(())
}
/// Puts the windows that are already open into containers on the focused workspace of the
/// monitor they are on, so that starting komorebi tiles what is on screen.
///
/// A window is on the monitor whose bounds contain its middle. A window that is minimized, that
/// komorebi does not manage ([`Window::should_manage`]), or that is on no monitor is left alone.
/// Nothing is moved: tiling is [`WindowManager::retile_all`]'s job.
///
/// # Errors
///
/// This never returns an error: a window that cannot be placed is skipped.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
///
/// use komorebi::backend::fake::FakeBackend;
/// use komorebi::backend::with_backend;
/// use komorebi::desktop::load_monitor_information;
/// use komorebi::desktop::load_workspace_information;
/// use komorebi::window_manager::WindowManager;
///
/// let fake = Arc::new(FakeBackend::with_one_monitor());
/// fake.open_window(1, "foot", "foot", "a terminal");
/// fake.open_window(2, "foot", "foot", "a dialog");
/// fake.set_normal(2, false);
///
/// let mut wm = WindowManager::new()?;
/// with_backend(fake, || {
/// load_monitor_information(&mut wm)?;
/// load_workspace_information(&mut wm)
/// })?;
///
/// let workspace = wm.focused_workspace()?;
/// assert!(workspace.contains_window(1));
/// assert!(!workspace.contains_window(2));
/// # Ok::<(), color_eyre::eyre::Report>(())
/// ```
#[tracing::instrument(skip_all)]
pub fn load_workspace_information(wm: &mut WindowManager) -> eyre::Result<()> {
let mut valid_window_count = 0;
for info in backend().windows() {
if info.minimized {
continue;
}
let window = Window::from(info.id);
if !window.should_manage() {
continue;
}
let (x, y) = (
info.rect.left + info.rect.right / 2,
info.rect.top + info.rect.bottom / 2,
);
let Some(monitor_idx) = wm
.monitors()
.iter()
.position(|m| contains_point(&m.size, x, y))
else {
continue;
};
let Some(monitor) = wm.monitors_mut().get_mut(monitor_idx) else {
continue;
};
let workspace_idx = monitor.focused_workspace_idx();
if let Some(workspace) = monitor.workspaces_mut().get_mut(workspace_idx) {
let mut container = Container::default();
container.windows_mut().push_back(window);
workspace.containers_mut().push_back(container);
valid_window_count += 1;
}
}
tracing::info!("{valid_window_count} valid windows identified");
Ok(())
}
+15 -2
View File
@@ -1,11 +1,16 @@
//! The komorebi daemon's library: the vocabulary the window manager is written in and the data
//! structures it is built from.
//! The komorebi daemon's library: the vocabulary the window manager is written in, the data
//! structures it is built from, and the window manager.
//!
//! The desktop is modeled as monitors ([`monitor::Monitor`]), each with a ring of workspaces
//! ([`workspace::Workspace`]), each with a ring of containers ([`container::Container`]), each with
//! a ring of windows ([`window::Window`]). A workspace tiles its containers by its layout, and a
//! window is moved by asking the [`backend`].
//!
//! The [`window_manager::WindowManager`] keeps that model. It is loaded from what the backend
//! reports ([`desktop`]) and changed by what the compositor reports about windows
//! ([`window_manager_event`], [`process_event`]).
use color_eyre::eyre;
use std::sync::atomic::AtomicI32;
#[macro_use]
@@ -14,11 +19,19 @@ pub mod ring;
pub mod backend;
pub mod container;
pub mod core;
pub mod desktop;
pub mod lockable_sequence;
pub mod monitor;
pub mod process_event;
pub mod window;
pub mod window_manager;
pub mod window_manager_event;
pub mod workspace;
/// The error the window manager returns when it talks to the desktop: a report, since every
/// failure comes from the one backend.
pub type LibraryError = eyre::Report;
/// The padding, in pixels, between the edge of a monitor's work area and the tiles of its
/// workspaces, for a monitor that sets none of its own. The default for this is 5.
pub static DEFAULT_WORKSPACE_PADDING: AtomicI32 = AtomicI32::new(5);
+123 -6
View File
@@ -1,15 +1,132 @@
//! The komorebi daemon: a tiling window manager for KDE Plasma.
//!
//! The daemon owns the layout of every window and asks KWin, the window
//! manager of Plasma, to put each one where the layout says.
//! The daemon owns the layout of every window and asks the compositor, through a backend, to
//! put each one where the layout says.
//!
//! The backend is chosen on the command line. `--fake-backend` is an in-memory desktop with one
//! monitor and no windows, for development and testing. Without a backend the daemon exits with
//! a usage error. With one, it loads the monitors and the windows that are open, tiles them, and
//! runs until it is stopped with `SIGINT` or `SIGTERM`.
use clap::CommandFactory;
use clap::Parser;
use clap::ValueEnum;
use clap::error::ErrorKind;
use color_eyre::eyre;
use komorebi::backend;
use komorebi::backend::fake::FakeBackend;
use komorebi::window_manager::WindowManager;
use serde::Deserialize;
use std::sync::Arc;
use tracing_subscriber::EnvFilter;
fn setup(log_level: LogLevel) -> eyre::Result<()> {
if std::env::var("RUST_LIB_BACKTRACE").is_err() {
unsafe {
std::env::set_var("RUST_LIB_BACKTRACE", "1");
}
}
color_eyre::install()?;
if std::env::var("RUST_LOG").is_err() {
unsafe {
std::env::set_var(
"RUST_LOG",
match log_level {
LogLevel::Error => "komorebi=error",
LogLevel::Warn => "komorebi=warn",
LogLevel::Info => "komorebi=info",
LogLevel::Debug => "komorebi=debug",
LogLevel::Trace => "komorebi=trace",
},
);
}
}
tracing::subscriber::set_global_default(
tracing_subscriber::fmt::Subscriber::builder()
.with_env_filter(EnvFilter::from_default_env())
.finish(),
)?;
// https://github.com/tokio-rs/tracing/blob/master/examples/examples/panic_hook.rs
// Set a panic hook that records the panic as a `tracing` event at the
// `ERROR` verbosity level.
std::panic::set_hook(Box::new(|panic| {
panic.location().map_or_else(
|| {
tracing::error!(message = %panic);
},
|location| {
tracing::error!(
message = %panic,
panic.file = location.file(),
panic.line = location.line(),
panic.column = location.column(),
);
},
);
}));
Ok(())
}
#[derive(Default, Deserialize, ValueEnum, Clone)]
#[serde(rename_all = "snake_case")]
enum LogLevel {
Error,
Warn,
#[default]
Info,
Debug,
Trace,
}
/// A tiling window manager for KDE Plasma.
#[derive(Parser)]
#[clap(author, about, version = version::LONG_VERSION)]
struct Opts {}
fn main() {
Opts::parse();
struct Opts {
/// Level of log output verbosity
#[clap(long, value_enum, default_value_t=LogLevel::Info)]
log_level: LogLevel,
/// Run against an in-memory desktop with one monitor and no windows, for development and
/// testing. Windows and monitors are not real.
#[clap(long)]
fake_backend: bool,
}
fn main() -> eyre::Result<()> {
let opts: Opts = Opts::parse();
setup(opts.log_level)?;
if opts.fake_backend {
tracing::warn!("running against an in-memory desktop; nothing here is a real window");
backend::set_backend(Arc::new(FakeBackend::with_one_monitor()));
} else {
Opts::command()
.error(
ErrorKind::MissingRequiredArgument,
"a backend has to be chosen: pass --fake-backend to run against an in-memory desktop",
)
.exit();
}
let mut wm = WindowManager::new()?;
wm.init()?;
wm.retile_all()?;
let (quit_sender, quit_receiver) = std::sync::mpsc::channel();
ctrlc::set_handler(move || {
let _ = quit_sender.send(());
})
.expect("could not set ctrl-c handler");
// this thread only waits to be told to stop
let _ = quit_receiver.recv();
tracing::info!("stop signal received");
backend::backend().shutdown();
std::process::exit(130);
}
+160
View File
@@ -0,0 +1,160 @@
//! How the window manager answers what the compositor reports: [`WindowManager::process_event`].
//!
//! An event about a window komorebi does not manage ([`Window::should_manage`]) changes nothing.
//! Otherwise:
//!
//! - **Show**: the window gets a container of its own after the focused one, and the workspace is
//! tiled again. The first window on an empty workspace is given the focus.
//! - **Destroy**: the window is taken out of whichever workspace has it, and if that is the one in
//! front it is tiled again.
//! - **FocusChange**: the workspace is tiled again and the container of the window that has the
//! focus becomes the focused container.
//! - **Minimize**: a window the user minimized leaves its workspace and the rest are tiled
//! again; **Restore** brings it back in a container of its own.
//!
//! [`Window::should_manage`]: crate::window::Window::should_manage
use crate::backend::backend;
use crate::window_manager::WindowManager;
use crate::window_manager_event::WindowManagerEvent;
use color_eyre::eyre;
use tracing::instrument;
/// After a managed window is destroyed KWin activates whatever it considers next. Only when there
/// is nothing to activate does komorebi step in and focus its own selection; otherwise the
/// `FocusChange` for the successor does the reconciling and the two do not fight.
fn should_refocus_after_destroy(foreground: Option<u32>) -> bool {
foreground.is_none()
}
impl WindowManager {
/// Handle an event from the compositor, and log how long it took
pub fn process_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> {
let started = std::time::Instant::now();
let result = self.handle_event(event);
tracing::debug!("handled {event} in {:?}", started.elapsed());
result
}
#[instrument(skip_all)]
fn handle_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> {
let Some(window) = event.window() else {
return Ok(());
};
let window_id = window.id;
// A destroyed window can no longer be asked whether it should be managed, so a removal is
// let through without asking
let is_removal = matches!(event, WindowManagerEvent::Destroy(_, _));
let should_manage = is_removal || window.should_manage();
if !should_manage {
tracing::debug!("ignoring event as window should not be managed: {window}");
return Ok(());
}
tracing::info!(
"processing event: {event} for window {window_id} with notification {}",
event.notification(),
);
// events are read against what is in the containers now, not against what was there when the
// last one finished
self.update_known_window_ids();
match event {
WindowManagerEvent::FocusChange(_, _) => {
let mut is_on_current_workspace = false;
// don't want to trigger the full workspace updates when there are no managed
// containers
if !self.focused_workspace()?.containers().is_empty() {
self.update_focused_workspace(self.mouse_follows_focus, false)?;
}
let workspace = self.focused_workspace_mut()?;
if workspace.contains_window(window_id) {
is_on_current_workspace = true;
}
if is_on_current_workspace {
workspace.focus_container_by_window(window_id)?;
}
}
WindowManagerEvent::Show(_, _) => {
let mut create = true;
if self.focused_workspace()?.contains_window(window_id) {
tracing::debug!("ignoring show event for window already on workspace");
// ignore bogus show events
create = false;
}
if let Some((m_idx, w_idx)) = self.known_window_ids.get(&window_id)
&& let Ok(focused_workspace_idx) = self.focused_workspace_idx()
&& (*m_idx != self.focused_monitor_idx() || *w_idx != focused_workspace_idx)
{
tracing::debug!(
"ignoring show event for window already associated with another workspace"
);
create = false;
}
if create {
let workspace = self.focused_workspace_mut()?;
workspace.new_container_for_window(&window)?;
self.update_focused_workspace(false, false)?;
if self.focused_workspace()?.containers().len() == 1 {
// If after adding this window the workspace only contains 1 window, it
// was previously empty, so give this window the focus
window.focus(self.mouse_follows_focus)?;
}
}
}
WindowManagerEvent::Destroy(_, _) => {
// the window may be on any workspace, not only the one in front
let location = self.known_window_ids.get(&window_id).cloned();
if let Some((m_idx, w_idx)) = location {
let focused = m_idx == self.focused_monitor_idx()
&& Some(w_idx) == self.focused_workspace_idx().ok();
if let Some(workspace) = self
.monitors_mut()
.get_mut(m_idx)
.and_then(|m| m.workspaces_mut().get_mut(w_idx))
{
let _ = workspace.remove_window(window_id);
}
if focused {
let refocus = should_refocus_after_destroy(backend().foreground_window());
self.update_focused_workspace(refocus, refocus)?;
}
}
self.minimized_windows.remove(&window_id);
}
WindowManagerEvent::Minimize(_, _) => {
self.extract_minimized_window(window_id)?;
self.update_focused_workspace(false, false)?;
}
WindowManagerEvent::Restore(_, _) => match self.minimized_windows.remove(&window_id) {
None => {}
Some(window) => {
let workspace = self.focused_workspace_mut()?;
workspace.new_container_for_window(&window)?;
self.update_focused_workspace(false, false)?;
}
},
}
self.update_known_window_ids();
Ok(())
}
}
+37
View File
@@ -190,6 +190,26 @@ impl Window {
pub fn unminimize(self) -> eyre::Result<()> {
backend().unminimize(self.id)
}
/// Whether the window is one komorebi should tile: a window that is still alive and that the
/// compositor considers a normal application window, as opposed to a dialog, a splash screen,
/// a utility window or a dock ([`WindowInfo::normal`](crate::backend::WindowInfo::normal)).
///
/// A window the compositor has no record of is not managed. Windows that are minimized when
/// komorebi starts are not picked up either
/// ([`load_workspace_information`](crate::desktop::load_workspace_information)).
pub fn should_manage(&self) -> bool {
let Some(info) = self.info() else {
return false;
};
if !info.alive {
return false;
}
// dialogs, splash screens, utility windows, docks and the like are not for tiling
info.normal
}
}
#[cfg(test)]
@@ -289,6 +309,23 @@ mod tests {
Ok(())
}
#[test]
fn only_a_normal_window_that_is_alive_is_managed() {
let fake = Arc::new(FakeBackend::with_one_monitor());
fake.open_window(205, "foot", "foot", "a terminal");
fake.open_window(206, "foot", "foot", "a dialog");
fake.set_normal(206, false);
fake.open_window(207, "foot", "foot", "closed");
fake.close_window_now(207);
with_backend(fake, || {
assert!(Window::from(205).should_manage());
assert!(!Window::from(206).should_manage());
assert!(!Window::from(207).should_manage());
assert!(!Window::from(208).should_manage());
});
}
#[test]
fn a_window_serializes_with_what_the_backend_knows_about_it() -> eyre::Result<()> {
let fake = fake_with(204);
+315
View File
@@ -0,0 +1,315 @@
//! [`WindowManager`], everything komorebi tiles, and the operations on it.
//!
//! The window manager keeps the monitors it loaded from the backend
//! ([`WindowManager::init`]), the windows the user minimized, and an index of which monitor and
//! workspace each window it manages is on. It changes when an event comes in
//! ([`WindowManager::process_event`]), and every change ends with the focused workspace tiled
//! again ([`WindowManager::update_focused_workspace`]).
use crate::LibraryError;
use crate::container::Container;
use crate::core::Rect;
use crate::desktop;
use crate::monitor::Monitor;
use crate::ring::Ring;
use crate::window::Window;
use crate::workspace::Workspace;
use color_eyre::eyre;
use color_eyre::eyre::OptionExt;
use std::collections::HashMap;
#[derive(Debug)]
pub struct WindowManager {
pub monitors: Ring<Monitor>,
pub mouse_follows_focus: bool,
pub work_area_offset: Option<Rect>,
pub minimized_windows: HashMap<u32, Window>,
/// Maps each known window id to the (monitor, workspace) index pair managing it
pub known_window_ids: HashMap<u32, (usize, usize)>,
}
impl_ring_elements!(WindowManager, Monitor);
impl WindowManager {
/// Returns a window manager with no monitors: [`WindowManager::init`] loads them from the
/// backend
pub fn new() -> eyre::Result<Self> {
Ok(Self {
monitors: Ring::default(),
mouse_follows_focus: true,
work_area_offset: None,
minimized_windows: HashMap::new(),
known_window_ids: Default::default(),
})
}
/// Loads the monitors and the windows that are already open from the backend
/// ([`desktop`])
#[tracing::instrument(skip(self))]
pub fn init(&mut self) -> Result<(), LibraryError> {
tracing::info!("initializing");
desktop::load_monitor_information(self)?;
desktop::load_workspace_information(self)?;
// the windows that were open already are in containers now; an event about one of them
// (the first thing to happen may be that it closes) has to find it
self.update_known_window_ids();
Ok(())
}
#[tracing::instrument(skip(self))]
pub fn update_focused_workspace(
&mut self,
follow_focus: bool,
trigger_focus: bool,
) -> eyre::Result<()> {
let offset = self.work_area_offset;
let mouse_follows_focus = self.mouse_follows_focus;
self.focused_monitor_mut()
.ok_or_eyre("there is no monitor")?
.update_focused_workspace(offset)?;
if follow_focus
&& trigger_focus
&& let Ok(window) = self.focused_window_mut()
{
window.focus(mouse_follows_focus)?;
}
Ok(())
}
pub fn focused_workspace_idx(&self) -> eyre::Result<usize> {
Ok(self
.focused_monitor()
.ok_or_eyre("there is no monitor")?
.focused_workspace_idx())
}
pub fn focused_workspace(&self) -> eyre::Result<&Workspace> {
self.focused_monitor()
.ok_or_eyre("there is no monitor")?
.focused_workspace()
.ok_or_eyre("there is no workspace")
}
pub fn focused_workspace_mut(&mut self) -> eyre::Result<&mut Workspace> {
self.focused_monitor_mut()
.ok_or_eyre("there is no monitor")?
.focused_workspace_mut()
.ok_or_eyre("there is no workspace")
}
pub fn focused_container(&self) -> eyre::Result<&Container> {
self.focused_workspace()?
.focused_container()
.ok_or_eyre("there is no container")
}
pub fn focused_container_idx(&self) -> eyre::Result<usize> {
Ok(self.focused_workspace()?.focused_container_idx())
}
pub fn focused_container_mut(&mut self) -> eyre::Result<&mut Container> {
self.focused_workspace_mut()?
.focused_container_mut()
.ok_or_eyre("there is no container")
}
pub fn focused_window(&self) -> eyre::Result<&Window> {
self.focused_container()?
.focused_window()
.ok_or_eyre("there is no window")
}
fn focused_window_mut(&mut self) -> eyre::Result<&mut Window> {
self.focused_container_mut()?
.focused_window_mut()
.ok_or_eyre("there is no window")
}
/// Takes a window the user minimized out of the focused workspace, and keeps it until it is
/// restored
pub fn extract_minimized_window(&mut self, window_id: u32) -> eyre::Result<()> {
let workspace = self.focused_workspace_mut()?;
let window = workspace.remove_window(window_id)?;
self.minimized_windows.insert(window_id, window);
Ok(())
}
/// Drop every window that no longer exists from the focused workspace and retile
pub fn reap_invalid_windows(&mut self) -> eyre::Result<()> {
let reaped_count = self.focused_workspace_mut()?.reap_invalid_windows()?;
if reaped_count > 0 {
tracing::debug!("reaped {reaped_count} invalid window(s)");
}
self.update_focused_workspace(false, false)
}
/// Tiles the focused workspace of every monitor
#[tracing::instrument(skip(self))]
pub fn retile_all(&mut self) -> eyre::Result<()> {
let offset = self.work_area_offset;
for monitor in self.monitors_mut() {
let offset = if monitor.work_area_offset.is_some() {
monitor.work_area_offset
} else {
offset
};
let focused_workspace_idx = monitor.focused_workspace_idx();
monitor.update_workspace_globals(focused_workspace_idx, offset);
let workspace = monitor
.focused_workspace_mut()
.ok_or_eyre("there is no workspace")?;
workspace.update()?;
}
Ok(())
}
pub fn update_known_window_ids(&mut self) {
tracing::trace!("updating list of known window_ids");
let mut known_window_ids = HashMap::new();
for (m_idx, monitor) in self.monitors().iter().enumerate() {
for (w_idx, workspace) in monitor.workspaces().iter().enumerate() {
for container in workspace.containers() {
for window in container.windows() {
known_window_ids.insert(window.id, (m_idx, w_idx));
}
}
}
}
if self.known_window_ids != known_window_ids {
// Store new window_ids
self.known_window_ids = known_window_ids;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backend::fake::FakeBackend;
use crate::backend::with_backend;
use std::sync::Arc;
fn setup_window_manager() -> WindowManager {
// Create a new WindowManager instance
let wm = WindowManager::new();
// Window Manager should be created successfully
assert!(wm.is_ok());
wm.unwrap()
}
#[test]
fn test_create_window_manager() {
let _wm = setup_window_manager();
}
fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect {
Rect {
left,
top,
right,
bottom,
}
}
/// The fake's 1920x1080 monitor and a second one to its right, with the windows `ids` open on
/// the first and `id + 1` on the second for each of them
fn two_monitors(ids: &[u32]) -> Arc<FakeBackend> {
let fake = Arc::new(FakeBackend::with_one_monitor());
fake.add_monitor(
2,
"Virtual-1",
rect(1920, 0, 1920, 1080),
rect(1920, 0, 1920, 1080),
);
for id in ids {
fake.open_window(*id, "foot", "foot", "left");
fake.open_window(id + 1, "foot", "foot", "right");
fake.move_window_by_user(id + 1, rect(2000, 100, 800, 600));
}
fake
}
#[test]
fn init_puts_each_open_window_on_the_monitor_it_is_on() -> eyre::Result<()> {
let fake = two_monitors(&[601]);
let mut wm = setup_window_manager();
with_backend(fake, || wm.init())?;
assert_eq!(wm.monitors().len(), 2);
assert_eq!(wm.known_window_ids.get(&601), Some(&(0, 0)));
assert_eq!(wm.known_window_ids.get(&602), Some(&(1, 0)));
assert_eq!(wm.focused_workspace_idx()?, 0);
assert_eq!(wm.focused_container_idx()?, 0);
assert_eq!(wm.focused_container()?.windows().len(), 1);
assert_eq!(wm.focused_window()?.id, 601);
Ok(())
}
#[test]
fn retile_all_tiles_the_focused_workspace_of_every_monitor() -> eyre::Result<()> {
let fake = two_monitors(&[611]);
let mut wm = setup_window_manager();
with_backend(fake.clone(), || {
wm.init()?;
wm.retile_all()
})?;
// the default workspace and container padding are 5 each, and the second monitor has no
// panel
assert_eq!(fake.rect_of(611), Some(rect(10, 10, 1900, 1030)));
assert_eq!(fake.rect_of(612), Some(rect(1930, 10, 1900, 1060)));
Ok(())
}
#[test]
fn reap_invalid_windows_drops_a_closed_window_and_retiles() -> eyre::Result<()> {
let fake = Arc::new(FakeBackend::with_one_monitor());
fake.open_window(621, "foot", "foot", "stays");
fake.open_window(622, "foot", "foot", "closes");
let mut wm = setup_window_manager();
with_backend(fake.clone(), || {
wm.init()?;
fake.close_window_now(622);
wm.reap_invalid_windows()
})?;
assert!(!wm.focused_workspace()?.contains_window(622));
assert_eq!(fake.rect_of(621), Some(rect(10, 10, 1900, 1030)));
Ok(())
}
#[test]
fn a_minimized_window_is_kept_out_of_the_workspace() -> eyre::Result<()> {
let fake = Arc::new(FakeBackend::with_one_monitor());
fake.open_window(631, "foot", "foot", "minimized");
let mut wm = setup_window_manager();
with_backend(fake, || {
wm.init()?;
wm.extract_minimized_window(631)
})?;
assert!(wm.focused_workspace()?.is_empty());
assert_eq!(wm.minimized_windows.get(&631), Some(&Window::from(631)));
Ok(())
}
}
+101
View File
@@ -0,0 +1,101 @@
//! [`WindowManagerEvent`], an event the compositor reported about a window, in the form the
//! window manager handles it
//! ([`WindowManager::process_event`](crate::window_manager::WindowManager::process_event)).
//!
//! An event is about one window and carries it, and the compositor signal it came from
//! ([`SystemNotification`]), which is only for logging.
use crate::window::Window;
use serde::Deserialize;
use serde::Serialize;
use strum::Display;
/// The compositor signal a [`WindowManagerEvent`] came from
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(tag = "type", content = "content")]
pub enum SystemNotification {
KWin(KWinNotification),
}
/// The signals of the KWin script API an event comes from
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum KWinNotification {
/// `workspace.windowAdded`
WindowAdded,
/// `workspace.windowRemoved`
WindowRemoved,
/// `workspace.windowActivated`
WindowActivated,
/// `window.minimizedChanged` to true
WindowMinimized,
/// `window.minimizedChanged` to false
WindowRestored,
}
/// Window events: each carries the window it is about.
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(tag = "type", content = "content")]
pub enum WindowManagerEvent {
FocusChange(SystemNotification, Window),
Show(SystemNotification, Window),
Destroy(SystemNotification, Window),
Minimize(SystemNotification, Window),
Restore(SystemNotification, Window),
}
impl WindowManagerEvent {
/// The window this event is about, if it is about one
pub fn window(&self) -> Option<Window> {
Some(match self {
WindowManagerEvent::FocusChange(_, window)
| WindowManagerEvent::Show(_, window)
| WindowManagerEvent::Destroy(_, window)
| WindowManagerEvent::Minimize(_, window)
| WindowManagerEvent::Restore(_, window) => *window,
})
}
pub fn window_id(&self) -> Option<u32> {
self.window().map(|w| w.id)
}
pub fn process_id(&self) -> Option<i32> {
self.window().map(|w| w.process_id())
}
/// The notification that caused this event, for logging
pub fn notification(&self) -> String {
match self {
WindowManagerEvent::FocusChange(n, _)
| WindowManagerEvent::Show(n, _)
| WindowManagerEvent::Destroy(n, _)
| WindowManagerEvent::Minimize(n, _)
| WindowManagerEvent::Restore(n, _) => match n {
SystemNotification::KWin(k) => k.to_string(),
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_event_names_its_window_and_the_signal_it_came_from() {
let event = WindowManagerEvent::Minimize(
SystemNotification::KWin(KWinNotification::WindowMinimized),
Window::from(301),
);
assert_eq!(event.window(), Some(Window::from(301)));
assert_eq!(event.window_id(), Some(301));
// the crate's unit tests get a permissive fake, which gives a window the pid id + 1000
assert_eq!(event.process_id(), Some(1301));
assert_eq!(event.notification(), "WindowMinimized");
assert_eq!(event.to_string(), "Minimize");
}
}
+22
View File
@@ -153,6 +153,28 @@ impl Workspace {
Ok(())
}
/// Remove every window that no longer exists
#[tracing::instrument(skip(self))]
pub fn reap_invalid_windows(&mut self) -> eyre::Result<usize> {
let mut invalid_window_ids = vec![];
for container in self.containers() {
for window in container.windows() {
if !window.is_valid() {
invalid_window_ids.push(window.id);
}
}
}
for window_id in &invalid_window_ids {
let _ = self.remove_window(*window_id);
}
tracing::debug!("reaping invalid windows {invalid_window_ids:?}");
Ok(invalid_window_ids.len())
}
pub fn remove_window(&mut self, window_id: u32) -> eyre::Result<Window> {
let container_idx = self
.container_idx_for_window(window_id)
+19
View File
@@ -0,0 +1,19 @@
//! `komorebi` refuses to start without a backend, and says how to choose one.
use std::process::Command;
#[test]
fn without_a_backend_komorebi_exits_with_an_error_naming_the_flag() {
let output = Command::new(env!("CARGO_BIN_EXE_komorebi"))
.output()
.expect("komorebi runs");
// the exit code of a usage error
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("a backend has to be chosen: pass --fake-backend"),
"{stderr}"
);
}
+242
View File
@@ -0,0 +1,242 @@
//! The window manager driven end to end against an in-memory desktop: compositor events go in,
//! and what comes out is the geometry of the windows and the commands sent to the backend.
//!
//! Window ids are unique per test (10_001 and up), because tests in one binary share the process
//! and anything process-wide in it.
use komorebi::backend::fake::FakeBackend;
use komorebi::backend::with_backend;
use komorebi::core::Rect;
use komorebi::window::Window;
use komorebi::window_manager::WindowManager;
use komorebi::window_manager_event::KWinNotification;
use komorebi::window_manager_event::SystemNotification;
use komorebi::window_manager_event::WindowManagerEvent;
use std::sync::Arc;
fn added(id: u32) -> WindowManagerEvent {
WindowManagerEvent::Show(
SystemNotification::KWin(KWinNotification::WindowAdded),
Window::from(id),
)
}
fn activated(id: u32) -> WindowManagerEvent {
WindowManagerEvent::FocusChange(
SystemNotification::KWin(KWinNotification::WindowActivated),
Window::from(id),
)
}
fn removed(id: u32) -> WindowManagerEvent {
WindowManagerEvent::Destroy(
SystemNotification::KWin(KWinNotification::WindowRemoved),
Window::from(id),
)
}
fn minimized(id: u32) -> WindowManagerEvent {
WindowManagerEvent::Minimize(
SystemNotification::KWin(KWinNotification::WindowMinimized),
Window::from(id),
)
}
fn restored(id: u32) -> WindowManagerEvent {
WindowManagerEvent::Restore(
SystemNotification::KWin(KWinNotification::WindowRestored),
Window::from(id),
)
}
/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel)
fn desktop() -> (Arc<FakeBackend>, WindowManager) {
desktop_on(FakeBackend::with_one_monitor())
}
fn desktop_on(fake: FakeBackend) -> (Arc<FakeBackend>, WindowManager) {
let fake = Arc::new(fake);
let wm = with_backend(fake.clone(), || {
let mut wm = WindowManager::new().unwrap();
wm.init().unwrap();
wm
});
(fake, wm)
}
fn open(fake: &FakeBackend, id: u32) {
fake.open_window(id, "foot", "foot", &format!("terminal {id}"));
}
fn work_area() -> Rect {
Rect {
left: 0,
top: 0,
right: 1920,
bottom: 1050,
}
}
fn inside(rect: &Rect, area: &Rect) -> bool {
rect.left >= area.left
&& rect.top >= area.top
&& rect.left + rect.right <= area.left + area.right
&& rect.top + rect.bottom <= area.top + area.bottom
}
fn overlap(a: &Rect, b: &Rect) -> bool {
a.left < b.left + b.right
&& b.left < a.left + a.right
&& a.top < b.top + b.bottom
&& b.top < a.top + a.bottom
}
#[test]
fn a_new_window_is_tiled_into_the_work_area() {
let (fake, mut wm) = desktop();
open(&fake, 10_001);
with_backend(fake.clone(), || wm.process_event(added(10_001))).unwrap();
let rect = fake.rect_of(10_001).unwrap();
assert!(
inside(&rect, &work_area()),
"{rect:?} is outside the work area"
);
assert!(
rect.right > 1800 && rect.bottom > 1000,
"{rect:?} does not fill the work area"
);
assert!(wm.focused_workspace().unwrap().contains_window(10_001));
}
#[test]
fn two_windows_split_the_work_area_without_overlapping() {
let (fake, mut wm) = desktop();
open(&fake, 10_011);
open(&fake, 10_012);
with_backend(fake.clone(), || {
wm.process_event(added(10_011))?;
wm.process_event(added(10_012))
})
.unwrap();
let (a, b) = (fake.rect_of(10_011).unwrap(), fake.rect_of(10_012).unwrap());
assert!(inside(&a, &work_area()) && inside(&b, &work_area()));
assert!(!overlap(&a, &b), "{a:?} overlaps {b:?}");
assert!(
a.right < 1000 && b.right < 1000,
"neither should be full width: {a:?} {b:?}"
);
}
#[test]
fn closing_a_window_gives_its_space_to_the_other() {
let (fake, mut wm) = desktop();
open(&fake, 10_021);
open(&fake, 10_022);
with_backend(fake.clone(), || {
wm.process_event(added(10_021))?;
wm.process_event(added(10_022))?;
fake.close_window_now(10_022);
wm.process_event(removed(10_022))
})
.unwrap();
assert!(!wm.focused_workspace().unwrap().contains_window(10_022));
let rect = fake.rect_of(10_021).unwrap();
assert!(
rect.right > 1800,
"the survivor should fill the work area: {rect:?}"
);
}
#[test]
fn dialogs_and_other_non_normal_windows_are_left_alone() {
let (fake, mut wm) = desktop();
open(&fake, 10_041);
fake.set_normal(10_041, false);
fake.clear_commands();
with_backend(fake.clone(), || wm.process_event(added(10_041))).unwrap();
assert!(!wm.focused_workspace().unwrap().contains_window(10_041));
assert!(
fake.commands().is_empty(),
"nothing should have been asked of it"
);
}
#[test]
fn a_minimize_by_the_user_unmanages_the_window_until_it_is_restored() {
let (fake, mut wm) = desktop();
open(&fake, 10_071);
open(&fake, 10_072);
with_backend(fake.clone(), || {
wm.process_event(added(10_071))?;
wm.process_event(added(10_072))?;
wm.process_event(minimized(10_072))
})
.unwrap();
assert!(!wm.focused_workspace().unwrap().contains_window(10_072));
assert!(wm.minimized_windows.contains_key(&10_072));
assert!(fake.rect_of(10_071).unwrap().right > 1800);
with_backend(fake.clone(), || wm.process_event(restored(10_072))).unwrap();
assert!(wm.focused_workspace().unwrap().contains_window(10_072));
assert!(!wm.minimized_windows.contains_key(&10_072));
}
#[test]
fn the_window_given_the_focus_is_in_the_focused_container() {
let (fake, mut wm) = desktop();
open(&fake, 10_601);
open(&fake, 10_602);
with_backend(fake.clone(), || {
wm.process_event(added(10_601))?;
wm.process_event(added(10_602))?;
// the user clicks the first window
fake.set_foreground(Some(10_601));
wm.process_event(activated(10_601))
})
.unwrap();
assert_eq!(wm.focused_container_idx().unwrap(), 0);
assert_eq!(wm.focused_window().unwrap().id, 10_601);
}
#[test]
fn a_window_that_was_open_before_komorebi_started_is_removed_when_it_closes() {
// the first event komorebi sees may be the close of a window it picked up at startup
let fake = FakeBackend::with_one_monitor();
fake.open_window(10_301, "foot", "foot", "terminal 10301");
fake.open_window(10_302, "foot", "foot", "terminal 10302");
let (fake, mut wm) = desktop_on(fake);
with_backend(fake.clone(), || {
fake.close_window_now(10_301);
wm.process_event(removed(10_301))
})
.unwrap();
let remaining: Vec<u32> = wm
.focused_workspace()
.unwrap()
.containers()
.iter()
.flat_map(|c| c.windows().iter().map(|w| w.id))
.collect();
assert_eq!(
remaining,
[10_302],
"a closed window is still in a container"
);
}