From 22c14ba5be8422d32c0fe13c6caa4f3c49ec0f38 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 15:42:16 -0700 Subject: [PATCH] feat(kwin): a border color for each kind of window The stock KDE Rounded Corners has one color for the active window and one for the others, and komorebi colors a window by what it is to the layout: the focused window, the others, a locked container that does not have the focus, a floating window that has it, a stack, a monocle. komorebi's build of the effect takes a color for each window over D-Bus. After every event and message the border manager works out the kind of each window and tells the backend, which sends the effect what changed, and tells it that no window has a color when borders are off. Without that build the borders are the look's two colors, and the backend says so once. komorebic gets border-colour. The fake desktop keeps the colors it was told, and gets window_commands, which leaves the look out of the list of what the window manager asked for. vm-features reads the colors of the kinds of window in a real session. The colors of a stack and of a monocled window are read from the fake and, in vm-features, from the pixels. The border_colours key of komorebi.json is not here: its colors are written as the Colour of komorebi-themes, which the themes (49) bring, and 49 adds the key. The maximize check of vm-features, which was the whole suite, reads a pixel a quarter of the way into the window and not the middle one: komorebi puts the pointer in the middle of the window it focuses, and a screenshot has the arrow on it, white. It read the arrow on most runs once the border effect was loaded. vm-features waits for the panel's room too, where it starts the daemon for its sections B to E: the border colors of section C are read from the pixels around a window, which the panel can cover. --- CONTRIBUTING.md | 16 ++ README.md | 13 +- docs/cli/border-colour.md | 24 ++ docs/dev/ARCHITECTURE.md | 31 ++- docs/dev/DESIGN.md | 20 ++ docs/dev/PLATFORM.md | 30 ++- docs/dev/vm-tests.md | 3 + docs/usage/borders.md | 33 ++- komorebi/src/backend/fake.rs | 72 ++++++ komorebi/src/backend/mod.rs | 34 ++- komorebi/src/border_manager/mod.rs | 176 +++++++++++++- komorebi/src/core/mod.rs | 3 + komorebi/src/kwin/effects.rs | 70 ++++++ komorebi/src/kwin/mod.rs | 22 +- komorebi/src/main.rs | 6 + komorebi/src/process_command.rs | 28 ++- komorebi/src/process_event.rs | 13 +- komorebi/tests/border_colours.rs | 153 ++++++++++++ komorebi/tests/border_commands.rs | 24 ++ komorebi/tests/borders_off.rs | 52 +++++ komorebi/tests/focus.rs | 8 +- komorebi/tests/manage.rs | 4 +- komorebi/tests/maximize_commands.rs | 15 +- komorebi/tests/monocle.rs | 3 +- komorebic/src/main.rs | 30 ++- komorebic/tests/cli.rs | 16 ++ nix/kde-rounded-corners.nix | 8 + .../komorebi-border-colours.patch | 218 ++++++++++++++++++ nix/tests/effects.nix | 5 + nix/tests/vm/lib/komorebi_vm/kde.py | 17 ++ nix/tests/vm/lib/tests/test_kde.py | 27 +++ nix/tests/vm/suites/commands/test.py | 1 + nix/tests/vm/suites/features/default.nix | 5 +- nix/tests/vm/suites/features/test.py | 148 ++++++++++-- nix/tests/vm/suites/look/test.py | 20 +- 35 files changed, 1282 insertions(+), 66 deletions(-) create mode 100644 docs/cli/border-colour.md create mode 100644 komorebi/tests/border_colours.rs create mode 100644 komorebi/tests/borders_off.rs create mode 100644 nix/kde-rounded-corners/komorebi-border-colours.patch diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0d68d68b..559028de 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,6 +87,22 @@ the Rust test that covers the same behavior against the fake desktop. [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) says how they are laid out, how to run one (`just vm NAME`) and how to add one. +## The KWin effects + +The patches in [`nix`](nix) change the KWin effects komorebi drives. Each one +is a derivative work of its effect, which is under the GNU General Public +License version 3, and is under the same license. A patch starts with a header +that describes the change and carries the license notice; `patch` skips the +text before the first `diff` line. To change a patch, make the change in the +effect's source at the version the package pins, and write the whole diff again +with `diff -ruN a b` below the header. The check of the package (in +[`nix/tests/effects.nix`](nix/tests/effects.nix)) builds it and checks the +files it installs, the patch included: + +```sh +nix build .#checks.x86_64-linux.kde-rounded-corners-komorebi-install +``` + ## Continuous integration [`ci.yaml`](.github/workflows/ci.yaml) runs on every pull request and on every diff --git a/README.md b/README.md index fe6cd2f1..f1d9b559 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,8 @@ KWin: - `kde-rounded-corners-komorebi` ([`nix/kde-rounded-corners.nix`](nix/kde-rounded-corners.nix)): KDE Rounded Corners 0.11.0, which draws an outline around each window, built so that KWin - does not load it until it is asked to. + does not load it until it is asked to, and with a patch that lets komorebi + give each window a color of its own. Each one is a package for Linux and an attribute of `overlays.default`, built with the KWin of the nixpkgs the overlay is applied to. @@ -248,8 +249,10 @@ starts it again if it fails. The borders are KWin's: komorebi asks the backend for a look, a border of a width, a radius and two colors, and the KWin backend has the KDE Rounded Corners effect draw it, which the module installs. A border takes room around each -window, so the layout leaves the room while the compositor says it draws one. -`border`, `border-width` and `border-offset` set it. +window, so the layout leaves the room while the compositor says it draws one, and +komorebi gives each window the border color of what it is to the layout: the focused +window, the others, a locked container, a floating window. `border`, `border-colour`, +`border-width` and `border-offset` set it. ## Documentation @@ -274,4 +277,6 @@ are accepted under the terms in [`CONTRIBUTING.md`](CONTRIBUTING.md). The license lets others distribute the source code but not binaries, so there is no public binary cache for what the flake builds: komorebi and the KWin effects are built on each machine that installs them, with their dependencies -from nixpkgs. +from nixpkgs. The patches to the effects in [`nix`](nix) are derivative works +of the effects, which are under the GNU General Public License version 3, and +are under the same license, as the header of each one states. diff --git a/docs/cli/border-colour.md b/docs/cli/border-colour.md new file mode 100644 index 00000000..8930e45c --- /dev/null +++ b/docs/cli/border-colour.md @@ -0,0 +1,24 @@ +```text +Set the color for a window border kind + +Usage: border-colour [OPTIONS] + +Arguments: + + Red + + + Green + + + Blue + +Options: + -w, --window-kind + [default: single] + [possible values: single, stack, monocle, unfocused, unfocused-locked, floating] + + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 831d1313..abcb0155 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -778,6 +778,15 @@ the two colors. [`border_manager::current_look`] makes the [`Look`] of them, and after every retile. A backend remembers the look it applied last and does nothing when it is asked for the same again, so nothing reaches KWin unless a setting changed. +What a window is to the layout decides the color of its border: the focused window of the focused +container on the focused monitor is `Single`, or `Stack` when its container has more than one +window, the focused window of every other container is `Unfocused` or, when the container is +locked, `UnfocusedLocked`, and a floating window is `Floating` while it has the focus and +`Unfocused` otherwise ([`border_manager::window_kinds`]). After every event and every message +[`border_manager::update_colours`] tells the backend the color of each window's border +([`Backend::set_border_colours`]), or that none has one when borders are off, and the backend sends +nothing it sent last time. `BorderColour` sets the color of one kind. + A drawn border takes room. While [`BORDER_DRAWN`] is set, [`Monitor::update_workspace_globals`] gives the workspace the width and the offset of the border, and [`Workspace::update`] takes both off every side of every tile, so the border falls in the gap and not on the window next to it. @@ -791,7 +800,11 @@ into the user's `kwinrc`, group `[Round-Corners]`, through [`Kwinrc`]; loads the (`reconfigureEffect`), since KWin hands an effect the copy of `kwinrc` it read when it started. A look without a border unloads the effect, if komorebi loaded it, and puts the user's settings back. `shutdown` does the same. An effect KWin did not find when it started is reported once and -komorebi goes on without it, with `apply_look` answering false. +komorebi goes on without it, with `apply_look` answering false. The stock effect has one color for +the active window and one for the others; komorebi's build of it takes a color for each window, +over D-Bus, by the UUID KWin knows the window by. `set_border_colours` answers false, and logs it +once, when the effect is the stock one: every border is then the focused or the unfocused color of +the look. [PLATFORM.md](PLATFORM.md#kwin-effects) has the effect, its settings and what was measured. ## The NixOS module @@ -1029,6 +1042,8 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A border takes room around the windows only while the compositor draws it | framework path: [`border_manager::send_notification`] keeps the backend's answer in [`BORDER_DRAWN`], which [`Monitor::update_workspace_globals`] reads | `a_border_the_compositor_draws_takes_room_around_each_window_and_none_is_taken_without_one`, `a_look_is_a_command_once_and_says_whether_borders_are_drawn` | none | | The compositor is asked for the look after every event, every message and every retile, and only a changed look reaches it | framework path: [`WindowManager::process_event`], [`WindowManager::process_command`] and [`WindowManager::retile_all`] call [`border_manager::send_notification`], and a backend compares with the look it applied last | `the_border_messages_set_the_border_and_the_compositor_is_asked_for_it`, `a_look_is_a_command_once_and_says_whether_borders_are_drawn` | the same look applied twice by the KWin backend is not tested | | No outline is drawn inside a window, and a border is never thicker than the effect can draw | framework path: [`kwin::effects`](../../komorebi/src/kwin/effects.rs) sets every inner outline to 0 and clamps the width to 20 | `the_border_is_the_outer_outline_and_nothing_is_drawn_inside_the_window`, `a_border_thicker_than_the_effect_can_draw_is_the_thickest_it_can`, `vm-look` | none | +| Every window has the border color of what it is to the layout, and a window whose kind changes has the new one at once | framework path: [`border_manager::update_colours`] is called after every event and every message, from [`border_manager::window_kinds`], and the backend sends the colors it did not send last time | `the_focused_window_has_the_focus_colour_and_the_others_do_not`, `a_locked_container_that_is_not_focused_is_marked`, `a_stack_has_its_own_colour_when_it_has_the_focus`, `a_monocled_window_has_the_monocle_colour`, `a_floating_window_has_the_floating_colour_while_it_has_the_focus`, `border_colours_are_a_command_only_when_they_change`, `vm-features` (section C) | the stock effect: two colors for every window | +| With borders off no window has a color | framework path: [`border_manager::update_colours`] tells the backend an empty list when `BORDER_ENABLED` is false | `with_borders_off_no_window_has_a_colour` | none | | The effect komorebi loaded is unloaded, and the user's settings of it are put back, when komorebi stops using it or exits | framework path: the effect's state unloads what komorebi loaded, and [`Kwinrc`] puts the group back | `one_group_can_be_put_back_while_the_others_stay_changed`, `vm-look` | `SIGKILL`: the next run puts the settings back when it stops | | Queries never block on the compositor | convention only | none | the KWin backend's `cursor_pos` waits up to 250 ms | | Only the backend module reaches the compositor | convention only | none | none | @@ -1149,14 +1164,21 @@ A window is shown, and ends up on a tile: - [`nix/tests/vm/suites/kwin-restart`](../../nix/tests/vm/suites/kwin-restart/test.py): KWin restarting under the daemon. - [`nix/kde-rounded-corners.nix`](../../nix/kde-rounded-corners.nix): the build of the KWin - effect that draws an outline around each window, and + effect that draws an outline around each window, with + [`komorebi-border-colours.patch`](../../nix/kde-rounded-corners/komorebi-border-colours.patch), + which lets komorebi give each window a color; and [`nix/tests/effects.nix`](../../nix/tests/effects.nix), the checks of the files each effect package installs. - [`komorebi/tests/borders.rs`](../../komorebi/tests/borders.rs) and [`komorebi/tests/border_commands.rs`](../../komorebi/tests/border_commands.rs): the room a drawn border takes, and the messages that set the border, against the fake; + [`komorebi/tests/border_colours.rs`](../../komorebi/tests/border_colours.rs) and + [`komorebi/tests/borders_off.rs`](../../komorebi/tests/borders_off.rs), the color of each + window's border, and none with borders off; [`nix/tests/vm/suites/look`](../../nix/tests/vm/suites/look/test.py), the border in a real - Plasma session, read from the pixels of a screenshot. + Plasma session, read from the pixels of a screenshot, and + [`nix/tests/vm/suites/features`](../../nix/tests/vm/suites/features/test.py), the colors of the + kinds of window. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager driven end to end against the fake. - [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket, @@ -1240,6 +1262,9 @@ A window is shown, and ends up on a tile: [`border_manager::current_look`]: ../../komorebi/src/border_manager/mod.rs [`border_manager::send_notification`]: ../../komorebi/src/border_manager/mod.rs [`BORDER_DRAWN`]: ../../komorebi/src/border_manager/mod.rs +[`Backend::set_border_colours`]: ../../komorebi/src/backend/mod.rs +[`border_manager::window_kinds`]: ../../komorebi/src/border_manager/mod.rs +[`border_manager::update_colours`]: ../../komorebi/src/border_manager/mod.rs [`WindowManager::retile_all`]: ../../komorebi/src/window_manager.rs [`Ring`]: ../../komorebi/src/ring.rs [`Monitor`]: ../../komorebi/src/monitor.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 455ae834..06b7b9bc 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -425,3 +425,23 @@ Because KWin keeps the copy of `kwinrc` it read when it started, and an effect r from that copy, also one loaded a moment ago. Writing the file and loading the effect leaves the effect with the settings the file had at the start of the session. `reconfigureEffect` makes it read them again, so komorebi calls it every time, after loading too. + +## Why does the border effect take a color for each window? + +Because komorebi colors a window by what it is to the layout (the focused window of each monitor, +a stack, a monocle, a floating window, a locked container), and the stock effect knows only "the +active window" and "the others". komorebi's build of KDE Rounded Corners takes a color for each +window over D-Bus, through KWin's name ([PLATFORM.md](PLATFORM.md#the-patches)). Without that +build every kind falls back to the two colors of the look, and komorebi says so once in its log. + +## Why are the effects patched? + +Because the stock effects lack what komorebi needs of them. Each patch leaves the effect +working without komorebi, with the settings the stock effect has: + +| Effect | Patched for | Why | +|---|---|---| +| KDE Rounded Corners | a color for each window, set over D-Bus; drawing a window again when its opacity changes | komorebi colors a window by what it is to the layout (the focused window of each monitor, a stack, a monocle, a floating window, a locked container), and the stock effect has one color for the active window and one for the others. It also draws a window from a texture that has the window's opacity in it, made again only when the contents change or the window is resized, so a change of opacity alone would not show | + +The patches are derivative works of the effects and are under the effects' license, the GNU +General Public License version 3 ([PLATFORM.md](PLATFORM.md#the-patches)). diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 980bf5cc..04bac157 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -227,6 +227,7 @@ What komorebi calls: | `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `AddMatch(s)`, for the signal `NameOwnerChanged` | at start, to see KWin leave the bus and come back | | `org.kde.kglobalaccel` | `/component/kwin` | `org.kde.kglobalaccel.Component` | `invokeShortcut(s)`, with `MoveMouseToFocus` | when the pointer follows the focus | | `org.kde.KWin` | `/Effects` | `org.kde.kwin.Effects` | `isEffectSupported(s)`, `isEffectLoaded(s)`, `loadEffect(s)`, `unloadEffect(s)`, `reconfigureEffect(s)`, with `kwin4_effect_shapecorners` | when the look changes (the border is turned on, off or changed), and at exit | +| `org.kde.KWin` | `/org/komorebi/BorderColours` | `org.komorebi.BorderColours1` | `SetColours(asau)`: the UUID of each window and its color, `0xRRGGBB` | when the color of a window's border changes; the object is komorebi's build of the border effect ([The patches](#the-patches)) | | `org.kde.KWin` | `/KWin` | `org.kde.KWin` | `reconfigure()` | after komorebi changed `kwinrc`, at start and at exit | | `org.kde.KWin` | `/VirtualDesktopManager` | `org.kde.KWin.VirtualDesktopManager` | the properties `desktops` and `count`, `createDesktop(us)`, `setDesktopName(ss)`, `removeDesktop(s)` | when a workspace has no desktop, and at start; `createDesktop` also for the parking desktop, the first time a window is hidden, and `removeDesktop` for it when komorebi stops and for one a killed run left | @@ -401,7 +402,8 @@ The spikes measured the channel alone, with twenty windows in each batch, at 16, ## KWin effects An effect is a plugin of KWin's compositor that changes how windows are drawn. The flake -builds the effects komorebi drives as packages of their own, from source: +builds the effects komorebi drives as packages of their own, from source, with komorebi's +patches (see [The patches](#the-patches)): | Package | Effect | Plugin id | Installed as | |---|---|---|---| @@ -461,6 +463,32 @@ that way, also for an effect loaded a moment before. A screenshot of a session s in the pixels just outside the frame the window has in KWin, on all four sides, in the focused and unfocused colors, and not inside the frame. +### The patches + +Each patch is a derivative work of the effect it changes, and is under the same license, the +GNU General Public License version 3; its header states the license and describes the +change. The check of each package asserts that its patch is in the build. + +[`komorebi-border-colours.patch`](../../nix/kde-rounded-corners/komorebi-border-colours.patch), +for KDE Rounded Corners, makes two changes: + +- **A color for each window.** The stock effect has one outline color for the active window + and one for the others. The patched effect exports an object through KWin's name, which + takes a color for each window: + + | Name | Object | Interface | Member | + |---|---|---|---| + | `org.kde.KWin` | `/org/komorebi/BorderColours` | `org.komorebi.BorderColours1` | `SetColours(asau)` | + + `SetColours` replaces the colors of every window at once: the windows' UUIDs as KWin writes + them (with or without braces), and `0xRRGGBB` values in the same order. A window it does not + name gets the colors of the settings for the active and the other windows. The object is + registered when the effect is loaded, and removed with every color when it is unloaded. +- **A window is drawn again when its opacity changes.** The effect draws a window from a + texture that has the window's opacity in it, and makes the texture again only when the + contents change or the window is resized, so a change of opacity alone would not show. The + patched effect redirects the window again when its opacity changes. + ## Rendering in virtual machines and over RDP At time of writing (2026-10-27): diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index 0c62d3aa..cbc4178f 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -148,6 +148,9 @@ the run. - `effect_supported(name)` and `effect_loaded(name)` ask KWin whether an effect is installed (KWin found it when it started) and loaded, and `unload_effect(name)` unloads one, whoever loaded it. +- `colored_window(title, color)` opens a terminal that is one color all over, and + waits for KWin to have it, and `close_colored_windows()` closes them: a test + reads the color of a pixel of a screenshot, and wants nothing else there. - `pixels` reads a screenshot: `pixels.pixel(image, x, y)` is the color of a pixel, `pixels.near(a, b)` compares two colors within a tolerance, since a compositor blends the edge of what it draws, and `pixels.ring(image, frame, diff --git a/docs/usage/borders.md b/docs/usage/borders.md index e97276ad..61a53063 100644 --- a/docs/usage/borders.md +++ b/docs/usage/borders.md @@ -2,8 +2,9 @@ komorebi puts a colored border around every window. It does not draw it: a KWin effect, KDE Rounded Corners, draws the border outside each window, in the gap between the tiles, and komorebi -tells the effect how wide it is, how round the corners are and which color to use. The border -around the window that has the focus is blue, and the border around every other window is gray. +tells the effect how wide it is, how round the corners are and which color each window's border +has. The border around the window that has the focus is blue, and the border around every other +window is gray. ## Installing the effect @@ -26,6 +27,34 @@ komorebic border disable komorebic border enable ``` +## Colors + +A window's border has the color of what the window is to the layout: + +| Kind | Window | Default | +|---|---|---| +| `single` | the focused window | blue, `66 165 245` | +| `unfocused` | every other window | gray, `128 128 128` | +| `unfocused-locked` | a locked container that does not have the focus | red, `158 8 8` | +| `stack` | a stack that has the focus | green, `0 165 66` | +| `monocle` | a monocled window | pink, `255 51 153` | +| `floating` | a floating window that has the focus | yellow, `245 245 165` | + +[`komorebic border-colour`](../cli/border-colour.md) sets the color of a kind, from its red, +green and blue, each from 0 to 255; without `--window-kind` it sets `single`. + +```sh +komorebic border-colour 255 128 0 +komorebic border-colour --window-kind unfocused 64 64 64 +komorebic border-colour --window-kind floating 200 200 0 +``` + +The stock KDE Rounded Corners has one color for the active window and one for the others. The +build the flake installs also takes a color for each window, which is what lets a locked, a +floating, a stack and a monocled window have colors of their own. With the stock effect every +kind is drawn as `single` or `unfocused`, whichever is closer, and komorebi says so once in its +log. + ## Width and room [`komorebic border-width`](../cli/border-width.md) sets how thick the border is, in pixels: 10 by diff --git a/komorebi/src/backend/fake.rs b/komorebi/src/backend/fake.rs index cc99c53f..c208764e 100644 --- a/komorebi/src/backend/fake.rs +++ b/komorebi/src/backend/fake.rs @@ -67,6 +67,9 @@ pub enum Command { SetWindowWorkspace(u32, usize), /// [`Backend::apply_look`]: the look, when it is not the one applied before. ApplyLook(Look), + /// [`Backend::set_border_colours`]: the colors of each window's border, when they are not the + /// ones given before. + BorderColours(Vec<(u32, u32)>), } #[derive(Default)] @@ -90,6 +93,8 @@ struct State { window_ws: HashMap, /// the desktop each monitor (by id) shows shown: HashMap, + /// the border color each window was last given, `0xRRGGBB` + border_colours: HashMap, /// the look last applied, so that asking for it again is not a command last_look: Option, /// whether the compositor has an effect that draws borders @@ -363,6 +368,12 @@ impl FakeBackend { state.shown.insert(monitor_id, idx); } + /// Returns the border color the window manager last gave this window, `0xRRGGBB`, if it gave + /// it one. + pub fn border_colour_of(&self, id: u32) -> Option { + self.state.lock().border_colours.get(&id).copied() + } + /// Says whether the compositor has an effect that draws borders. Without one, which is how a /// fake starts, [`Backend::apply_look`] answers false however much of a border it is asked /// for, as it does on a machine where the effect is not installed. @@ -375,6 +386,20 @@ impl FakeBackend { self.state.lock().commands.clone() } + /// Returns every command received so far that is not about the look, oldest first. + /// + /// The window manager asks for the look, and tells the colors of the borders, after every event + /// and every message, and the fake records each one that is not what it was told before: a + /// test that checks what the window manager did to the windows exactly compares this, and a + /// test about the look compares [`FakeBackend::commands`]. + pub fn window_commands(&self) -> Vec { + let mut commands = self.commands(); + commands.retain(|command| { + !matches!(command, Command::ApplyLook(_) | Command::BorderColours(_)) + }); + commands + } + /// Forgets the commands received so far. pub fn clear_commands(&self) { self.state.lock().commands.clear(); @@ -578,6 +603,19 @@ impl Backend for FakeBackend { } Ok(state.borders_drawn && look.border.is_some()) } + + fn set_border_colours(&self, colours: &[(u32, u32)]) -> eyre::Result { + let mut state = self.state.lock(); + let colours_now: HashMap = colours.iter().copied().collect(); + // like a real backend: nothing is sent for what has not changed + if state.border_colours != colours_now { + state.border_colours = colours_now; + state + .commands + .push(Command::BorderColours(colours.to_vec())); + } + Ok(true) + } } #[cfg(test)] @@ -885,6 +923,40 @@ mod tests { Ok(()) } + #[test] + fn border_colours_are_a_command_only_when_they_change() -> eyre::Result<()> { + let fake = fake_with(&[1, 2]); + + assert!(fake.set_border_colours(&[(1, 0xFF0000), (2, 0x00FF00)])?); + assert!(fake.set_border_colours(&[(2, 0x00FF00), (1, 0xFF0000)])?); + assert_eq!(fake.border_colour_of(1), Some(0xFF0000)); + assert_eq!(fake.border_colour_of(2), Some(0x00FF00)); + + fake.set_border_colours(&[(2, 0x00FF00)])?; + assert_eq!(fake.border_colour_of(1), None); + assert_eq!( + fake.commands(), + [ + Command::BorderColours(vec![(1, 0xFF0000), (2, 0x00FF00)]), + Command::BorderColours(vec![(2, 0x00FF00)]), + ] + ); + Ok(()) + } + + #[test] + fn window_commands_leave_out_the_look() -> eyre::Result<()> { + let fake = fake_with(&[1]); + + fake.apply_look(&Look::default())?; + fake.focus(1, false)?; + fake.set_border_colours(&[(1, 0xFF0000)])?; + + assert_eq!(fake.commands().len(), 3); + assert_eq!(fake.window_commands(), [Command::Focus(1, false)]); + Ok(()) + } + #[test] fn the_cursor_can_be_centered_in_a_rectangle() -> eyre::Result<()> { let fake = FakeBackend::new(); diff --git a/komorebi/src/backend/mod.rs b/komorebi/src/backend/mod.rs index 7c9162f0..07747c4f 100644 --- a/komorebi/src/backend/mod.rs +++ b/komorebi/src/backend/mod.rs @@ -43,7 +43,8 @@ //! frames, the corners and the shadows. The window manager describes a [`Look`] and the backend //! sees that it is drawn ([`Backend::apply_look`]); the window manager is told whether the //! compositor draws a border, because a border that is drawn takes room around each window, which -//! the layout leaves. +//! the layout leaves. The color of each window's border is another request +//! ([`Backend::set_border_colours`]), which a compositor may not be able to honor. #![deny(missing_docs)] @@ -391,6 +392,37 @@ pub trait Backend: Send + Sync + 'static { Ok(false) } + /// Tells the compositor the color of each window's border, as `(window id, 0xRRGGBB)`: the + /// window manager picks it by what the window is to the layout (the focused window of the + /// focused monitor, a stack, a monocle, a floating window, a locked container). A window that + /// is not named has the border [`Backend::apply_look`] gave it. The colors replace the ones + /// given before, and a backend sends the compositor nothing it sent last time. + /// + /// Returns true if and only if the compositor can give each window a color of its own. When it + /// cannot, the borders are the look's two colors, one for the focused window and one for every + /// other. The default draws nothing and answers false. + /// + /// # Errors + /// + /// When the compositor cannot be reached. + /// + /// # Example + /// + /// ```rust + /// use komorebi::backend::Backend; + /// use komorebi::backend::fake::FakeBackend; + /// + /// let fake = FakeBackend::with_one_monitor(); + /// fake.open_window(7, "foot", "foot", "a terminal"); + /// + /// assert!(fake.set_border_colours(&[(7, 0x42A5F5)])?); + /// assert_eq!(fake.border_colour_of(7), Some(0x42A5F5)); + /// # Ok::<(), color_eyre::eyre::Report>(()) + /// ``` + fn set_border_colours(&self, _colours: &[(u32, u32)]) -> eyre::Result { + Ok(false) + } + // ---- provided ------------------------------------------------------------------------------ /// Called once as komorebi exits, after the window manager has put back what it moved, so that diff --git a/komorebi/src/border_manager/mod.rs b/komorebi/src/border_manager/mod.rs index 7358d902..36a8fdb9 100644 --- a/komorebi/src/border_manager/mod.rs +++ b/komorebi/src/border_manager/mod.rs @@ -8,6 +8,9 @@ //! ([`current_look`]): the border's width, radius and two colors, one for the focused window and //! one for the others. The backend answers whether the borders are drawn, which is kept in //! [`BORDER_DRAWN`]: a drawn border takes room around each window, which the layout leaves. +//! - [`update_colours`] tells the backend the color of each window's border, by what the window +//! is to the layout ([`window_kinds`]). Only komorebi's build of the effect takes them; the +//! stock one draws the look's two colors, one for the active window and one for the others. //! //! The settings are the statics of this module, which the `komorebic border*` commands set and //! the `border*` keys of `komorebi.json` ([`crate::static_config::StaticConfig`]) give their @@ -16,6 +19,8 @@ use crate::backend::BorderLook; use crate::backend::Look; use crate::backend::backend; +use crate::core::WindowKind; +use crate::window_manager::WindowManager; use color_eyre::eyre; use lazy_static::lazy_static; use std::sync::atomic::AtomicBool; @@ -42,6 +47,151 @@ lazy_static! { pub static ref FOCUSED: AtomicU32 = AtomicU32::new(pack(66, 165, 245)); /// The color of the border of every other window, as [`pack`] stores it. pub static ref UNFOCUSED: AtomicU32 = AtomicU32::new(pack(128, 128, 128)); + /// The color of the border of a locked container that does not have the focus. + pub static ref UNFOCUSED_LOCKED: AtomicU32 = AtomicU32::new(pack(158, 8, 8)); + /// The color of the border of a monocled window. + pub static ref MONOCLE: AtomicU32 = AtomicU32::new(pack(255, 51, 153)); + /// The color of the border of a stack that has the focus. + pub static ref STACK: AtomicU32 = AtomicU32::new(pack(0, 165, 66)); + /// The color of the border of a floating window that has the focus. + pub static ref FLOATING: AtomicU32 = AtomicU32::new(pack(245, 245, 165)); +} + +/// Returns the kind of border the stock border effect gives a window of this kind. +/// +/// The stock effect has one color for the active window and one for the others, so `Stack`, +/// `Monocle` and `Floating` are shown as `Single`, and `UnfocusedLocked` as `Unfocused`. +/// +/// ```rust +/// use komorebi::border_manager::outline_kind; +/// use komorebi::core::WindowKind; +/// +/// assert_eq!(outline_kind(WindowKind::Stack), WindowKind::Single); +/// assert_eq!(outline_kind(WindowKind::UnfocusedLocked), WindowKind::Unfocused); +/// ``` +pub fn outline_kind(kind: WindowKind) -> WindowKind { + match kind { + WindowKind::Single | WindowKind::Stack | WindowKind::Monocle | WindowKind::Floating => { + WindowKind::Single + } + WindowKind::Unfocused | WindowKind::UnfocusedLocked => WindowKind::Unfocused, + } +} + +/// Returns the color the settings give a kind of window, as the statics store it (red, green and +/// blue in one number). +fn kind_colour(kind: WindowKind) -> u32 { + match kind { + WindowKind::Single => FOCUSED.load(Ordering::SeqCst), + WindowKind::Stack => STACK.load(Ordering::SeqCst), + WindowKind::Monocle => MONOCLE.load(Ordering::SeqCst), + WindowKind::Floating => FLOATING.load(Ordering::SeqCst), + WindowKind::Unfocused => UNFOCUSED.load(Ordering::SeqCst), + WindowKind::UnfocusedLocked => UNFOCUSED_LOCKED.load(Ordering::SeqCst), + } +} + +/// Returns what the border of each window is to the layout, which decides its color. +/// +/// Only the workspace each monitor shows is looked at. On it, the focused window of the focused +/// container on the focused monitor is `Single`, or `Stack` if its container has more than one +/// window; a monocled window is `Monocle` on the focused monitor; the focused window of any other +/// container is `Unfocused`, or `UnfocusedLocked` if its container is locked; a floating window is +/// `Floating` if it has the focus and `Unfocused` if not. A workspace with a monocle lists the +/// monocled window, and its floating windows only when the floating layer is in front. +pub fn window_kinds(wm: &WindowManager) -> Vec<(u32, WindowKind)> { + let mut out = vec![]; + let focused_monitor_idx = wm.focused_monitor_idx(); + let foreground = backend().foreground_window(); + + let floating = |workspace: &crate::workspace::Workspace, out: &mut Vec<(u32, WindowKind)>| { + for window in workspace.floating_windows() { + let kind = if foreground == Some(window.id) { + WindowKind::Floating + } else { + WindowKind::Unfocused + }; + out.push((window.id, kind)); + } + }; + + for (monitor_idx, monitor) in wm.monitors().iter().enumerate() { + let Some(workspace) = monitor.focused_workspace() else { + continue; + }; + + if let Some(monocle) = &workspace.monocle_container { + if let Some(window) = monocle.focused_window() { + let kind = if monitor_idx == focused_monitor_idx { + WindowKind::Monocle + } else { + WindowKind::Unfocused + }; + out.push((window.id, kind)); + } + + if matches!(workspace.layer, crate::workspace::WorkspaceLayer::Floating) { + floating(workspace, &mut out); + } + + continue; + } + + for (idx, container) in workspace.containers().iter().enumerate() { + let kind = + if idx != workspace.focused_container_idx() || monitor_idx != focused_monitor_idx { + if container.locked { + WindowKind::UnfocusedLocked + } else { + WindowKind::Unfocused + } + } else if container.windows().len() > 1 { + WindowKind::Stack + } else { + WindowKind::Single + }; + + if let Some(window) = container.focused_window() { + out.push((window.id, kind)); + } + } + + floating(workspace, &mut out); + } + + out +} + +/// Returns the border color of each window [`window_kinds`] lists, as `0xRRGGBB`. +pub fn window_colours(wm: &WindowManager) -> Vec<(u32, u32)> { + window_kinds(wm) + .into_iter() + .map(|(id, kind)| { + let (r, g, b) = unpack(kind_colour(kind)); + ( + id, + (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b), + ) + }) + .collect() +} + +/// Tells the backend the color of every window's border, or that no window has one when the +/// borders are off. +/// +/// Called whenever anything about the windows could have changed, after [`send_notification`] +/// (the compositor has to be drawing the borders first). The backend sends nothing it sent last +/// time, and a failure is logged. +pub fn update_colours(wm: &WindowManager) { + let colours = if BORDER_ENABLED.load(Ordering::SeqCst) { + window_colours(wm) + } else { + vec![] + }; + + if let Err(error) = backend().set_border_colours(&colours) { + tracing::warn!("could not set the colour of the borders: {error}"); + } } /// Returns a color as the statics store it: red in the low byte, then green, then blue. @@ -53,8 +203,8 @@ lazy_static! { /// assert_eq!(pack(1, 2, 3), 0x030201); /// assert_eq!(unpack(pack(66, 165, 245)), (66, 165, 245)); /// ``` -pub const fn pack(r: u8, g: u8, b: u8) -> u32 { - (r as u32) | ((g as u32) << 8) | ((b as u32) << 16) +pub const fn pack(r: u32, g: u32, b: u32) -> u32 { + r | (g << 8) | (b << 16) } /// Returns the red, green and blue of a color as the statics store it. The bits above the third @@ -160,6 +310,28 @@ mod tests { assert_eq!((border.width, border.radius), (10, 12)); } + #[test] + fn every_kind_of_window_has_a_color_of_its_own_and_the_stock_effect_has_two() { + let colours: Vec = [ + WindowKind::Single, + WindowKind::Stack, + WindowKind::Monocle, + WindowKind::Floating, + WindowKind::Unfocused, + WindowKind::UnfocusedLocked, + ] + .into_iter() + .map(kind_colour) + .collect(); + let mut distinct = colours.clone(); + distinct.sort_unstable(); + distinct.dedup(); + assert_eq!(distinct.len(), colours.len()); + + assert_eq!(outline_kind(WindowKind::Floating), WindowKind::Single); + assert_eq!(outline_kind(WindowKind::Unfocused), WindowKind::Unfocused); + } + #[test] fn a_negative_width_or_radius_is_none() { let look = look(true, -4, -1, 0, 0); diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 9a5f0d22..db572329 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -240,6 +240,7 @@ pub enum ApplicationIdentifier { Path, } +/// What a window is to the layout, which decides the color of its border #[derive( Copy, Clone, @@ -471,6 +472,8 @@ pub enum SocketMessage { // AltFocusHack(bool), #[serde(alias = "ActiveWindowBorder")] Border(bool), + #[serde(alias = "ActiveWindowBorderColour")] + BorderColour(WindowKind, u32, u32, u32), // #[serde(alias = "ActiveWindowBorderStyle")] // BorderStyle(BorderStyle), BorderWidth(i32), diff --git a/komorebi/src/kwin/effects.rs b/komorebi/src/kwin/effects.rs index 678a72df..e8c07c8f 100644 --- a/komorebi/src/kwin/effects.rs +++ b/komorebi/src/kwin/effects.rs @@ -13,6 +13,9 @@ //! installed later cannot be loaded until the next login. An effect that is not installed is //! reported once in the log, and komorebi carries on without it. //! +//! komorebi's build of the effect (`nix/kde-rounded-corners.nix`) adds what the stock one lacks: a +//! border color for each window, set over D-Bus with [`EffectsState::set_window_colours`]. +//! //! # What is guaranteed, and by what //! //! | Rule | Enforced by | Proof | @@ -42,6 +45,12 @@ pub const ROUNDED_CORNERS: &str = "kwin4_effect_shapecorners"; /// The `kwinrc` group KDE Rounded Corners reads, as its `options.kcfg` names it. const ROUNDED_CORNERS_GROUP: &str = "Round-Corners"; +/// The D-Bus object path at which komorebi's build of the border effect takes a color for each +/// window, on KWin's bus name. +const COLOURS_PATH: &str = "/org/komorebi/BorderColours"; +/// The D-Bus interface of [`COLOURS_PATH`]. +const COLOURS_INTERFACE: &str = "org.komorebi.BorderColours1"; + /// The thickest outline, in pixels, that the border effect can draw. /// /// The effect draws the outer outline only where the window has a shadow (its shader returns early @@ -64,6 +73,11 @@ pub struct EffectsState { loaded_by_us: Vec<&'static str>, /// The effects komorebi found missing, so that each is reported once. missing: Vec<&'static str>, + /// The border color of each window that the border effect was last given. + colours: Option>, + /// Whether the border effect takes a color for each window, once known: only komorebi's build + /// of it does. + colours_supported: Option, } /// Returns the settings of KDE Rounded Corners, as `kwinrc` keys and values, for this border. @@ -182,6 +196,62 @@ impl EffectsState { Ok(self.drawn) } + /// Tells the border effect the border color of each window, given as KWin's UUID of the window + /// and `0xRRGGBB`, and returns true if and only if the effect has them. + /// + /// It returns false when the effect cannot be told: the borders are not being drawn, there is + /// no proxy for the effect's object, or the effect is the stock one, which has a color for the + /// active window and one for the others, from its settings, and nothing else. The first call + /// that finds the stock effect logs it once; later calls return false without asking. The same + /// colors as the last call send nothing. + pub async fn set_window_colours( + &mut self, + connection: &Connection, + colours: &[(String, u32)], + ) -> bool { + if !self.drawn { + // unloaded, and the next time it is loaded it knows nothing + self.colours = None; + return false; + } + + if self.colours_supported == Some(false) { + return false; + } + + if self.colours.as_deref() == Some(colours) { + return true; + } + + let proxy = + match Proxy::new(connection, "org.kde.KWin", COLOURS_PATH, COLOURS_INTERFACE).await { + Ok(proxy) => proxy, + Err(error) => { + tracing::debug!("no proxy for the border colours: {error}"); + return false; + } + }; + + let (names, rgbs): (Vec, Vec) = colours.iter().cloned().unzip(); + match proxy.call_method("SetColours", &(names, rgbs)).await { + Ok(_) => { + self.colours_supported = Some(true); + self.colours = Some(colours.to_vec()); + true + } + Err(error) => { + // a stock build of the effect has no such object; this is the answer, not a fault + self.colours_supported = Some(false); + tracing::info!( + "the border effect does not take a colour for each window ({error}): borders \ + are the focused and the unfocused colour only. komorebi's build of KDE \ + Rounded Corners (nix/kde-rounded-corners.nix) does." + ); + false + } + } + } + /// Gives the effect these settings and has it running, and returns true if and only if it is /// running with them. /// diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index a75234d6..09261fca 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -54,7 +54,9 @@ //! //! Borders are drawn by a KWin effect, KDE Rounded Corners, which the backend configures: it writes //! the effect's settings into the user's `kwinrc`, loads the effect, and takes the settings back -//! out when komorebi exits ([`Backend::apply_look`]). +//! out when komorebi exits ([`Backend::apply_look`]). The effect komorebi builds +//! (`nix/kde-rounded-corners.nix`) also takes a color for each window, which the backend gives it +//! by KWin's UUID of the window ([`Backend::set_border_colours`]). //! //! `docs/dev/PLATFORM.md` has the D-Bus names, the files and the environment variables involved, //! and `docs/dev/DESIGN.md` the reasons for this design. @@ -900,6 +902,24 @@ impl Backend for KWinBackend { })? } + fn set_border_colours(&self, colours: &[(u32, u32)]) -> eyre::Result { + let shared = self.shared.clone(); + + let named: Vec<(String, u32)> = { + let table = shared.table.lock(); + colours + .iter() + .filter_map(|(id, rgb)| table.uuid(*id).map(|uuid| (uuid, *rgb))) + .collect() + }; + + self.shared.block_on(async move { + let connection = shared.connection().await?; + let mut effects = shared.effects.lock().await; + Ok(effects.set_window_colours(&connection, &named).await) + })? + } + fn shutdown(&self) { // the window manager has already restored every window it hid. What is left is the parking // desktop, which KWin would otherwise keep in the user's configuration, and the script, diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 5ab071a2..f288542e 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -234,6 +234,12 @@ fn main() -> eyre::Result<()> { wm.lock().retile_all(false)?; + // and what the windows that are already there look like: their border colors + { + let wm = wm.lock(); + border_manager::update_colours(&wm); + } + listen_for_commands(wm.clone()); listen_for_events(wm.clone()); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index ab1709dd..48093404 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -179,7 +179,9 @@ //! - **Border** sets whether the compositor draws a border around each window, and **BorderWidth** //! and **BorderOffset** the room the layout leaves for it: each asks the backend for the look //! again ([`border_manager::send_notification`]), as does every message once it has been -//! handled. +//! handled. **BorderColour** sets the color of the border of one kind of window +//! ([`WindowKind`]), and every message, once handled, tells the backend the color of each +//! window's border ([`border_manager::update_colours`]). //! - **Retile** tiles the focused workspace of every monitor again, without the resize //! adjustments, and **RetileWithResizeDimensions** with them. //! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name @@ -215,6 +217,7 @@ use crate::core::ScrollingLayoutOptions; use crate::core::SocketMessage; use crate::core::StateQuery; use crate::core::WindowContainerBehaviour; +use crate::core::WindowKind; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; @@ -1941,6 +1944,28 @@ impl WindowManager { border_manager::destroy_all_borders()?; } } + SocketMessage::BorderColour(kind, r, g, b) => match kind { + WindowKind::Single => { + border_manager::FOCUSED.store(border_manager::pack(r, g, b), Ordering::SeqCst); + } + WindowKind::Stack => { + border_manager::STACK.store(border_manager::pack(r, g, b), Ordering::SeqCst); + } + WindowKind::Monocle => { + border_manager::MONOCLE.store(border_manager::pack(r, g, b), Ordering::SeqCst); + } + WindowKind::Unfocused => { + border_manager::UNFOCUSED + .store(border_manager::pack(r, g, b), Ordering::SeqCst); + } + WindowKind::UnfocusedLocked => { + border_manager::UNFOCUSED_LOCKED + .store(border_manager::pack(r, g, b), Ordering::SeqCst); + } + WindowKind::Floating => { + border_manager::FLOATING.store(border_manager::pack(r, g, b), Ordering::SeqCst); + } + }, SocketMessage::BorderWidth(width) => { border_manager::BORDER_WIDTH.store(width, Ordering::SeqCst); border_manager::destroy_all_borders()?; @@ -1962,6 +1987,7 @@ impl WindowManager { )?; border_manager::send_notification(); + border_manager::update_colours(self); tracing::info!("processed command: {message}"); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 39ba632a..e74b0d14 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -48,8 +48,9 @@ //! [`listen_for_events`], one at a time and in the order the backend raised them. //! //! Once an event about a managed window has been handled, every subscriber is sent a notification -//! of it ([`notify_subscribers`]), and the backend is asked for the look again -//! ([`border_manager::send_notification`]), which it does nothing about unless a setting changed. +//! of it ([`notify_subscribers`]), the backend is asked for the look again +//! ([`border_manager::send_notification`]), which it does nothing about unless a setting changed, +//! and told the color of each window's border ([`border_manager::update_colours`]). //! //! [`Window::should_manage`]: crate::window::Window::should_manage //! [`Monitor::assign_windows_to_workspaces`]: crate::monitor::Monitor::assign_windows_to_workspaces @@ -139,7 +140,12 @@ impl WindowManager { // a monitor changed which workspace it shows; nothing to do with any window if let WindowManagerEvent::WorkspaceChange(_, monitor_id, idx) = event { - return self.adopt_workspace_change(monitor_id, idx); + let result = self.adopt_workspace_change(monitor_id, idx); + + // other windows are in view + border_manager::send_notification(); + border_manager::update_colours(self); + return result; } let Some(window) = event.window() else { @@ -510,6 +516,7 @@ impl WindowManager { )?; border_manager::send_notification(); + border_manager::update_colours(self); Ok(()) } diff --git a/komorebi/tests/border_colours.rs b/komorebi/tests/border_colours.rs new file mode 100644 index 00000000..e2396ad4 --- /dev/null +++ b/komorebi/tests/border_colours.rs @@ -0,0 +1,153 @@ +//! The color of each window's border, for what the window is to the layout, against an in-memory +//! desktop. +//! +//! Window ids are in the 30_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::OperationDirection; +use komorebi::core::SocketMessage; +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 focused(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +fn desktop() -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmf-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +fn tiled(first: u32, count: u32) -> (Arc, WindowManager) { + let (fake, mut wm) = desktop(); + with_backend(fake.clone(), || { + for id in first..first + count { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + }); + (fake, wm) +} + +fn command(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +// The colours are the defaults: focused (66, 165, 245), unfocused (128, 128, 128), locked and +// unfocused (158, 8, 8), monocle (255, 51, 153), stack (0, 165, 66), floating (245, 245, 165). + +const SINGLE: u32 = 0x42A5F5; +const UNFOCUSED: u32 = 0x808080; +const UNFOCUSED_LOCKED: u32 = 0x9E0808; +const MONOCLE: u32 = 0xFF3399; +const STACK: u32 = 0x00A542; +const FLOATING: u32 = 0xF5F5A5; + +#[test] +fn the_focused_window_has_the_focus_colour_and_the_others_do_not() { + let (fake, _wm) = tiled(30_201, 3); + + assert_eq!(fake.border_colour_of(30_203), Some(SINGLE)); + assert_eq!(fake.border_colour_of(30_201), Some(UNFOCUSED)); + assert_eq!(fake.border_colour_of(30_202), Some(UNFOCUSED)); +} + +#[test] +fn a_locked_container_that_is_not_focused_is_marked() { + let (fake, mut wm) = tiled(30_211, 3); + + with_backend(fake.clone(), || wm.process_event(focused(30_211))).unwrap(); + command(&fake, &mut wm, SocketMessage::ToggleLock); + assert_eq!( + fake.border_colour_of(30_211), + Some(SINGLE), + "a locked container with the focus is the focused one" + ); + + with_backend(fake.clone(), || wm.process_event(focused(30_213))).unwrap(); + assert_eq!(fake.border_colour_of(30_211), Some(UNFOCUSED_LOCKED)); + assert_eq!(fake.border_colour_of(30_212), Some(UNFOCUSED)); + assert_eq!(fake.border_colour_of(30_213), Some(SINGLE)); +} + +#[test] +fn a_stack_has_its_own_colour_when_it_has_the_focus() { + let (fake, mut wm) = tiled(30_221, 3); + + command( + &fake, + &mut wm, + SocketMessage::StackWindow(OperationDirection::Up), + ); + + // the focused window is now in a container with another + let stacked = wm + .focused_workspace() + .unwrap() + .focused_container() + .unwrap() + .windows() + .len(); + assert_eq!(stacked, 2); + let focused = wm + .focused_workspace() + .unwrap() + .focused_container() + .unwrap() + .focused_window() + .unwrap() + .id; + assert_eq!(fake.border_colour_of(focused), Some(STACK)); +} + +#[test] +fn a_monocled_window_has_the_monocle_colour() { + let (fake, mut wm) = tiled(30_231, 3); + command(&fake, &mut wm, SocketMessage::ToggleMonocle); + + assert_eq!(fake.border_colour_of(30_233), Some(MONOCLE)); +} + +#[test] +fn a_floating_window_has_the_floating_colour_while_it_has_the_focus() { + let (fake, mut wm) = tiled(30_241, 3); + command(&fake, &mut wm, SocketMessage::ToggleFloat); + + // the focused window floats now, and has the focus + assert_eq!(fake.border_colour_of(30_243), Some(FLOATING)); + + // focus goes to a tile: the floating window is one of the others + fake.set_foreground(Some(30_241)); + with_backend(fake.clone(), || wm.process_event(focused(30_241))).unwrap(); + assert_eq!(fake.border_colour_of(30_243), Some(UNFOCUSED)); + assert_eq!(fake.border_colour_of(30_241), Some(SINGLE)); +} diff --git a/komorebi/tests/border_commands.rs b/komorebi/tests/border_commands.rs index ba830457..eb5c6205 100644 --- a/komorebi/tests/border_commands.rs +++ b/komorebi/tests/border_commands.rs @@ -11,6 +11,7 @@ use komorebi::backend::fake::FakeBackend; use komorebi::backend::with_backend; use komorebi::border_manager; use komorebi::core::SocketMessage; +use komorebi::core::WindowKind; use komorebi::window_manager::WindowManager; use std::sync::Arc; use std::sync::atomic::Ordering; @@ -49,6 +50,29 @@ fn the_border_messages_set_the_border_and_the_compositor_is_asked_for_it() { let border: BorderLook = last_look().border.expect("borders are on"); assert_eq!(border.width, 8); + // the colors of the focused window and of the others are in the look, the others are not + send( + &mut wm, + SocketMessage::BorderColour(WindowKind::Single, 10, 20, 30), + ); + send( + &mut wm, + SocketMessage::BorderColour(WindowKind::Unfocused, 40, 50, 60), + ); + send( + &mut wm, + SocketMessage::BorderColour(WindowKind::Floating, 70, 80, 90), + ); + let border = last_look().border.expect("borders are on"); + assert_eq!( + (border.focused, border.unfocused), + ((10, 20, 30), (40, 50, 60)) + ); + assert_eq!( + border_manager::unpack(border_manager::FLOATING.load(Ordering::SeqCst)), + (70, 80, 90) + ); + send(&mut wm, SocketMessage::Border(false)); assert_eq!(last_look(), Look::default()); assert!(!border_manager::BORDER_DRAWN.load(Ordering::SeqCst)); diff --git a/komorebi/tests/borders_off.rs b/komorebi/tests/borders_off.rs new file mode 100644 index 00000000..59b73615 --- /dev/null +++ b/komorebi/tests/borders_off.rs @@ -0,0 +1,52 @@ +//! With borders off, the compositor is told no window has a color; with them on again, it is told. +//! +//! This file has one test because it changes the process-wide border settings, which every other +//! test that tiles windows would see (their layouts would gain or lose room for a border in the middle +//! of the test). + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::SocketMessage; +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; + +#[test] +fn with_borders_off_no_window_has_a_colour() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = std::path::PathBuf::from(format!("/tmp/kmb-off-{}.sock", std::process::id())); + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + for id in [91_001, 91_002] { + fake.open_window(id, "foot", "foot", "terminal"); + with_backend(fake.clone(), || { + wm.process_event(WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + )) + .unwrap(); + }); + } + assert_eq!(fake.border_colour_of(91_002), Some(0x42A5F5)); + + with_backend(fake.clone(), || { + wm.process_command(SocketMessage::Border(false), Vec::new()) + }) + .unwrap(); + assert_eq!(fake.border_colour_of(91_001), None); + assert_eq!(fake.border_colour_of(91_002), None); + + with_backend(fake.clone(), || { + wm.process_command(SocketMessage::Border(true), Vec::new()) + }) + .unwrap(); + assert_eq!(fake.border_colour_of(91_002), Some(0x42A5F5)); +} diff --git a/komorebi/tests/focus.rs b/komorebi/tests/focus.rs index 6267e723..a0c9569b 100644 --- a/komorebi/tests/focus.rs +++ b/komorebi/tests/focus.rs @@ -73,7 +73,7 @@ fn focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing() { ); assert_eq!(focused(&wm), 19_001); - assert_eq!(fake.commands(), [Command::Focus(19_001, true)]); + assert_eq!(fake.window_commands(), [Command::Focus(19_001, true)]); send( &fake, @@ -83,7 +83,7 @@ fn focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing() { assert_eq!(focused(&wm), 19_002); assert_eq!( - fake.commands(), + fake.window_commands(), [Command::Focus(19_001, true), Command::Focus(19_002, true)] ); assert_eq!((fake.rect_of(19_001), fake.rect_of(19_002)), tiles); @@ -143,7 +143,7 @@ fn cycle_focus_goes_round_the_containers_in_order() { assert_eq!(focused(&wm), 19_023, "previous from the first is the last"); assert_eq!( - fake.commands(), + fake.window_commands(), [ Command::Focus(19_021, true), Command::Focus(19_022, true), @@ -186,7 +186,7 @@ fn without_mouse_follows_focus_the_pointer_stays_where_it_is() { ); assert_eq!( - fake.commands(), + fake.window_commands(), [Command::Focus(19_031, false), Command::Focus(19_032, true)] ); assert!(wm.mouse_follows_focus); diff --git a/komorebi/tests/manage.rs b/komorebi/tests/manage.rs index 173d2b7c..6552972b 100644 --- a/komorebi/tests/manage.rs +++ b/komorebi/tests/manage.rs @@ -112,7 +112,7 @@ fn minimize_and_close_ask_the_compositor_about_the_window_that_has_the_focus() { fake.clear_commands(); send(&fake, &mut wm, SocketMessage::Minimize).unwrap(); - assert_eq!(fake.commands(), [Command::Minimize(27_002)]); + assert_eq!(fake.window_commands(), [Command::Minimize(27_002)]); // the window leaves the layout when the compositor reports it minimized, not before assert_eq!(order(&wm), [27_001, 27_002]); with_backend(fake.clone(), || wm.process_event(minimized(27_002))).unwrap(); @@ -121,7 +121,7 @@ fn minimize_and_close_ask_the_compositor_about_the_window_that_has_the_focus() { fake.set_foreground(Some(27_001)); fake.clear_commands(); send(&fake, &mut wm, SocketMessage::Close).unwrap(); - assert_eq!(fake.commands(), [Command::Close(27_001)]); + assert_eq!(fake.window_commands(), [Command::Close(27_001)]); fake.set_foreground(None); assert_eq!( diff --git a/komorebi/tests/maximize_commands.rs b/komorebi/tests/maximize_commands.rs index 9b6fb4d5..7dd78e5b 100644 --- a/komorebi/tests/maximize_commands.rs +++ b/komorebi/tests/maximize_commands.rs @@ -169,7 +169,7 @@ fn a_window_goes_back_in_a_container_of_its_own_at_the_index_it_came_from() { fn while_a_window_is_maximized_what_is_about_the_tiles_does_nothing() { let (fake, mut wm) = desktop_with(&[36_011, 36_012]); send(&fake, &mut wm, SocketMessage::ToggleMaximize); - let asked = fake.commands(); + let asked = fake.window_commands(); for message in [ SocketMessage::MoveWindow(OperationDirection::Left), @@ -203,7 +203,11 @@ fn while_a_window_is_maximized_what_is_about_the_tiles_does_nothing() { .floating_windows() .is_empty() ); - assert_eq!(fake.commands(), asked, "nothing was asked of the backend"); + assert_eq!( + fake.window_commands(), + asked, + "nothing was asked of the backend" + ); } #[test] @@ -214,7 +218,7 @@ fn a_retile_while_a_window_is_maximized_asks_the_compositor_to_maximize_it_again send(&fake, &mut wm, SocketMessage::Retile); - assert_eq!(fake.commands(), [Command::Maximize(36_022, true)]); + assert_eq!(fake.window_commands(), [Command::Maximize(36_022, true)]); assert!(fake.is_maximized(36_022)); } @@ -321,9 +325,10 @@ fn a_maximized_window_is_hidden_with_its_workspace_and_shown_and_focused_with_it with_backend(fake.clone(), || workspace.restore(true)).unwrap(); assert!(!fake.is_hidden(36_072), "the maximized window is shown"); assert!( - fake.commands().ends_with(&[Command::Focus(36_072, true)]), + fake.window_commands() + .ends_with(&[Command::Focus(36_072, true)]), "and has the focus, ahead of the window of the container: {:?}", - fake.commands() + fake.window_commands() ); } diff --git a/komorebi/tests/monocle.rs b/komorebi/tests/monocle.rs index 14fbe9a5..2fba8464 100644 --- a/komorebi/tests/monocle.rs +++ b/komorebi/tests/monocle.rs @@ -184,7 +184,8 @@ fn toggle_monocle_gives_the_focused_window_the_work_area_and_toggling_again_puts assert_eq!(fake.rect_of(35_002), Some(alone(35_009))); assert_ne!(fake.rect_of(35_002), Some(tile)); assert!( - fake.commands().ends_with(&[Command::Focus(35_002, true)]), + fake.window_commands() + .ends_with(&[Command::Focus(35_002, true)]), "the monocle window is given the focus" ); assert_eq!( diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index f52bba59..f914d262 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -66,8 +66,9 @@ //! find by its name; `workspace-layout` and `workspace-tiling` set the layout and the tiling of //! a workspace by its index, and `ensure-workspaces` and `ensure-named-workspaces` give a //! monitor workspaces up to a number, or with names. -//! - `border` sets whether the compositor draws a border around each window, and `border-width` -//! and `border-offset` the room the layout leaves for it. +//! - `border` sets whether the compositor draws a border around each window, `border-colour` the +//! color of the border of a kind of window, and `border-width` and `border-offset` the room the +//! layout leaves for it. //! //! `ignore-rule` and `manage-rule` add a rule that keeps an application out of the layout or //! always in it, `session-float-rule` floats the focused window and every window like it until the @@ -120,6 +121,7 @@ use komorebi_client::Rect; use komorebi_client::Sizing; use komorebi_client::SocketMessage; use komorebi_client::StateQuery; +use komorebi_client::WindowKind; use komorebi_client::replace_env_in_path; use komorebi_client::send_message; use komorebi_client::send_query; @@ -729,6 +731,18 @@ struct Border { boolean_state: BooleanState, } +#[derive(Parser)] +struct BorderColour { + #[clap(value_enum, short, long, default_value = "single")] + window_kind: WindowKind, + /// Red + r: u32, + /// Green + g: u32, + /// Blue + b: u32, +} + #[derive(Parser)] struct BorderWidth { /// Desired width of the window border @@ -1160,6 +1174,10 @@ enum SubCommand { #[clap(arg_required_else_help = true)] #[clap(alias = "active-window-border")] Border(Border), + /// Set the color for a window border kind + #[clap(arg_required_else_help = true)] + #[clap(alias = "active-window-border-colour")] + BorderColour(BorderColour), /// Set the border width #[clap(arg_required_else_help = true)] #[clap(alias = "active-window-border-width")] @@ -1984,6 +2002,14 @@ fn main() -> eyre::Result<()> { SubCommand::Border(args) => { send_message(&SocketMessage::Border(args.boolean_state.into()))?; } + SubCommand::BorderColour(args) => { + send_message(&SocketMessage::BorderColour( + args.window_kind, + args.r, + args.g, + args.b, + ))?; + } SubCommand::BorderWidth(args) => { send_message(&SocketMessage::BorderWidth(args.width))?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 085e6447..f102ac98 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -487,6 +487,21 @@ fn the_border_subcommands_send_what_they_are_given() { &["active-window-border", "enable"], r#"{"type":"Border","content":true}"#, ); + sends( + &["border-colour", "10", "20", "30"], + r#"{"type":"BorderColour","content":["Single",10,20,30]}"#, + ); + sends( + &[ + "border-colour", + "--window-kind", + "unfocused-locked", + "1", + "2", + "3", + ], + r#"{"type":"BorderColour","content":["UnfocusedLocked",1,2,3]}"#, + ); sends( &["border-width", "8"], r#"{"type":"BorderWidth","content":8}"#, @@ -1015,6 +1030,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "adjust-container-padding.md", "adjust-workspace-padding.md", "application-specific-configuration-schema.md", + "border-colour.md", "border-offset.md", "border-width.md", "border.md", diff --git a/nix/kde-rounded-corners.nix b/nix/kde-rounded-corners.nix index face87d3..31126163 100644 --- a/nix/kde-rounded-corners.nix +++ b/nix/kde-rounded-corners.nix @@ -7,6 +7,14 @@ kde-rounded-corners.overrideAttrs (old: { version = "0.11.0"; + # per-window outline colors, set over D-Bus (org.komorebi.BorderColours1): komorebi colors a + # window by what it is to the layout (the focused one on each monitor, a stack, a monocle, a + # floating window, a locked container), which "the active window" cannot say. Without this the + # effect still works, with the colors of the settings for the active and the other windows. The + # patch also redraws a window from a fresh texture when only its opacity changes, which the + # effect's texture would not show otherwise. + patches = (old.patches or [ ]) ++ [ ./kde-rounded-corners/komorebi-border-colours.patch ]; + src = fetchFromGitHub { owner = "matinlotfali"; repo = "KDE-Rounded-Corners"; diff --git a/nix/kde-rounded-corners/komorebi-border-colours.patch b/nix/kde-rounded-corners/komorebi-border-colours.patch new file mode 100644 index 00000000..46fce004 --- /dev/null +++ b/nix/kde-rounded-corners/komorebi-border-colours.patch @@ -0,0 +1,218 @@ +komorebi-border-colours.patch, for KDE Rounded Corners 0.11.0 +(https://github.com/matinlotfali/KDE-Rounded-Corners), applied by +nix/kde-rounded-corners.nix. It gives each window's outer outline the color +komorebi sets for it over D-Bus (org.komorebi.BorderColours1 at +/org/komorebi/BorderColours, on KWin's name org.kde.KWin); a window without one +is drawn with the colors of the settings. It also redirects a window drawn +through the effect again when the window's opacity changes, so that a change +of opacity alone shows. + +This patch is a derivative work of KDE Rounded Corners, which is distributed +under the GNU General Public License version 3, and it is distributed under +the same license. + +SPDX-License-Identifier: GPL-3.0-only + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation, version 3. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with +this program. If not, see . + +diff -ruN a/src/CMakeLists.txt b/src/CMakeLists.txt +--- a/src/CMakeLists.txt 2026-10-26 21:49:20 ++++ b/src/CMakeLists.txt 2026-10-26 21:49:44 +@@ -5,6 +5,7 @@ + Shader.cpp + Window.h + Window.cpp ++ WindowColours.h + TileChecker.h + TileChecker.cpp + FloatColor.h +diff -ruN a/src/Effect.cpp b/src/Effect.cpp +--- a/src/Effect.cpp 2026-10-26 21:49:20 ++++ b/src/Effect.cpp 2026-10-26 23:24:01 +@@ -27,6 +27,7 @@ + #include "Config.h" + #include "Utils.h" + #include "Window.h" ++#include "WindowColours.h" + #include "WindowManager.h" + #if QT_VERSION_MAJOR >= 6 + #include +@@ -87,6 +88,9 @@ + + ShapeCorners::Effect::Effect() + { ++ // komorebi tells this effect which colour each window's border is ++ WindowColours::instance().registerOnBus(); ++ + // Read configuration and initialize the effect. + reconfigure(ReconfigureAll); + +@@ -98,11 +102,33 @@ + m_windowManager = std::make_unique(); + // Connect the windowAdded signal to handle new windows. + connect(KWin::effects, &KWin::EffectsHandler::windowAdded, this, &Effect::windowAdded); ++ // A window drawn through this effect is drawn from a texture that has the window's opacity ++ // in it, and that is made again only when the window's contents change or it is resized: a ++ // change of opacity alone (komorebi's transparency) would not show. Redirect it afresh. ++ const auto refreshOnOpacity = [this](KWin::EffectWindow *kwindow, qreal, qreal) { ++ auto *window = m_windowManager->findWindow(kwindow); ++ if (window == nullptr || !window->hasEffect()) { ++ return; ++ } ++ unredirect(kwindow); ++ redirect(kwindow); ++ setShader(kwindow, m_shaderManager.GetShader().get()); ++ kwindow->addRepaintFull(); ++ }; ++ for (auto *kwindow: KWin::effects->stackingOrder()) { ++ connect(kwindow, &KWin::EffectWindow::windowOpacityChanged, this, refreshOnOpacity); ++ } ++ connect(KWin::effects, &KWin::EffectsHandler::windowAdded, this, ++ [this, refreshOnOpacity](KWin::EffectWindow *kwindow) { ++ connect(kwindow, &KWin::EffectWindow::windowOpacityChanged, this, refreshOnOpacity); ++ }); + } + } + + ShapeCorners::Effect::~Effect() + { ++ WindowColours::instance().unregisterFromBus(); ++ + // If the shader manager is valid, then the effect has been active, so some cleanup is needed. + if (m_shaderManager.IsValid()) { + // Restore Breeze outline setting when effect is unloaded: +diff -ruN a/src/Shader.cpp b/src/Shader.cpp +--- a/src/Shader.cpp 2026-10-26 21:49:20 ++++ b/src/Shader.cpp 2026-10-26 21:49:44 +@@ -5,6 +5,7 @@ + #include "Config.h" + #include "Utils.h" + #include "Window.h" ++#include "WindowColours.h" + #include "WindowConfig.h" + #if QT_VERSION_MAJOR >= 6 + #include +@@ -160,8 +161,10 @@ + m_shader->setUniform(m_shader_secondOutlineColor1, secondOutline.color1.toQColor()); + m_shader->setUniform(m_shader_secondOutlineColor2, secondOutline.color2.toQColor()); + m_shader->setUniform(m_shader_secondOutlineAngle, secondOutline.angle); +- m_shader->setUniform(m_shader_outerOutlineColor1, outerOutline.color1.toQColor()); +- m_shader->setUniform(m_shader_outerOutlineColor2, outerOutline.color2.toQColor()); ++ // a colour komorebi gave this window wins over the active and inactive settings ++ const auto given = ShapeCorners::WindowColours::instance().colourFor(window.w); ++ m_shader->setUniform(m_shader_outerOutlineColor1, given ? *given : outerOutline.color1.toQColor()); ++ m_shader->setUniform(m_shader_outerOutlineColor2, given ? *given : outerOutline.color2.toQColor()); + m_shader->setUniform(m_shader_outerOutlineAngle, outerOutline.angle); + } else { + const QColor transparent(0, 0, 0, 0); +diff -ruN a/src/WindowColours.h b/src/WindowColours.h +--- a/src/WindowColours.h 1969-12-31 16:00:00 ++++ b/src/WindowColours.h 2026-10-26 23:12:15 +@@ -0,0 +1,98 @@ ++/** ++ * @file WindowColours.h ++ * @brief Per-window colours for the outer outline, set from outside over D-Bus (komorebi). ++ * ++ * A tiling window manager knows better than "the active window" which windows are what: the ++ * focused one on each monitor, a stack, a monocled window, a floating window, a locked container. ++ * It says so, and this effect draws the outer outline of each window it has a colour for in that ++ * colour. Windows it has none for are drawn as the settings say. ++ * ++ * The object is on the session bus at /org/komorebi/BorderColours, interface ++ * org.komorebi.BorderColours1, reached through KWin's own name (org.kde.KWin). ++ */ ++ ++#pragma once ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#if QT_VERSION_MAJOR >= 6 ++#include ++#include ++#else ++#include ++#endif ++ ++namespace ShapeCorners ++{ ++ class WindowColours final : public QObject ++ { ++ Q_OBJECT ++ Q_CLASSINFO("D-Bus Interface", "org.komorebi.BorderColours1") ++ ++ public: ++ static WindowColours &instance() ++ { ++ static WindowColours colours; ++ return colours; ++ } ++ ++ void registerOnBus() ++ { ++ QDBusConnection::sessionBus().registerObject(QStringLiteral("/org/komorebi/BorderColours"), this, ++ QDBusConnection::ExportAllSlots); ++ } ++ ++ void unregisterFromBus() ++ { ++ QDBusConnection::sessionBus().unregisterObject(QStringLiteral("/org/komorebi/BorderColours")); ++ m_colours.clear(); ++ } ++ ++ /// The colour this window's outer outline is to be drawn in, if it was given one ++ [[nodiscard]] ++ std::optional colourFor(const KWin::EffectWindow *window) const ++ { ++ if (m_colours.isEmpty()) { ++ return std::nullopt; ++ } ++ const auto found = m_colours.constFind(window->internalId()); ++ if (found == m_colours.constEnd()) { ++ return std::nullopt; ++ } ++ return *found; ++ } ++ ++ public Q_SLOTS: ++ /// Replace the colours of every window at once: window uuids (as KWin writes them, with or ++ /// without braces) and 0xRRGGBB values, in step. Windows not named go back to the settings. ++ void SetColours(const QStringList &windows, const QList &rgb) ++ { ++ QHash colours; ++ for (qsizetype i = 0; i < windows.size() && i < rgb.size(); ++i) { ++ const auto id = QUuid::fromString(windows[i]); ++ if (!id.isNull()) { ++ colours.insert(id, QColor::fromRgb(rgb[i] & 0xFFFFFF)); ++ } ++ } ++ ++ if (colours == m_colours) { ++ return; ++ } ++ m_colours = colours; ++ ++ for (auto *window: KWin::effects->stackingOrder()) { ++ window->addRepaintFull(); ++ } ++ } ++ ++ private: ++ QHash m_colours; ++ }; ++} // namespace ShapeCorners diff --git a/nix/tests/effects.nix b/nix/tests/effects.nix index e6c96a5b..d7c72918 100644 --- a/nix/tests/effects.nix +++ b/nix/tests/effects.nix @@ -50,6 +50,11 @@ in fail "$needed resolves to '$found', not to the KWin of this nixpkgs (${kwin})" echo "ok: $needed is ${kwin}/lib/$needed" + # komorebi's patch: the interface that takes a color for each window + grep -q -a -F org.komorebi.BorderColours1 "$plugin" || + fail "the plugin has no org.komorebi.BorderColours1: komorebi-border-colours.patch is not in it" + echo "ok: the plugin has org.komorebi.BorderColours1" + touch $out ''; } diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index 0bd87456..3f430586 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -241,6 +241,23 @@ class Kde: """ self.sh(f"setsid nohup {command} > {shlex.quote(log)} 2>&1 < /dev/null &") + def colored_window(self, title: str, color: str, timeout: float = 30) -> None: + """Opens a window that is one color all over, titled `title`, and waits for KWin to have it. + + The window is a `foot` terminal with a background of `color` (`rrggbb`) that is not + see-through, running `sleep 3000`: a test that wants to read its pixels from a screenshot + wants one color and nothing else, and [`Kde.close_colored_windows`][] finds it by the + command it runs, since NixOS wraps programs and their process names are not what they seem. + """ + words = f"foot -T {shlex.quote(title)} -o colors-dark.background={color}" + self.spawn(f"{words} -o colors-dark.alpha=1.0 sleep 3000") + self.wait_for(lambda: self.wid(title) != "", timeout=timeout) + + def close_colored_windows(self) -> None: + """Closes every window [`Kde.colored_window`][] opened, and waits until they are gone.""" + self.run("pkill -f 'sleep 3000'") + self.wait_for(lambda: self.run("pgrep -f 'sleep 3000'")[0] != 0, timeout=10) + def systemctl(self, *args: str) -> str: """Runs `systemctl --user` as the test user.""" return self.as_user("systemctl --user " + " ".join(args)) diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index db423e3b..cc8b009f 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -657,6 +657,33 @@ def test_unload_effect_asks_kwin_over_the_session_bus(machine: FakeMachine) -> N assert "kwin4_effect_shapecorners" in command +def test_a_colored_window_is_a_foot_of_one_color_that_the_session_waits_for( + machine: FakeMachine, +) -> None: + machine.reply("kdotool search --name", output="{abc}\n") + kde = Kde(machine, "main") + + kde.colored_window("red", "ff0000") + + spawn = next(command for command in machine.commands if "setsid nohup" in command) + assert "foot -T red -o colors-dark.background=ff0000 -o colors-dark.alpha=1.0 sleep 3000" in ( + inner(spawn) + ) + assert "WAYLAND_DISPLAY=wayland-main" in spawn + + +def test_close_colored_windows_kills_what_ran_sleep_and_waits_for_them_to_go( + machine: FakeMachine, +) -> None: + machine.reply("pgrep", status=1) + kde = Kde(machine, "main") + + kde.close_colored_windows() + + assert "pkill -f 'sleep 3000'" in inner(machine.commands[0]) + assert "pgrep -f 'sleep 3000'" in inner(machine.commands[1]) + + def test_a_kwin_script_is_loaded_run_and_unloaded_and_its_reports_returned( machine: FakeMachine, ) -> None: diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index bb0b942f..c80f9d1a 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -328,6 +328,7 @@ toggle-mouse-follows-focus border enable border-width 8 border-offset 1 +border-colour --window-kind single 10 20 30 border disable session-float-rule session-float-rules diff --git a/nix/tests/vm/suites/features/default.nix b/nix/tests/vm/suites/features/default.nix index 91ff32cb..f2a97096 100644 --- a/nix/tests/vm/suites/features/default.nix +++ b/nix/tests/vm/suites/features/default.nix @@ -1,5 +1,8 @@ { tier = "slow"; kind = "session"; - timeoutMinutes = 15; + timeoutMinutes = 20; + # The module installs the effects and its unit starts komorebi when the session does. The first + # section uses that daemon; the others stop it and run the unit themselves, once for each + # feature. } diff --git a/nix/tests/vm/suites/features/test.py b/nix/tests/vm/suites/features/test.py index 96ed6a7b..f1bce62e 100644 --- a/nix/tests/vm/suites/features/test.py +++ b/nix/tests/vm/suites/features/test.py @@ -1,15 +1,33 @@ -# What komorebi does that is on the screen of a real compositing session, read from screenshots: the -# session guest draws, and the daemon is the module's unit, as on a user's machine. A headless KWin -# cannot draw, so what the compositor puts on top can only be told here. +# What komorebi on Windows does itself and komorebi on KDE has the compositor do, in a real Plasma +# session whose machine has the effects installed (the module does that): what is on the screen, +# read from screenshots, not what komorebi wrote. Each feature is a section, and a run of the +# daemon: # -# A. toggle-maximize the window fills the work area, is the one on top, and goes back to its -# tile +# A toggle-maximize: the window fills the work area, is the one on top, and goes back to its +# tile. It runs on the daemon the session started with the module's unit, as on a user's +# machine; the sections after it stop that daemon and start their own runs +# C border colors: every kind of window has its own: the focused window, the others, a locked +# container that does not have the focus, a stack and a monocled window that have it, and a +# floating window that has it # -# `komorebi/tests/maximize.rs` and `maximize_commands.rs` check what the window manager does against -# the fake; this checks that KWin's own maximize does it. +# Every window is a `foot` of one color all over (`Kde.colored_window`), and a color is read at the +# pixels just outside the frame of the window (`pixels.ring`). `komorebi/tests/maximize.rs` and +# `maximize_commands.rs` check what the window manager does with a maximize against the fake; +# section A checks that KWin's own maximize does it. import time -from komorebi_vm import Checks, Kde +from komorebi_vm import Checks, Kde, pixels + +UNIT = "komorebi.service" +ROUNDED_CORNERS = "kwin4_effect_shapecorners" + +BLUE = (0, 0, 255) +SINGLE = (66, 165, 245) +UNFOCUSED = (128, 128, 128) +LOCKED = (158, 8, 8) +STACK = (0, 165, 66) +MONOCLE = (255, 51, 153) +FLOATING = (245, 245, 165) start_all() machine.wait_for_unit("multi-user.target") @@ -17,7 +35,47 @@ machine.wait_for_unit("multi-user.target") checks = Checks() kde = Kde.session(machine, scale=SCALE) -BLUE = (0, 0, 255) + +def answering() -> bool: + return kde.run("komorebic monitor-information")[0] == 0 + + +def start_komorebi() -> None: + kde.systemctl("start", UNIT) + kde.wait_for(answering, timeout=60) + # The shell's panel takes room from the windows a while after the shell has made it, and the + # daemon learns that up to a second later. The windows are opened after that: before it they + # are tiled under the panel and then again, and the ring is read in between. + kde.wait_for_panel_room() + # the effects are written, loaded and told to read their settings as the daemon starts + time.sleep(2) + + +def stop_komorebi() -> None: + kde.systemctl("stop", UNIT) + kde.close_colored_windows() + + +def windows() -> None: + """Opens a red, a green and a blue window, in that order, and waits for them to be tiled.""" + for title, color in (("red", "ff0000"), ("green", "00ff00"), ("blue", "0000ff")): + kde.colored_window(title, color) + time.sleep(1) + kde.wait_for(lambda: kde.managed() == 3, timeout=30) + time.sleep(2) + + +def ring_is(title: str, color: tuple[int, int, int]) -> bool: + """Returns true if and only if the window with this title has a ring of `color` just outside + its frame, in a screenshot taken now.""" + wid = kde.wid(title) + return wid != "" and pixels.ring(kde.shot(f"ring-{title}"), kde.rect(wid), color) == [] + + +def focus(title: str) -> None: + """Gives the window the focus, and waits until komorebi has it focused too.""" + kde.activate(kde.wid(title)) + kde.wait_for(lambda: kde.focused_title() == title, timeout=10) def near(pixel: object, want: tuple[int, int, int], tolerance: int = 14) -> bool: @@ -26,10 +84,6 @@ def near(pixel: object, want: tuple[int, int, int], tolerance: int = 14) -> bool return all(abs(got - wanted) <= tolerance for got, wanted in zip(pixel, want, strict=True)) -def answering() -> bool: - return kde.run("komorebic monitor-information")[0] == 0 - - def open_window(title: str, background: str) -> None: """Opens a terminal with a plain background, so that a screenshot says which window is on top.""" kde.spawn( @@ -83,15 +137,18 @@ maximized = kde.rect(blue) checks.check( f"the focused window fills the work area (blue is {maximized}, the area is {area})", filled ) + +# a pixel that is not the middle of the window: komorebi puts the pointer there (mouse follows +# focus), and a screenshot has the white arrow on it image = kde.shot("maximized") print(f" the screenshot is {image.size[0]}x{image.size[1]}") -middle = image.getpixel( +inside = image.getpixel( ( - min(maximized.x + maximized.w // 2, image.width - 1), - min(maximized.y + maximized.h // 2, image.height - 1), + min(maximized.x + maximized.w // 4, image.width - 1), + min(maximized.y + maximized.h // 4, image.height - 1), ) ) -checks.check(f"and is the one on top ({middle})", near(middle, BLUE)) +checks.check(f"and is the one on top ({inside})", near(inside, BLUE)) workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] checks.check( "komorebi's state has it as the maximized window, out of its containers", @@ -110,4 +167,61 @@ checks.check( workspace["maximized_window"] is None and len(workspace["containers"]["elements"]) == 3, ) + +# the session started the module's unit when it logged in: section A used its daemon, and the +# sections after it start their own runs +stop_komorebi() + +print("== C. border colors") +start_komorebi() +windows() +checks.check( + "komorebi's build of the border effect is on the bus (it takes a color for each window)", + kde.run( + "busctl --user introspect org.kde.KWin /org/komorebi/BorderColours | grep -q SetColours" + )[0] + == 0, +) +checks.check( + "the focused window has the focus color", + kde.wait_for(lambda: ring_is("blue", SINGLE), timeout=15), +) +checks.check("the others have the unfocused one", ring_is("green", UNFOCUSED)) + +# a locked container that does not have the focus +focus("red") +kde.komorebic("toggle-lock") +focus("blue") +checks.check( + "a locked container that does not have the focus is marked", + kde.wait_for(lambda: ring_is("red", LOCKED), timeout=15), +) +focus("red") +kde.komorebic("toggle-lock") +focus("blue") + +# a stack that has the focus: blue goes into the container on its left +kde.komorebic("stack", "left") +checks.check( + "a stack with the focus has the stack color", + kde.wait_for(lambda: ring_is("blue", STACK), timeout=15), +) +kde.komorebic("unstack") + +# a monocled window +kde.komorebic("toggle-monocle") +checks.check( + "a monocled window has the monocle color", + kde.wait_for(lambda: ring_is("blue", MONOCLE), timeout=15), +) +kde.komorebic("toggle-monocle") + +# a floating window that has the focus +kde.komorebic("toggle-float") +checks.check( + "a floating window with the focus has the floating color", + kde.wait_for(lambda: ring_is("blue", FLOATING), timeout=15), +) +stop_komorebi() + checks.finish() diff --git a/nix/tests/vm/suites/look/test.py b/nix/tests/vm/suites/look/test.py index ee28a13d..64ee69f8 100644 --- a/nix/tests/vm/suites/look/test.py +++ b/nix/tests/vm/suites/look/test.py @@ -7,8 +7,7 @@ # A the borders, as they are by default: the ring is outside the frame on all four sides # B the commands that change them: the effect follows, and takes the border away and back # -# Every window is a `foot` of one color all over, `sleep 3000` inside it: NixOS wraps programs, so -# the process names are not what they seem. +# Every window is a `foot` of one color all over (`Kde.colored_window`). import time from komorebi_vm import Checks, Kde, Rect, daemon, pixels @@ -41,17 +40,6 @@ def asked(title: str) -> Rect | None: return daemon.asked(machine.execute(f"cat {LOG}")[1], title) -def colored_window(title: str, color: str) -> None: - command = f"foot -T {title} -o colors-dark.background={color} -o colors-dark.alpha=1.0" - kde.spawn(f"{command} sleep 3000") - kde.wait_for(lambda: kde.wid(title) != "", timeout=30) - - -def close_windows() -> None: - kde.run("pkill -f 'sleep 3000'") - kde.wait_for(lambda: kde.run("pgrep -f 'sleep 3000'")[0] != 0, timeout=10) - - def start_komorebi() -> None: kde.systemctl("start", UNIT) kde.wait_for(answering, timeout=60) @@ -65,7 +53,7 @@ def start_komorebi() -> None: def stop_komorebi() -> None: kde.systemctl("stop", UNIT) - close_windows() + kde.close_colored_windows() print("== the effect is installed, and not loaded by anyone") @@ -104,9 +92,9 @@ checks.check( checks.check("the corner radius is the border radius", rc.get("Size") == "10") print("== A. two windows, side by side") -colored_window("red", "ff0000") +kde.colored_window("red", "ff0000") time.sleep(1) -colored_window("blue", "0000ff") +kde.colored_window("blue", "0000ff") checks.check("komorebi tiles both", kde.wait_for(lambda: kde.managed() == 2, timeout=30)) time.sleep(3) red, blue = kde.wid("red"), kde.wid("blue")