From 2c35e4bb6fe959fd6f1c3dc8ac14adb59e18879f Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 15:36:39 -0700 Subject: [PATCH] feat(kwin): borders drawn by the compositor komorebi draws no border. KWin's KDE Rounded Corners effect does, outside each window in the gap the layout leaves, and komorebi says how it looks. The window manager describes a Look (a border with a width, a radius and two colors) and asks the backend for it with Backend::apply_look after every event, message and retile. The backend answers whether borders are being drawn, and the layout leaves room around the windows only while they are: a border with no effect to draw it takes none. The KWin backend writes the effect's settings into the user's kwinrc, with every inner outline off (the effect's default draws one over the title bar), loads the effect when borders are on and has it read them again. It unloads the effect and puts the user's settings back when the borders go or komorebi exits. The module installs the effect (effects.borders), which is built to stay unloaded until komorebi asks, and vm-look reads the pixels around two windows in a real session. The session library of the VM tests also waits for the panel of the Plasma shell now: a window komorebi tiles before the panel is made is tiled under it, which hides the bottom of its border from a screenshot. Kde.wait_for_panel_room waits until the daemon's work area is not the whole of its monitor, which is the daemon having learned that the panel takes room, and vm-look calls it where the daemon starts, before the windows open. The shell makes its panel and KWin takes room for it a while later, which the daemon learns of up to a second after, so a daemon that tiles in between puts the windows under the panel and tiles them again, and a screenshot taken between the two shows frames as high as the screen. It is a wait and not a check, since a session that is too slow, as TCG often is, may never take the room. komorebic gets border, border-width and border-offset, and visible-windows. komorebi.json takes the same settings as border, border_width and border_offset, and border_radius, which has no command. The module warns when config asks for borders and the effect is not installed. --- README.md | 40 ++- docs/cli/border-offset.md | 14 + docs/cli/border-width.md | 14 + docs/cli/border.md | 14 + docs/cli/visible-windows.md | 10 + docs/dev/ARCHITECTURE.md | 103 ++++++- docs/dev/DESIGN.md | 53 ++++ docs/dev/PLATFORM.md | 74 ++++- docs/dev/vm-tests.md | 21 +- docs/example-configurations.md | 3 + docs/index.md | 1 + docs/installation.md | 11 +- docs/komorebi.example.json | 3 + docs/usage/borders.md | 68 +++++ docs/usage/configuration.md | 18 +- flake.nix | 11 + komorebi/src/backend/fake.rs | 55 ++++ komorebi/src/backend/mod.rs | 93 +++++++ komorebi/src/border_manager/mod.rs | 169 ++++++++++++ komorebi/src/core/mod.rs | 9 + komorebi/src/kwin/effects.rs | 334 +++++++++++++++++++++++ komorebi/src/kwin/kwinrc.rs | 62 ++++- komorebi/src/kwin/mod.rs | 33 ++- komorebi/src/lib.rs | 3 + komorebi/src/main.rs | 13 +- komorebi/src/monitor.rs | 21 +- komorebi/src/process_command.rs | 42 +++ komorebi/src/process_event.rs | 6 +- komorebi/src/static_config.rs | 86 +++++- komorebi/src/window_manager.rs | 6 +- komorebi/src/workspace.rs | 104 ++++++- komorebi/tests/border_commands.rs | 59 ++++ komorebi/tests/border_config.rs | 97 +++++++ komorebi/tests/borders.rs | 73 +++++ komorebi/tests/config_parity.rs | 6 +- komorebic/src/main.rs | 64 ++++- komorebic/tests/cli.rs | 37 +++ nix/kde-rounded-corners.nix | 26 ++ nix/komorebi-options.nix | 22 +- nix/nixos-module.nix | 39 ++- nix/tests/effects.nix | 55 ++++ nix/tests/komorebi-example.nix | 3 + nix/tests/nixos-module.nix | 87 +++++- nix/tests/vm/lib/komorebi_vm/__init__.py | 6 +- nix/tests/vm/lib/komorebi_vm/kde.py | 96 ++++++- nix/tests/vm/lib/komorebi_vm/pixels.py | 46 ++++ nix/tests/vm/lib/tests/test_kde.py | 108 ++++++++ nix/tests/vm/lib/tests/test_pixels.py | 65 +++++ nix/tests/vm/suites/commands/test.py | 5 + nix/tests/vm/suites/look/default.nix | 8 + nix/tests/vm/suites/look/test.py | 174 ++++++++++++ nix/tests/vm/suites/module/default.nix | 5 +- schema.json | 35 +++ 53 files changed, 2546 insertions(+), 64 deletions(-) create mode 100644 docs/cli/border-offset.md create mode 100644 docs/cli/border-width.md create mode 100644 docs/cli/border.md create mode 100644 docs/cli/visible-windows.md create mode 100644 docs/usage/borders.md create mode 100644 komorebi/src/border_manager/mod.rs create mode 100644 komorebi/src/kwin/effects.rs create mode 100644 komorebi/tests/border_commands.rs create mode 100644 komorebi/tests/border_config.rs create mode 100644 komorebi/tests/borders.rs create mode 100644 nix/kde-rounded-corners.nix create mode 100644 nix/tests/effects.nix create mode 100644 nix/tests/vm/lib/komorebi_vm/pixels.py create mode 100644 nix/tests/vm/lib/tests/test_pixels.py create mode 100644 nix/tests/vm/suites/look/default.nix create mode 100644 nix/tests/vm/suites/look/test.py diff --git a/README.md b/README.md index e5f4ef4a..fe6cd2f1 100644 --- a/README.md +++ b/README.md @@ -67,8 +67,10 @@ 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 backend that reaches KWin through a script it runs and edits - the one setting of KWin's it needs in the user's `kwinrc` and the parking desktop - it hides the back of a stack and the windows behind a monocle on (`kwin`), + the settings of KWin's it needs in the user's `kwinrc`, the parking desktop it + hides the back of a stack and the windows behind a monocle on, and the borders + it has KWin draw (`kwin`), the border settings and the look they make + (`border_manager`), the model of what it tiles (`monitor`, `workspace`, `container`, `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 @@ -92,6 +94,22 @@ The layouts, which turn a work area and a number of containers into a rectangle for each, are `komorebi-layouts` from [komorebi](https://github.com/LGUG2Z/komorebi), a git dependency at the revision `Cargo.toml` pins. +## KWin effects + +The flake also builds the KWin effects komorebi drives, which are not part of +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. + +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. +[`nix/tests/effects.nix`](nix/tests/effects.nix) checks the files each package +installs. [`docs/dev/PLATFORM.md`](docs/dev/PLATFORM.md#kwin-effects) has what +they need from KWin. + ## Checks `just check` runs the formatting check, clippy with warnings denied, the tests, @@ -102,9 +120,10 @@ TOML and Nix formatting, the tests under `cargo nextest`, and `nixos-module-eval`, which evaluates the NixOS module in real NixOS systems, on Linux and on an Apple silicon Mac, `schema-fresh`, which compares the schemas and the options made from them with the Rust types, and `nix-options-validation`, -which checks the example configuration, in Nix and in JSON, against the schema. On Linux it also boots every VM test, which -needs KVM. A Mac runs the tests against the fake desktop, since KWin only exists -on Linux. `nix fmt` formats every file the checks look at. +which checks the example configuration, in Nix and in JSON, against the schema. +On Linux it also builds the KWin effects and checks their files, and boots every +VM test, which needs KVM. A Mac runs the tests against the fake desktop, since +KWin only exists on Linux. `nix fmt` formats every file the checks look at. The VM tests boot NixOS with Plasma and run a real KWin, on machines configured with the NixOS module, so every one of them runs komorebi as the module installs @@ -226,6 +245,12 @@ On NixOS, the module [`nix/nixos-module.nix`](nix/nixos-module.nix) runs the daemon as a systemd user unit that the Plasma session starts, and systemd 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. + ## Documentation The user guide starts at [`docs/index.md`](docs/index.md), @@ -245,3 +270,8 @@ and [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) how the VM tests work. komorebi for KDE is under the [Komorebi License](LICENSE.md). Contributions 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. diff --git a/docs/cli/border-offset.md b/docs/cli/border-offset.md new file mode 100644 index 00000000..fa7f3d6d --- /dev/null +++ b/docs/cli/border-offset.md @@ -0,0 +1,14 @@ +```text +Set the border offset + +Usage: border-offset + +Arguments: + + Desired offset of the window border + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/border-width.md b/docs/cli/border-width.md new file mode 100644 index 00000000..8eec285c --- /dev/null +++ b/docs/cli/border-width.md @@ -0,0 +1,14 @@ +```text +Set the border width + +Usage: border-width + +Arguments: + + Desired width of the window border + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/border.md b/docs/cli/border.md new file mode 100644 index 00000000..4fcbdbe7 --- /dev/null +++ b/docs/cli/border.md @@ -0,0 +1,14 @@ +```text +Enable or disable borders + +Usage: border + +Arguments: + + [possible values: enable, disable] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/visible-windows.md b/docs/cli/visible-windows.md new file mode 100644 index 00000000..f88fbd97 --- /dev/null +++ b/docs/cli/visible-windows.md @@ -0,0 +1,10 @@ +```text +Show a JSON representation of visible windows + +Usage: visible-windows + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 6a7ee5b8..831d1313 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -9,9 +9,9 @@ This page describes that trait, who implements and calls it, where each of its r enforced, the model of the desktop the window manager tiles, the backend that reaches KWin, how an event about a window becomes a tile, how workspaces are the compositor's desktops, how a stack hides its windows, how a message on the daemon's socket is answered, how subscribers -are notified of both, what the orders a message gives do, how `komorebi.json` configures the -daemon, and how the NixOS module runs the daemon. It grows with the code: each part of the -daemon that is added has its place here. +are notified of both, what the orders a message gives do, how the compositor is asked to draw the +borders, how `komorebi.json` configures the daemon, and how the NixOS module runs the daemon. It +grows with the code: each part of the daemon that is added has its place here. ## Vocabulary @@ -67,6 +67,10 @@ daemon that is added has its place here. asked the daemon, by the name of that socket, to send it notifications. - **Notification**: what a subscriber is sent after each event and each message the window manager handles: the event or the message, and the state after it ([`Notification`]). +- **Look**: how the compositor is asked to dress the windows, which it draws ([`Look`]): + a border, with its width, its corner radius and two colors. +- **Effect**: a plugin of the compositor that changes how windows are drawn. KDE Rounded Corners + is the effect that draws the border. - **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) @@ -650,9 +654,10 @@ file `--config` names, or else `komorebi.json` in [`HOME_DIR`] (`$KOMOREBI_CONFI has three steps, because the monitors are known only after the backend is asked: 1. [`StaticConfig::preload`] reads the file, applies the settings that are process-wide (the - default paddings, [`LAYOUT_DEFAULTS`], the indices of the monitors, and the rules in - [`IGNORE_IDENTIFIERS`], [`MANAGE_IDENTIFIERS`] and [`FLOATING_APPLICATIONS`]) and makes the - [`WindowManager`], with the settings that are its own. It starts a watcher on the file. + default paddings, [`LAYOUT_DEFAULTS`], the indices of the monitors, the settings of the borders + in [`border_manager`], and the rules in [`IGNORE_IDENTIFIERS`], [`MANAGE_IDENTIFIERS`] and + [`FLOATING_APPLICATIONS`]) and makes the [`WindowManager`], with the settings that are its own. + It starts a watcher on the file. 2. [`WindowManager::init`] loads the monitors and the windows from the backend, in the order the indices of the monitors give. 3. [`StaticConfig::postload`] gives each monitor the entry of the file that is its own, and each @@ -679,9 +684,11 @@ there and is not an applications.json is an error. Three kinds of key reach the model. A **setting** of the window manager is a field of it ([`WindowManager::resize_delta`] and the others). A **default** is a process-wide static that a monitor or a workspace falls back to when it has no value of its own: the paddings, the layout -defaults. A **rule** is an entry of one of the process-wide lists. A workspace's own -`layout_rules`, `work_area_offset_rules` and `window_container_behaviour_rules` are fields of the -[`Workspace`], which [`Workspace::update`] reads each time it tiles. +defaults. The settings of the borders are statics too, which the file sets and +[`border_manager::current_look`] and the layout read. A **rule** is an entry of one of the +process-wide lists. A workspace's own `layout_rules`, `work_area_offset_rules` and +`window_container_behaviour_rules` are fields of the [`Workspace`], which [`Workspace::update`] +reads each time it tiles. A workspace's `workspace_rules` and `initial_workspace_rules` are not fields of the window manager but entries of [`WORKSPACE_MATCHING_RULES`], which [`StaticConfig::postload`] and @@ -754,15 +761,50 @@ goes the other way, for `GenerateStaticConfig`. | The configuration the daemon generates loads and says the same | test | `a_configuration_comes_out_again_as_the_settings_of_the_window_manager` | none | | The daemon reads the file it is given or the one in the config home, not both | startup order: `main.rs` takes `--config` before the config home | `the_daemon_follows_the_file_it_is_given_when_the_file_changes`, `the_daemon_reads_komorebi_json_from_the_config_home` | none | +## The look + +komorebi decides what the windows look like and the compositor draws it, since only the +compositor has the frames, the corners and the shadows. A border is the outer outline of a window, +drawn outside it, in the gap the layout leaves between tiles. The window manager describes a +[`Look`] and asks the backend for it ([`Backend::apply_look`]); the backend sees that it is drawn +and answers whether borders are being drawn. The reasons are in +[DESIGN.md](DESIGN.md#why-does-the-compositor-draw-the-borders-and-not-komorebi). + +[`border_manager`] holds the settings, as statics that the messages `Border`, `BorderWidth` and +`BorderOffset` set: whether borders are on, their width, the offset, the radius of the corners and +the two colors. [`border_manager::current_look`] makes the [`Look`] of them, and +[`border_manager::send_notification`] asks the backend for it and keeps the answer in +[`BORDER_DRAWN`]. It is called before the first layout, after every event and every message, 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. + +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. +Without a border, because they are off or the compositor has no effect to draw one, the room is +given back the next time the workspace is tiled. + +The KWin backend draws the border with the effect KDE Rounded Corners +([`kwin::effects`](../../komorebi/src/kwin/effects.rs)). `apply_look` writes the effect's settings +into the user's `kwinrc`, group `[Round-Corners]`, through [`Kwinrc`]; loads the effect with +`loadEffect` unless it is loaded; and always asks it to read its settings again +(`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. +[PLATFORM.md](PLATFORM.md#kwin-effects) has the effect, its settings and what was measured. + ## The NixOS module The flake exports one module under two names, `nixosModules.default` and `nixosModules.komorebi`: [`nixos-module.nix`] and the flake's overlay, which builds `komorebi-full` (both programs) with the flake's nixpkgs and Rust toolchain. Its options are `enable`, `package` (by default `pkgs.komorebi-full`, from the overlay), `logLevel`, -`configFile`, `config`, `applicationSpecificConfiguration`, and `execStart`, which is read-only: the -module sets it to `bin/komorebi` of the package with `--log-level`, and `--config` with a -`komorebi.json` when `configFile` or `config` is set. `config` is typed from +`configFile`, `config`, `applicationSpecificConfiguration`, `effects.borders.enable` and +`effects.borders.package` (by default `pkgs.kde-rounded-corners-komorebi`, from the overlay), and +`execStart`, which is read-only: the module sets it to `bin/komorebi` of the package with +`--log-level`, and `--config` with a `komorebi.json` when `configFile` or `config` is set. `config` +is typed from `nix/komorebi-options.nix`, the options `schemars-nixgen` makes from the schema of `komorebi.json`; the module writes it as JSON, with no null in it, and `configFile` and the written file both go through `check-jsonschema` against `schema.json` when the system is built (comment lines taken out @@ -771,7 +813,8 @@ fetched from GitHub that become `app_specific_configuration_path`; the module ha `internal.configAttrs` is the configuration as the attribute set the options make, for the tests. With `services.komorebi.enable`, the module: -- installs the package in the system profile; +- installs the package in the system profile, and the effect that draws the borders unless + `effects.borders.enable` is off; - defines the user unit `komorebi.service`, which every user of the machine has. Plasma's `plasma-workspace.target` wants it, so a Plasma session starts it at login, and it is ordered after `plasma-core.target`, which Plasma orders after KWin's service, `plasma-kwin_wayland`; @@ -794,6 +837,8 @@ module's unit. | A configuration with a layout or a value komorebi does not have does not build | evaluation error: `config` is typed from the schema; and `check-jsonschema` fails the build for a file that does not follow it | `nixos-module-eval` ("a layout komorebi does not have does not evaluate"), `nix-options-validation` | `configFile` with a file the schema accepts | | The sources of application specific configuration reach the daemon only while `applicationSpecificConfiguration.enable` is set | framework path: the module adds `app_specific_configuration_path` to the file it writes only when `enable` is set and there are sources | `nixos-module-eval` ("with applicationSpecificConfiguration.enable = false, the sources are left out of config", "with the sources turned off and no config, there is nothing to write") | none | | `komorebi` and `komorebic` are on every user's `PATH` | the module installs the package in the system profile | `nixos-module-eval`; every VM suite runs `komorebic` | none | +| The border effect is installed with komorebi, and only by the module | the module installs `effects.borders.package` in the system profile when `effects.borders.enable` is set | `nixos-module-eval` ("the border effect is installed in the system profile", "with the border effect off, komorebi is installed and the effect is not"), `vm-look` | `effects.borders.enable = false` | +| The border effect the module installs is built for the KWin of the system and is not loaded until komorebi asks | the package: `kde-rounded-corners-komorebi` links the `libkwin` of the nixpkgs' KWin and says `EnabledByDefault` false in its metadata | the `kde-rounded-corners-komorebi-install` check | `effects.borders.package` | | Every Plasma session starts komorebi, once KWin's service has started | systemd: the user unit is wanted by `plasma-workspace.target`, after `plasma-core.target` | `nixos-module-eval`, `vm-module` | `systemctl --user mask komorebi` | | A daemon that fails or is killed is started again | systemd: `Restart=on-failure` | `vm-module` (`SIGKILL`) | none | | A daemon that is told to stop stays stopped, and the unit is not failed | systemd: the exit statuses of `Stop` (0) and of `SIGTERM` (130) are successes | `vm-module` | none | @@ -839,6 +884,10 @@ module's unit. [`bridge.js`](../../komorebi/src/kwin/bridge.js), the bridge. - [`static_config`](../../komorebi/src/static_config.rs): `komorebi.json`, [`StaticConfig`], and how it is loaded, reloaded and generated. +- [`border_manager`](../../komorebi/src/border_manager/mod.rs): the border settings, and the + [`Look`] they make, which it asks the backend for. +- [`kwin::effects`](../../komorebi/src/kwin/effects.rs): the KWin effect that draws the border, + its settings and the state komorebi keeps of it. - [`process_command`](../../komorebi/src/process_command.rs): the thread that listens on the socket, and what the window manager does with each message. - [`state`](../../komorebi/src/state.rs): the [`State`] a `State` message is answered with, @@ -854,8 +903,9 @@ module's unit. `docs/cli`. - [`main.rs`](../../komorebi/src/main.rs): the daemon. It connects to KWin, or installs the fake with `--fake-backend`, makes the window manager from `komorebi.json` when there is one, - which binds the socket, loads the desktop, gives the monitors their configuration and tiles, starts the threads that listen on the socket and handle events, and - waits to be stopped. + which binds the socket, loads the desktop, gives the monitors their configuration, asks for the + borders and tiles, starts the threads that listen on the socket and handle events, and waits to + be stopped. - [`nixos-module.nix`]: the NixOS module, which installs komorebi and runs the daemon as a systemd user unit of every Plasma session. @@ -888,6 +938,9 @@ the fake. The window manager is its only caller, through [`backend`]. The contra `set_window_workspace` changes where it comes back to, not where it is hidden. Only the back of a stack and the containers behind a monocle are hidden: nothing is hidden to leave a workspace. +- The look is a request (`apply_look`): a backend asks the compositor to draw it and answers + whether borders are being drawn, and one that draws nothing answers false, which is the default. + It does nothing when it is asked for the look it applied last. - `shutdown`, `is_window`, `window_rect` and `monitor_from_point` have defaults, written in terms of the queries. An implementor should not need to override them, except `shutdown` when it created something in the compositor that has to be given up. @@ -973,6 +1026,10 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | What the backend sends is what the bridge carries out | tests: the commands of [`fixtures`] are what the backend's tests check it sends and what the bridge's tests answer it with, checking what KWin is asked to do for each | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a command for a window KWin no longer has is given back, and the rest are carried out` | none | | Everything the bridge sends over D-Bus is one string | type checker: [`kwin-api.d.ts`] gives `callDBus` one string argument | `tsc`, `every call goes to the daemon's names, with one JSON string` | none | | The bridge uses nothing a KWin script does not have | type checker: the library is ECMAScript 2016 alone, and KWin's API is what [`kwin-api.d.ts`] declares | `tsc` | a declaration KWin does not match: the VM tests run the bridge in KWin | +| 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 | +| 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 | @@ -1091,6 +1148,15 @@ A window is shown, and ends up on a tile: stopped with `komorebic`. - [`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 + [`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; + [`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. - [`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, @@ -1168,6 +1234,13 @@ A window is shown, and ends up on a tile: [`set_backend`]: ../../komorebi/src/backend/mod.rs [`backend`]: ../../komorebi/src/backend/mod.rs [`with_backend`]: ../../komorebi/src/backend/mod.rs +[`Look`]: ../../komorebi/src/backend/mod.rs +[`Backend::apply_look`]: ../../komorebi/src/backend/mod.rs +[`border_manager`]: ../../komorebi/src/border_manager/mod.rs +[`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 +[`WindowManager::retile_all`]: ../../komorebi/src/window_manager.rs [`Ring`]: ../../komorebi/src/ring.rs [`Monitor`]: ../../komorebi/src/monitor.rs [`Workspace`]: ../../komorebi/src/workspace.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 7013b377..455ae834 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -372,3 +372,56 @@ what a Plasma session runs at login for a program that is not part of it, so ordered after `plasma-workspace` (`X-KDE-autostart-after`), as the module's unit is ordered after `plasma-core.target`: the daemon exits when KWin is not on the session bus. The entry and the unit do not go together, since the session bus gives its name to one komorebi. + +## Why is KDE Rounded Corners built from source, and not taken from nixpkgs? + +Because the version in nixpkgs draws its outline in the wrong place on KWin 6.8, the oldest +KWin komorebi supports. At time of writing (2026-10-27, nixpkgs `d3b13ad`) nixpkgs has +0.10.0, which puts the outline about 24 px too low, across the title bar. 0.11.0 is the +release that handles the texture coordinates KWin 6.8 inverted, so +[`nix/kde-rounded-corners.nix`](../../nix/kde-rounded-corners.nix) overrides the nixpkgs +package with it ([PLATFORM.md](PLATFORM.md#kwin-effects)). + +## Why are the effects built disabled by default? + +So that they cannot load with their own defaults before komorebi configures them. KWin loads +an effect that is enabled by default as soon as it starts, with the settings the effect has +then, and KDE Rounded Corners at its defaults draws a one pixel black outline over the title +bar of every window. Built with `EnabledByDefault` false, an effect is loaded only when +something asks for it with `loadEffect`, which can come after its settings are written. That +KWin then starts without the effect and loads it when asked was measured before the package +was written ([PLATFORM.md](PLATFORM.md#kwin-effects)). + +## Why does the compositor draw the borders, and not komorebi? + +Because the compositor has the frames, the corners and the shadows of the windows, and komorebi +has none of them. komorebi decides what the windows look like and describes it to the backend as a +`Look` ([`Backend::apply_look`](../../komorebi/src/backend/mod.rs)); on KWin the effect KDE +Rounded Corners draws it, and komorebi writes the effect's settings. The same code that decides the +look then runs against the fake desktop, which records the look it was asked for. + +## Why is the border the outer outline of the effect? + +Because the effect's own defaults draw a black outline one pixel thick *inside* every window, over +its title bar and contents, which is what an unconfigured install looks like. So komorebi sets +every inner outline to 0 and uses the outer outline, which is drawn outside the window, in the gap +the layout leaves between tiles. The effect draws the outer outline only in the shadow of the +window (its shader stops where the window's texture is transparent), so it is at most 20 px thick, +and a window that has no shadow has no border. komorebi does not take the title bar off a window +to change that: removing it also removed the shadow, and the border with it, and Plasma 6.8 gives +a window without a shadow one of its own ([PLATFORM.md](PLATFORM.md#kwin-effects)). + +## Why does the layout leave room for the border only while it is drawn? + +Because the border is outside the window: without room for it, it would fall on the window next +to it. And because komorebi cannot know that a border is drawn. The effect may not be installed +(KWin finds effects when it starts), or borders may be off, so the backend answers whether +`apply_look` drew one, and the layout leaves room only after a yes. A compositor that draws no +border takes none. + +## Why does komorebi ask the effect to read its settings again after it loads it? + +Because KWin keeps the copy of `kwinrc` it read when it started, and an effect reads its settings +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. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 40f44843..980bf5cc 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -139,6 +139,10 @@ there. The desktop is not a workspace: komorebi counts the workspaces without it it is on the workspace it will come back to. It checks that KWin still lists the desktop before it sends another window there. +When borders are on, it also asks KWin to load KDE Rounded Corners, the effect that draws them, +after writing the effect's settings into `kwinrc`, and asks it to read them again +([KWin effects](#kwin-effects)). An effect KWin did not find is reported once in the log. + Every command of the window manager (move and resize, focus, raise, hide or restore, minimize, bring back, maximize, unmaximize or close a window, show a workspace on an output, put a window on a workspace) is queued for the bridge, which gets the queue as the answer to its held call and @@ -165,8 +169,9 @@ an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a runnin When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it brings back the windows it hid, waits until the commands that do so have reached the bridge, removes the -parking desktop, puts back the value `PerOutputVirtualDesktops` had in `kwinrc` (or removes the -key, when the user had none) and asks KWin to reload its configuration, asks KWin to unload the +parking desktop, unloads the border effect, if komorebi loaded it, puts back the values the keys it +set in `kwinrc` had (`PerOutputVirtualDesktops`, and the keys of the border effect), or removes a +key the user had not set, and asks KWin to reload its configuration, asks KWin to unload the script, closes an empty connection to each subscriber, and removes the socket. The desktops it created for workspaces stay: they are the user's desktops from then on. A `StopIgnoreRestore` message stops it the same way, except that it does not bring the windows back: the parking desktop @@ -221,6 +226,7 @@ What komorebi calls: | `org.kde.KWin` | `/Scripting/Script` | `org.kde.kwin.Script` | `run()` | after `loadScript` | | `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` | `/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 | @@ -235,6 +241,7 @@ since a read right after `createDesktop` has to see the new desktop. | `$KOMOREBI_CONFIG_HOME/komorebi.json` (`~/.config/komorebi/komorebi.json`) | komorebi's configuration, which komorebi never writes: read when the daemon starts, and again when it changes. `--config` names another file | the user's | | `$XDG_CONFIG_HOME/autostart/komorebi.desktop` (`~/.config/autostart/komorebi.desktop`) | the XDG autostart entry `komorebic enable-autostart` writes: `Exec=komorebi`, or `komorebi --config "FILE"`, and `X-KDE-autostart-after=plasma-workspace`, which a Plasma session starts komorebi from at login | the user's; `komorebic disable-autostart` removes it | | `$XDG_CONFIG_HOME/kwinrc` (`~/.config/kwinrc`) | KWin's configuration: komorebi sets `PerOutputVirtualDesktops=true` in `[Windows]`, changing that line or adding it and nothing else, and writes the file beside it first and renames it over it | put back as it was when the daemon stops | +| `$XDG_CONFIG_HOME/kwinrc`, group `[Round-Corners]` | the settings of the border effect, written when borders are on ([KWin effects](#kwin-effects)) | put back, with the rest of `kwinrc`, when borders are turned off and when the daemon stops | | `$XDG_RUNTIME_DIR/komorebi/kwinrc-backup.json` | the value each key of `kwinrc` had before komorebi first changed it | removed when the values are put back; one a crash left behind is used by the next run | | `$XDG_RUNTIME_DIR/komorebi/bridge.js` | the script KWin loads, with its configuration (the D-Bus names and the hold time of `Poll`) on its first line | written at every start; the directory is removed at logout | | `$XDG_RUNTIME_DIR/komorebi/komorebi.sock` | the command socket | bound once the daemon is connected to KWin, after a file left there is removed; removed when the daemon stops | @@ -391,6 +398,69 @@ the batch moved, the client's answer included: The spikes measured the channel alone, with twenty windows in each batch, at 16, 19 and 20 ms ([DESIGN.md](DESIGN.md#why-do-commands-go-to-the-bridge-as-the-answer-to-a-held-call)). +## 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: + +| Package | Effect | Plugin id | Installed as | +|---|---|---|---| +| `kde-rounded-corners-komorebi` | [KDE Rounded Corners](https://github.com/matinlotfali/KDE-Rounded-Corners) 0.11.0, which draws an outline around each window | `kwin4_effect_shapecorners` | a C++ plugin, `lib/qt-6/plugins/kwin/effects/plugins/kwin4_effect_shapecorners.so` | + +Each package is in the flake's `packages` for Linux and in `overlays.default`, which builds it +with the `callPackage` of the nixpkgs it is applied to, so that it follows that nixpkgs' KWin. +[`nix/tests/effects.nix`](../../nix/tests/effects.nix) has a check for each, which builds the +package and inspects its files the way KWin finds them, without a session. + +At time of writing (2026-10-27): + +- **KWin finds effects only when it starts.** An effect installed while KWin runs cannot be + loaded (`isEffectSupported` is false and `loadEffect` returns false) until KWin starts + again, which in a session means logging out and back in. +- **KWin loads every effect that is enabled by default when it starts**, with the settings + the effect has then. KDE Rounded Corners 0.11.0 is enabled by default in its + `metadata.json`, and at its defaults it draws a one pixel black outline inside every + window, over its title bar. The package builds it with `"EnabledByDefault": false`: KWin + starts without it (`loadedEffects` lists the built-in effects only), `isEffectSupported` + is true, and `loadEffect` with `kwin4_effect_shapecorners` on `org.kde.KWin`'s `/Effects` + loads it. The metadata is compiled into the plugin, which is where the check reads the + flag, with `qtplugininfo`. +- **KDE Rounded Corners 0.10.0, the version in nixpkgs, draws the outline about 24 px too low + on KWin 6.8**: across the title bar at the top, the same distance below the frame at the + bottom, and in the right place at the sides. KWin 6.8 inverted the texture coordinates of + the offscreen window, and Breeze's shadow is deeper below a window than above it; the error + is the difference of the two. 0.11.0 is the release that handles it. +- **KDE Rounded Corners links `libkwin.so.6`**, so it is built against the KWin that loads + it. With the package in a NixOS system's `environment.systemPackages`, KWin finds the + plugin in `/run/current-system/sw/lib/qt-6/plugins/kwin/effects/plugins/`, and the plugin + links the libkwin of the store path the running `kwin_wayland` comes from. The check + asserts the same for the `kdePackages.kwin` of the flake's nixpkgs: the first directory of + the plugin's `RUNPATH` that has `libkwin.so.6` is that KWin's `lib`. +- **KDE Rounded Corners draws its outer outline in the window's shadow**: its shader stops + where the window's texture is transparent. A window without a shadow has no outer outline, + and the outline is at most 20 px thick. + +### What komorebi writes for the border + +KDE Rounded Corners reads its settings from the group `[Round-Corners]` of `kwinrc` (the names are +those of the effect's `options.kcfg`). komorebi sets every outline, not only the one it uses: + +| Key | Value | +|---|---| +| `OuterOutlineThickness`, `InactiveOuterOutlineThickness` | the border's width, 0 to 20 | +| `OuterOutlineColor`, `InactiveOuterOutlineColor` | `r,g,b`: the focused window's border, and every other window's | +| `Size`, `InactiveCornerRadius` | the corner radius | +| `OutlineThickness`, `InactiveOutlineThickness`, `SecondOutlineThickness`, `InactiveSecondOutlineThickness` | `0`: nothing inside the window | +| `ActiveOuterOutlineAlpha`, `InactiveOuterOutlineAlpha` | `255` | +| `ActiveOuterOutlineUseCustom`, `InactiveOuterOutlineUseCustom` | `true`, so that the colors are komorebi's | +| `ActiveOuterOutlineUsePalette`, `InactiveOuterOutlineUsePalette`, `OuterOutlineIsGradient`, `InactiveOuterOutlineIsGradient` | `false` | + +komorebi then calls `reconfigureEffect` on `/Effects`: at time of writing (2026-10-27), KWin 6.8.1 +hands an effect the copy of `kwinrc` it read when it started, so the new values reach it only +that way, also for an effect loaded a moment before. A screenshot of a session shows the border +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. + ## 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 8ec59c15..0c62d3aa 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -141,8 +141,18 @@ the run. - `desk(wid)` is the number of the desktop a window is on and `shown()` the one KWin shows, both counted from 1 as `kdotool` counts, `desktops()` how many desktops KWin has, `desktop_names()` their names in order (the parking desktop - of a stack is the one named `komorebi-park`), and `kwinrc(group, key)` a value - of the user's `kwinrc`. + of a stack is the one named `komorebi-park`), `kwinrc(group, key)` a value of + the user's `kwinrc`, and `kwinrc_group(group)` every key of a group, which a + test compares before and after komorebi to see that the user's settings are + put back. +- `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. +- `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, + color)` names the sides of a window's frame that have no ring of `color` just + outside them, which is how a test sees a border. - `kwin_script(name, source, keep=)` runs a KWin script and returns the lines it reported: the script calls `report(...)`, which `print`s a line marked with `name` to KWin's log, and ends with `report("done")`. A script that is kept @@ -161,6 +171,13 @@ Two traps are worth knowing about before writing a screenshot test: on it, so "the screenshot is not blank" passes while Plasma is still starting. `Kde.session` waits for the splash process to exit, and a test should check a pixel it knows, such as the middle of a terminal. +- The panel comes after the shell. A window tiled before the panel was made is + tiled under it, which hides the bottom of its border from a screenshot, and + nothing tiles it again. `Kde.session` waits until the shell has made a panel. KWin takes + the room for the panel a while after that, and a daemon learns of it up to a second later: a + test that opens windows right after the daemon starts waits with + `Kde.wait_for_panel_room` first. It is a wait and not a check, because a session that is too + slow may never take the room. - NixOS wraps programs, so a process's name is the wrapper's (`.plasmashell-wrapped`), and `pgrep -x plasmashell` never matches. Match the command line instead, with a bracket in the pattern (`pgrep -f '[p]lasmashell'`) so that the shell running diff --git a/docs/example-configurations.md b/docs/example-configurations.md index 9ba5ac25..c17942dc 100644 --- a/docs/example-configurations.md +++ b/docs/example-configurations.md @@ -16,6 +16,9 @@ different layout. This page has the file as it is: "cross_monitor_move_behaviour": "Insert", "default_workspace_padding": 15, "default_container_padding": 15, + "border": true, + "border_width": 6, + "border_offset": 5, "floating_window_aspect_ratio": "Widescreen", "floating_layer_behaviour": "Float", "resize_delta": 100, diff --git a/docs/index.md b/docs/index.md index 7a9b0fad..a3f4c2c8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -59,6 +59,7 @@ explains the files of rules for particular applications it can name. [Quickstart and autostart](usage/quickstart-and-autostart.md) explains how to write an example configuration, how to start komorebi with Plasma without the module, and how to replace the configuration of a running daemon. +[Borders](usage/borders.md) explains how komorebi has KWin draw a border around each window. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/installation.md b/docs/installation.md index 4acfe947..addc42ec 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -55,6 +55,10 @@ the repository's `rust-toolchain.toml` selects, whatever nixpkgs your system use - It installs `komorebi` and `komorebic` in the system profile, so they are on every user's `PATH`. +- It installs KDE Rounded Corners, the KWin effect that draws komorebi's borders, unless + `services.komorebi.effects.borders.enable` is `false`. KWin finds effects when it starts, so a + session that was running when you switched to the new configuration has the borders after the + next login. - It defines a systemd user unit, `komorebi.service`, for every user of the machine. Plasma's `plasma-workspace.target` starts it when a user logs in to a Plasma session, after `plasma-core.target`, which Plasma orders after KWin. The unit runs the daemon with the `PATH` @@ -75,6 +79,8 @@ the repository's `rust-toolchain.toml` selects, whatever nixpkgs your system use | `services.komorebi.config` | `null` | The configuration, as Nix: every key of `komorebi.json`, typed from the schema. The module writes it as a `komorebi.json`, checks that against the schema, and the unit passes it to komorebi as `--config`. Ignored if `configFile` is set. | | `services.komorebi.configFile` | `null` | A `komorebi.json` for the daemon, checked against the schema when the system is built. The unit passes it to komorebi as `--config`, so the daemon reads it and not the `komorebi.json` of `~/.config/komorebi`. The file is in the Nix store: komorebi reads a new one when it starts again. | | `services.komorebi.applicationSpecificConfiguration` | `enable = true`, `sources = [ ]` | Files of [application specific configuration](usage/application-specific-configuration.md) fetched from GitHub (`owner`, `repo`, `rev`, `path` and `hash` each), which become the `app_specific_configuration_path` of the configuration `config` makes. There are none by default. | +| `services.komorebi.effects.borders.enable` | `true` | Installs the KWin effect that draws komorebi's borders. Whether borders are drawn is komorebi's own setting ([Borders](usage/borders.md)). KWin finds effects when it starts: log in again after the first switch. The module warns when `config` sets `border` to `true` and this is off. | +| `services.komorebi.effects.borders.package` | `pkgs.kde-rounded-corners-komorebi` | The effect: KDE Rounded Corners 0.11.0, built against the KWin of the system and not loaded until komorebi asks. | | `services.komorebi.execStart` | read only | The command line the unit starts komorebi with, built from `package`, `logLevel` and `configFile` or `config`. A unit of your own that runs komorebi uses it to start komorebi the same way. | `config` takes the keys of `komorebi.json` ([Configuration](usage/configuration.md)) as Nix, and a @@ -132,14 +138,15 @@ doing, and its log. ### The packages without the module The flake's packages are `komorebi`, `komorebic`, and `komorebi-full`, which has both and is the -`default`. To install them without the unit, and start komorebi yourself: +`default`, and `kde-rounded-corners-komorebi`, the effect that draws the borders. To install them without the unit, and start komorebi yourself: ```sh nix profile install github:LGUG2Z/komorebi-for-kde ``` On a NixOS configuration, the overlay, `overlays.default`, provides `pkgs.komorebi`, -`pkgs.komorebic` and `pkgs.komorebi-full` for `environment.systemPackages`. +`pkgs.komorebic`, `pkgs.komorebi-full` and `pkgs.kde-rounded-corners-komorebi` for +`environment.systemPackages`. ## Other distributions: from source diff --git a/docs/komorebi.example.json b/docs/komorebi.example.json index 7ab0d827..e7058e85 100644 --- a/docs/komorebi.example.json +++ b/docs/komorebi.example.json @@ -3,6 +3,9 @@ "cross_monitor_move_behaviour": "Insert", "default_workspace_padding": 15, "default_container_padding": 15, + "border": true, + "border_width": 6, + "border_offset": 5, "floating_window_aspect_ratio": "Widescreen", "floating_layer_behaviour": "Float", "resize_delta": 100, diff --git a/docs/usage/borders.md b/docs/usage/borders.md new file mode 100644 index 00000000..e97276ad --- /dev/null +++ b/docs/usage/borders.md @@ -0,0 +1,68 @@ +# Borders + +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. + +## Installing the effect + +The effect is not part of KWin, and KWin finds effects when it starts: log out and in again after +installing it. On NixOS the flake's module installs it with komorebi, which is what +`services.komorebi.effects.borders.enable` does (it is on by default); the effect is built so that +KWin does not load it until komorebi asks. +[`installation.md`](../installation.md) has the module's options. + +komorebi loads the effect when it starts and borders are on, and unloads it when it exits or the +borders are turned off. A machine that does not have the effect has no borders: komorebi says so +once in its log, and leaves no room for them. + +## Turning borders on and off + +[`komorebic border`](../cli/border.md) turns borders on or off. They are on by default. + +```sh +komorebic border disable +komorebic border enable +``` + +## Width and room + +[`komorebic border-width`](../cli/border-width.md) sets how thick the border is, in pixels: 10 by +default. The effect draws at most 20 pixels, and draws the border only where a window has a shadow, +so a window with no shadow has no border. + +While the borders are drawn, the layout leaves room for them: every tile gives up the width of the +border on each side, so that the border is drawn in the gap between two windows and does not fall +on the window next to it. [`komorebic border-offset`](../cli/border-offset.md) leaves more room +than the width, in pixels, which the effect draws nothing in. With borders off, or without the +effect, the layout leaves no room at all. A change of the width or the offset reaches the layout +the next time the workspace is tiled again, which [`komorebic retile`](../cli/retile.md) does. + +```sh +komorebic border-width 6 +komorebic border-offset 2 +komorebic retile +``` + +## In komorebi.json + +The same settings can be in [`komorebi.json`](configuration.md#borders): `border`, `border_width` +and `border_offset` are what the three commands above set, and `border_radius` is how round the +corners are, in pixels (10 by default), which has no command. The file sets them when the daemon +starts and when the file changes; a key it leaves out leaves the setting as it is. + +```json +{ + "border": true, + "border_width": 6, + "border_offset": 2, + "border_radius": 12 +} +``` + +## What is put back + +The effect keeps its settings in the user's `kwinrc`, in the group `[Round-Corners]`. komorebi +writes them when it asks for the border, and when it exits or the borders are turned off it puts +back what the user had there, also after a crash: the next run puts them back when it stops. diff --git a/docs/usage/configuration.md b/docs/usage/configuration.md index 0c284c3c..7fa07481 100644 --- a/docs/usage/configuration.md +++ b/docs/usage/configuration.md @@ -37,8 +37,9 @@ trailing commas. Reading the file again sets every setting of the daemon from it, and a key the file leaves out is the default of the setting: a `resize-delta` given with a command is gone when the file changes. -Three things stay as they were when the file leaves them out: `default_workspace_padding`, -`default_container_padding` and `display_index_preferences`. The rules add up, as +These stay as they were when the file leaves them out: `default_workspace_padding`, +`default_container_padding`, `display_index_preferences` and the four settings of the borders. +The rules add up, as [Rules](#rules) says. A workspace the file lists gets its name, padding, offsets and rules from its entry, and its layout when the entry names one; a workspace the file does not list is left as it is. @@ -91,6 +92,19 @@ how another platform draws or hides windows, are accepted: `titleless_applicatio (`container_padding`, `workspace_padding`, `work_area_offset`) and a workspace (the same three) can have values of their own, which come before the default. +### Borders + +| Key | Default | What it does | +|---|---|---| +| `border` | `true` | Whether the compositor draws a border around each window (`active_window_border` is the same key under its old name) | +| `border_width` | `10` | How thick the border is, in pixels (`active_window_border_width`) | +| `border_offset` | `0` | How much more room than the width the layout leaves around each window (`active_window_border_offset`) | +| `border_radius` | `10` | How round the corners of the border are, in pixels | + +[Borders](borders.md) explains what the compositor draws and what the layout leaves room for. +`komorebic border`, `border-width` and `border-offset` change the first three while the daemon +runs. + ### Rules | Key | What it does | diff --git a/flake.nix b/flake.nix index dd0904e3..f99d33bc 100644 --- a/flake.nix +++ b/flake.nix @@ -256,12 +256,20 @@ inherit (nixpkgs.lib) nixosSystem; module = self.nixosModules.default; komorebiFor = guestSystem: self.packages.${guestSystem}.komorebi-full; + borderEffectFor = guestSystem: self.packages.${guestSystem}.kde-rounded-corners-komorebi; }; } # The VM tests need QEMU with KVM, so only Linux checks them. A Mac runs the same tests # through legacyPackages..vm, see docs/dev/vm-tests.md. // lib.optionalAttrs isLinux ( lib.mapAttrs' (name: test: lib.nameValuePair "vm-${name}" test) vm.suites + ) + # the KWin effects komorebi drives, installed and inspected without a session + // lib.optionalAttrs isLinux ( + import ./nix/tests/effects.nix { + inherit pkgs; + inherit (config) packages; + } ); legacyPackages = { @@ -286,6 +294,7 @@ inherit (build) komorebi komorebic; komorebi-full = build.fullBuild; default = build.fullBuild; + kde-rounded-corners-komorebi = pkgs.callPackage ./nix/kde-rounded-corners.nix { }; }; apps = lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { @@ -350,6 +359,8 @@ { inherit (build) komorebi komorebic; komorebi-full = build.fullBuild; + # with the consumer's KWin, so that the plugin links the libkwin it is loaded into + kde-rounded-corners-komorebi = final.callPackage ./nix/kde-rounded-corners.nix { }; }; overlays.komorebi = self.overlays.default; diff --git a/komorebi/src/backend/fake.rs b/komorebi/src/backend/fake.rs index cb12a014..cc99c53f 100644 --- a/komorebi/src/backend/fake.rs +++ b/komorebi/src/backend/fake.rs @@ -28,6 +28,7 @@ #![deny(missing_docs)] use super::Backend; +use super::Look; use super::MonitorInfo; use super::WindowInfo; use crate::core::Rect; @@ -64,6 +65,8 @@ pub enum Command { SwitchWorkspace(u32, usize), /// [`Backend::set_window_workspace`]: the window, and the workspace it was put on. SetWindowWorkspace(u32, usize), + /// [`Backend::apply_look`]: the look, when it is not the one applied before. + ApplyLook(Look), } #[derive(Default)] @@ -87,6 +90,10 @@ struct State { window_ws: HashMap, /// the desktop each monitor (by id) shows shown: 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 + borders_drawn: bool, } impl State { @@ -356,6 +363,13 @@ impl FakeBackend { state.shown.insert(monitor_id, idx); } + /// 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. + pub fn set_borders_drawn(&self, drawn: bool) { + self.state.lock().borders_drawn = drawn; + } + /// Returns every command received so far, oldest first. pub fn commands(&self) -> Vec { self.state.lock().commands.clone() @@ -554,6 +568,16 @@ impl Backend for FakeBackend { .map(|m| (m.id, state.shown.get(&m.id).copied().unwrap_or(0))) .collect() } + + fn apply_look(&self, look: &Look) -> eyre::Result { + let mut state = self.state.lock(); + // like a real backend, remember what was applied and say nothing twice + if state.last_look.as_ref() != Some(look) { + state.commands.push(Command::ApplyLook(look.clone())); + state.last_look = Some(look.clone()); + } + Ok(state.borders_drawn && look.border.is_some()) + } } #[cfg(test)] @@ -830,6 +854,37 @@ mod tests { assert_eq!(fake.workspace_of(9), None); } + #[test] + fn a_look_is_a_command_once_and_says_whether_borders_are_drawn() -> eyre::Result<()> { + let fake = FakeBackend::new(); + fake.set_borders_drawn(true); + let bordered = Look { + border: Some(crate::backend::BorderLook { + width: 10, + radius: 10, + focused: (1, 2, 3), + unfocused: (4, 5, 6), + }), + }; + + assert!(fake.apply_look(&bordered)?); + assert!(fake.apply_look(&bordered)?); + assert!(!fake.apply_look(&Look::default())?); + + fake.set_borders_drawn(false); + assert!(!fake.apply_look(&bordered)?); + + assert_eq!( + fake.commands(), + [ + Command::ApplyLook(bordered.clone()), + Command::ApplyLook(Look::default()), + Command::ApplyLook(bordered) + ] + ); + 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 b1c665b7..7c9162f0 100644 --- a/komorebi/src/backend/mod.rs +++ b/komorebi/src/backend/mod.rs @@ -36,6 +36,14 @@ //! ([`Backend::restore`]) when they are given the tile. A hidden window stays alive, stays on its //! workspace and is not minimized, so what the compositor reports about it is not taken for the //! user's doing (the window manager keeps a table of the windows it has hidden). +//! +//! # The look +//! +//! How windows look is asked of the compositor and drawn by it, since only the compositor has the +//! 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. #![deny(missing_docs)] @@ -88,6 +96,48 @@ pub struct MonitorInfo { pub work_area: Rect, } +/// How the compositor is asked to dress the windows komorebi arranges. +/// +/// komorebi decides what the windows look like and the compositor draws it, so this only +/// describes. The default asks for nothing. +/// +/// # Example +/// +/// ```rust +/// use komorebi::backend::BorderLook; +/// use komorebi::backend::Look; +/// +/// assert_eq!(Look::default().border, None); +/// +/// let look = Look { +/// border: Some(BorderLook { +/// width: 10, +/// radius: 12, +/// focused: (66, 165, 245), +/// unfocused: (128, 128, 128), +/// }), +/// }; +/// assert!(look.border.is_some()); +/// ``` +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Look { + /// A colored outline outside every window, or none. + pub border: Option, +} + +/// The outline around every window. +#[derive(Clone, Debug, PartialEq)] +pub struct BorderLook { + /// The thickness of the outline, outside the window, in pixels. + pub width: i32, + /// The radius of the window's corners, in pixels. + pub radius: i32, + /// The outline of the focused window, as red, green and blue. + pub focused: (u8, u8, u8), + /// The outline of every other window. + pub unfocused: (u8, u8, u8), +} + /// The desktop, as the window manager sees it. /// /// This is the **only** way the window manager reaches the compositor. Everything else in the crate @@ -114,6 +164,8 @@ pub struct MonitorInfo { /// comes back to. /// - A backend asked to show a workspace, or to put a window on one, that has no desktop yet makes /// the desktops up to it first. +/// - The look is a request: a backend that cannot draw what it is asked for says so in the answer +/// of [`Backend::apply_look`] and the window manager goes on without it. /// /// The compiler enforces the first and last parts of the contract that it can see. A backend that /// leaves out a method does not compile: @@ -298,6 +350,47 @@ pub trait Backend: Send + Sync + 'static { /// Returns the workspace each monitor shows, as `(monitor id, workspace index)`. fn current_workspaces(&self) -> Vec<(u32, usize)>; + // ---- look, which a backend that draws nothing need not say anything about -------------------- + + /// Asks the compositor to draw this look, and returns true if and only if window borders are + /// being drawn afterwards. + /// + /// A drawn border takes room around each window, which the layout has to leave, so the answer + /// is what the window manager reads to know that. A backend remembers the look it applied last + /// and does nothing when it is asked for the same again, so the window manager may call this as + /// often as it likes. The default draws nothing and answers false. + /// + /// # Errors + /// + /// When the compositor cannot be reached. + /// + /// # Example + /// + /// ```rust + /// use komorebi::backend::Backend; + /// use komorebi::backend::BorderLook; + /// use komorebi::backend::Look; + /// use komorebi::backend::fake::FakeBackend; + /// + /// let fake = FakeBackend::with_one_monitor(); + /// fake.set_borders_drawn(true); + /// let look = Look { + /// border: Some(BorderLook { + /// width: 10, + /// radius: 10, + /// focused: (66, 165, 245), + /// unfocused: (128, 128, 128), + /// }), + /// }; + /// + /// assert!(fake.apply_look(&look)?); + /// assert!(!fake.apply_look(&Look::default())?); + /// # Ok::<(), color_eyre::eyre::Report>(()) + /// ``` + fn apply_look(&self, _look: &Look) -> 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 new file mode 100644 index 00000000..7358d902 --- /dev/null +++ b/komorebi/src/border_manager/mod.rs @@ -0,0 +1,169 @@ +//! The borders around the windows, which the compositor draws. +//! +//! komorebi draws no border itself. KWin's KDE Rounded Corners effect draws an outline outside +//! each window, in the gap komorebi leaves between tiles, and this module decides what it looks +//! like: +//! +//! - [`send_notification`] asks the backend for the [`Look`] of the settings in force +//! ([`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. +//! +//! 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 +//! first values. + +use crate::backend::BorderLook; +use crate::backend::Look; +use crate::backend::backend; +use color_eyre::eyre; +use lazy_static::lazy_static; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicI32; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; + +/// The thickness of the border, in pixels. +/// +/// It is also the room the layout leaves for the border on each side of a window while the borders +/// are drawn ([`BORDER_DRAWN`]). The effect draws at most 20 pixels; the layout leaves the whole +/// width even when it is more. +pub static BORDER_WIDTH: AtomicI32 = AtomicI32::new(10); +/// More room the layout leaves on each side of a window while the borders are drawn, on top of +/// [`BORDER_WIDTH`]. The effect draws nothing in it. +pub static BORDER_OFFSET: AtomicI32 = AtomicI32::new(0); +/// The radius of the window's corners, in pixels. +pub static BORDER_RADIUS: AtomicI32 = AtomicI32::new(10); +/// Whether borders are asked for at all. +pub static BORDER_ENABLED: AtomicBool = AtomicBool::new(true); + +lazy_static! { + /// The color of the focused window's border, as [`pack`] stores it. + 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)); +} + +/// Returns a color as the statics store it: red in the low byte, then green, then blue. +/// +/// ```rust +/// use komorebi::border_manager::pack; +/// use komorebi::border_manager::unpack; +/// +/// 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) +} + +/// Returns the red, green and blue of a color as the statics store it. The bits above the third +/// byte are dropped. +pub const fn unpack(colour: u32) -> (u8, u8, u8) { + ( + (colour & 0xff) as u8, + ((colour >> 8) & 0xff) as u8, + ((colour >> 16) & 0xff) as u8, + ) +} + +/// Whether the compositor is drawing the borders, as the backend last answered +/// [`send_notification`]. +/// +/// When it is, they take room around each window ([`BORDER_WIDTH`] and [`BORDER_OFFSET`]), which +/// the layout leaves; when it is not (no effect installed, borders off) they take none. +pub static BORDER_DRAWN: AtomicBool = AtomicBool::new(false); + +/// Returns the [`Look`] of these settings. +/// +/// The border is there when `enabled`, with its width and radius at least 0; the colors are as the +/// statics store them, red, green and blue in one number. +/// +/// ```rust +/// use komorebi::border_manager::look; +/// use komorebi::border_manager::pack; +/// +/// let blue = pack(66, 165, 245); +/// let grey = pack(128, 128, 128); +/// +/// let on = look(true, 8, -2, blue, grey); +/// let border = on.border.expect("the borders are on"); +/// assert_eq!((border.width, border.radius), (8, 0)); +/// assert_eq!(border.focused, (66, 165, 245)); +/// assert_eq!(border.unfocused, (128, 128, 128)); +/// +/// assert_eq!(look(false, 8, 10, blue, grey).border, None); +/// ``` +pub fn look(enabled: bool, width: i32, radius: i32, focused: u32, unfocused: u32) -> Look { + Look { + border: enabled.then(|| BorderLook { + width: width.max(0), + radius: radius.max(0), + focused: unpack(focused), + unfocused: unpack(unfocused), + }), + } +} + +/// Returns the [`Look`] of the settings in force: the border statics of this module. +pub fn current_look() -> Look { + look( + BORDER_ENABLED.load(Ordering::SeqCst), + BORDER_WIDTH.load(Ordering::SeqCst), + BORDER_RADIUS.load(Ordering::SeqCst), + FOCUSED.load(Ordering::SeqCst), + UNFOCUSED.load(Ordering::SeqCst), + ) +} + +/// Asks the backend for the [`Look`] of the settings in force, and keeps its answer, whether the +/// borders are drawn, in [`BORDER_DRAWN`]. +/// +/// Called whenever the window manager's state changes in a way that could change the look, and +/// whenever a setting does. The backend does nothing when the look is the one it applied last, and +/// a failure is logged. +pub fn send_notification() { + match backend().apply_look(¤t_look()) { + Ok(drawn) => BORDER_DRAWN.store(drawn, Ordering::SeqCst), + Err(error) => tracing::warn!("could not set how windows look: {error}"), + } +} + +/// Asks the backend for the look again, as [`send_notification`] does. Called when a border +/// setting changed. +/// +/// There are no border windows to destroy: the compositor draws the borders. The name is the one +/// its callers share with komorebi on the other platforms. +/// +/// # Errors +/// +/// Never returns an error: a failure is logged. +pub fn destroy_all_borders() -> eyre::Result<()> { + send_notification(); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_stored_colours_become_red_green_and_blue() { + let blue = pack(66, 165, 245); + let grey = pack(128, 128, 128); + + let look = look(true, 10, 12, blue, grey); + let border = look.border.unwrap(); + + assert_eq!(border.focused, (66, 165, 245)); + assert_eq!(border.unfocused, (128, 128, 128)); + assert_eq!((border.width, border.radius), (10, 12)); + } + + #[test] + fn a_negative_width_or_radius_is_none() { + let look = look(true, -4, -1, 0, 0); + let border = look.border.unwrap(); + assert_eq!((border.width, border.radius), (0, 0)); + } +} diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 62a8862e..9a5f0d22 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -469,6 +469,14 @@ pub enum SocketMessage { // WatchConfiguration(bool), // CompleteConfiguration, // AltFocusHack(bool), + #[serde(alias = "ActiveWindowBorder")] + Border(bool), + // #[serde(alias = "ActiveWindowBorderStyle")] + // BorderStyle(BorderStyle), + BorderWidth(i32), + BorderOffset(i32), + // BorderImplementation(BorderImplementation), + // InvisibleBorders(Rect), WorkAreaOffset(Rect), MonitorWorkAreaOffset(usize, Rect), WorkspaceWorkAreaOffset(usize, usize, Rect), @@ -494,6 +502,7 @@ pub enum SocketMessage { // IdentifyBorderOverflowApplication(ApplicationIdentifier, String), State, GlobalState, + VisibleWindows, MonitorInformation, Query(StateQuery), MouseFollowsFocus(bool), diff --git a/komorebi/src/kwin/effects.rs b/komorebi/src/kwin/effects.rs new file mode 100644 index 00000000..678a72df --- /dev/null +++ b/komorebi/src/kwin/effects.rs @@ -0,0 +1,334 @@ +//! The KWin effect that draws komorebi's borders. +//! +//! komorebi draws no border itself. A compositor effect does, and this module configures it: +//! **KDE Rounded Corners** ([`ROUNDED_CORNERS`]) draws the border, its outer outline, outside the +//! window, in the gap komorebi leaves between tiles. [`border_settings`] has the settings. +//! +//! [`EffectsState::apply`] writes the effect's settings into `kwinrc` through [`Kwinrc`], loads the +//! effect if it is not loaded, and tells it to read its settings again. It always does the last +//! step: KWin keeps the copy of `kwinrc` it read when it started, and an effect reads its settings +//! from that copy until it is told to reconfigure, even one loaded a moment ago. +//! +//! The effect does not come with KWin, and KWin discovers effects only when it starts: an effect +//! 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. +//! +//! # What is guaranteed, and by what +//! +//! | Rule | Enforced by | Proof | +//! |---|---|---| +//! | No outline is drawn inside the window, over its title bar | [`border_settings`] sets every inner outline to 0 | `kwin::effects::tests::the_border_is_the_outer_outline_and_nothing_is_drawn_inside_the_window` | +//! | The border is never thicker than the effect can draw | [`border_settings`] clamps the width to `0..=20` | `kwin::effects::tests::a_border_thicker_than_the_effect_can_draw_is_the_thickest_it_can` | +//! | The same look asked for twice sends nothing to KWin | [`EffectsState::apply`] compares with the last look applied | no test | +//! | An effect komorebi loaded is unloaded when komorebi exits | [`EffectsState::finish`], called by the KWin backend when it shuts down | the `vm-look` VM suite | +//! | An effect the user had loaded stays loaded, with the user's settings | [`EffectsState::finish`] unloads only the effects komorebi loaded, and puts the settings back | no test | +//! | The user's settings of an effect are put back when komorebi stops using it or exits, even after a crash | [`Kwinrc`], which keeps the first value of every key it sets in a backup file | `kwin::kwinrc::tests::a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run` | +//! +//! At time of writing (2026-10-27) the stock KDE Rounded Corners in nixpkgs is 0.10.0, which draws +//! the border about 24 pixels too low on KWin 6.8; `nix/kde-rounded-corners.nix` builds 0.11.0. + +#![deny(missing_docs)] + +use super::kwinrc::Kwinrc; +use crate::backend::BorderLook; +use crate::backend::Look; +use color_eyre::eyre; +use zbus::Connection; +use zbus::proxy::Proxy; + +/// The plugin id of KDE Rounded Corners, the effect that draws the border. +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 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 +/// where the texture is transparent), which caps the thickness at 20 pixels. This was read from +/// screenshots of a KWin 6.8.1 session, at time of writing (2026-10-27). +const MAX_OUTLINE: i32 = 20; + +/// The state komorebi keeps of the effect: the look it last applied, and what it has to undo when +/// it exits. +/// +/// The KWin backend keeps one for the life of the connection to KWin. The default is the state of +/// a komorebi that has told the effects nothing. +#[derive(Default)] +pub struct EffectsState { + /// The look last applied, so that asking for it again does nothing. + last: Option, + /// Whether borders were being drawn after [`EffectsState::last`] was applied. + drawn: bool, + /// The effects komorebi loaded, which it unloads when it is done. + loaded_by_us: Vec<&'static str>, + /// The effects komorebi found missing, so that each is reported once. + missing: Vec<&'static str>, +} + +/// Returns the settings of KDE Rounded Corners, as `kwinrc` keys and values, for this border. +/// +/// Every outline is set, not only the one komorebi uses: the effect's defaults draw a one pixel +/// black outline *inside* the window, over its title bar and contents, which is what an +/// unconfigured install looks like. The border is the outer outline, outside the window, in the gap +/// komorebi leaves between tiles. The width is clamped to `0..=20`, the thickest the effect can +/// draw, and the colors are written as `r,g,b`. +/// +/// Covered by `kwin::effects::tests::the_border_is_the_outer_outline_and_nothing_is_drawn_inside_the_window` +/// and `kwin::effects::tests::a_border_thicker_than_the_effect_can_draw_is_the_thickest_it_can`. +pub fn border_settings(border: &BorderLook) -> Vec<(&'static str, String)> { + let width = border.width.clamp(0, MAX_OUTLINE).to_string(); + let colour = |(r, g, b): (u8, u8, u8)| format!("{r},{g},{b}"); + let off = || "0".to_string(); + let t = || "true".to_string(); + let f = || "false".to_string(); + + vec![ + ("Size", border.radius.to_string()), + ("InactiveCornerRadius", border.radius.to_string()), + // nothing inside the window + ("OutlineThickness", off()), + ("InactiveOutlineThickness", off()), + ("SecondOutlineThickness", off()), + ("InactiveSecondOutlineThickness", off()), + // the border, outside it + ("OuterOutlineThickness", width.clone()), + ("InactiveOuterOutlineThickness", width), + ("OuterOutlineColor", colour(border.focused)), + ("InactiveOuterOutlineColor", colour(border.unfocused)), + ("ActiveOuterOutlineAlpha", "255".to_string()), + ("InactiveOuterOutlineAlpha", "255".to_string()), + ("ActiveOuterOutlineUseCustom", t()), + ("InactiveOuterOutlineUseCustom", t()), + ("ActiveOuterOutlineUsePalette", f()), + ("InactiveOuterOutlineUsePalette", f()), + ("OuterOutlineIsGradient", f()), + ("InactiveOuterOutlineIsGradient", f()), + ] +} + +/// Returns a proxy for KWin's `/Effects` object, which loads, unloads and reconfigures effects. +async fn effects(connection: &Connection) -> eyre::Result> { + Ok(Proxy::new( + connection, + "org.kde.KWin", + "/Effects", + "org.kde.kwin.Effects", + ) + .await?) +} + +/// Returns true if and only if KWin has the effect installed (it found it when it started). A +/// failed call counts as not installed. +async fn supported(proxy: &Proxy<'_>, name: &str) -> bool { + proxy + .call::<_, _, bool>("isEffectSupported", &(name,)) + .await + .unwrap_or(false) +} + +/// Returns true if and only if the effect is loaded. A failed call counts as not loaded. +async fn loaded(proxy: &Proxy<'_>, name: &str) -> bool { + proxy + .call::<_, _, bool>("isEffectLoaded", &(name,)) + .await + .unwrap_or(false) +} + +impl EffectsState { + /// Brings the effect in line with `look`, and returns true if and only if borders are being + /// drawn afterwards. + /// + /// A look with no border stops the use of the effect (see [`EffectsState::disable`]); one with a + /// border writes the effect's settings and has it running (see [`EffectsState::enable`]). The + /// same look as the last one does nothing. + /// + /// # Errors + /// + /// Returns an error if and only if there is no proxy for KWin's `/Effects` object. Everything + /// that goes wrong with the effect (not installed, settings not written, not loaded) is logged, + /// and the function still returns whether borders are drawn. + pub async fn apply( + &mut self, + connection: &Connection, + kwinrc: &Kwinrc, + look: &Look, + ) -> eyre::Result { + if self.last.as_ref() == Some(look) { + return Ok(self.drawn); + } + + let proxy = effects(connection).await?; + + self.drawn = match &look.border { + Some(border) => { + self.enable( + &proxy, + kwinrc, + ROUNDED_CORNERS, + ROUNDED_CORNERS_GROUP, + &border_settings(border), + ) + .await + } + None => { + self.disable(&proxy, kwinrc, ROUNDED_CORNERS, ROUNDED_CORNERS_GROUP) + .await; + false + } + }; + + self.last = Some(look.clone()); + Ok(self.drawn) + } + + /// Gives the effect these settings and has it running, and returns true if and only if it is + /// running with them. + /// + /// Returns false, and logs why, when the effect is not installed (reported once), when its + /// settings cannot be written, or when KWin does not load it. + async fn enable( + &mut self, + proxy: &Proxy<'_>, + kwinrc: &Kwinrc, + effect: &'static str, + group: &str, + settings: &[(&'static str, String)], + ) -> bool { + if !supported(proxy, effect).await { + if !self.missing.contains(&effect) { + self.missing.push(effect); + tracing::info!( + "the {effect} effect is not installed (KWin finds effects when it starts), \ + so it is not used" + ); + } + return false; + } + + if let Err(error) = kwinrc.set(group, settings) { + tracing::warn!("could not write the settings of {effect}: {error}"); + return false; + } + + if !loaded(proxy, effect).await { + match proxy.call::<_, _, bool>("loadEffect", &(effect,)).await { + Ok(true) => { + self.loaded_by_us.push(effect); + tracing::info!("loaded the {effect} effect"); + } + other => { + tracing::warn!("KWin would not load the {effect} effect: {other:?}"); + return false; + } + } + } + + // KWin's own copy of kwinrc is as it was when it started, and what the effect reads when + // it loads comes from there: the settings only reach it by being told to read them again, + // even for an effect loaded a moment ago + let _ = proxy.call_method("reconfigureEffect", &(effect,)).await; + + true + } + + /// Stops using the effect: unloads it if komorebi loaded it, and puts the user's settings for + /// it back, telling it to read them again if it is still loaded. + async fn disable( + &mut self, + proxy: &Proxy<'_>, + kwinrc: &Kwinrc, + effect: &'static str, + group: &str, + ) { + if let Some(at) = self.loaded_by_us.iter().position(|e| *e == effect) { + self.loaded_by_us.remove(at); + let _ = proxy.call_method("unloadEffect", &(effect,)).await; + } + + if kwinrc.restore_group(group).unwrap_or(false) && loaded(proxy, effect).await { + let _ = proxy.call_method("reconfigureEffect", &(effect,)).await; + } + } + + /// Undoes what komorebi did to the effect, when it exits: unloads it if komorebi loaded it, and + /// puts back the user's settings. + /// + /// An effect the user had loaded keeps running, with the settings it had. Nothing is done when + /// there is no proxy for KWin's `/Effects` object. + pub async fn finish(&mut self, connection: &Connection, kwinrc: &Kwinrc) { + let Ok(proxy) = effects(connection).await else { + return; + }; + + for effect in std::mem::take(&mut self.loaded_by_us) { + let _ = proxy.call_method("unloadEffect", &(effect,)).await; + } + + // an effect the user had running keeps running, with the settings it had + if kwinrc.restore_group(ROUNDED_CORNERS_GROUP).unwrap_or(false) + && loaded(&proxy, ROUNDED_CORNERS).await + { + let _ = proxy + .call_method("reconfigureEffect", &(ROUNDED_CORNERS,)) + .await; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn settings(border: &BorderLook) -> std::collections::HashMap<&'static str, String> { + border_settings(border).into_iter().collect() + } + + #[test] + fn the_border_is_the_outer_outline_and_nothing_is_drawn_inside_the_window() { + let s = settings(&BorderLook { + width: 10, + radius: 12, + focused: (66, 165, 245), + unfocused: (128, 128, 128), + }); + + assert_eq!(s["OuterOutlineThickness"], "10"); + assert_eq!(s["InactiveOuterOutlineThickness"], "10"); + assert_eq!(s["OuterOutlineColor"], "66,165,245"); + assert_eq!(s["InactiveOuterOutlineColor"], "128,128,128"); + assert_eq!(s["Size"], "12"); + assert_eq!(s["InactiveCornerRadius"], "12"); + + // the effect's defaults put a black outline over the title bar: every inner one is off + for key in [ + "OutlineThickness", + "InactiveOutlineThickness", + "SecondOutlineThickness", + "InactiveSecondOutlineThickness", + ] { + assert_eq!(s[key], "0", "{key}"); + } + assert_eq!(s["ActiveOuterOutlineUseCustom"], "true"); + assert_eq!(s["ActiveOuterOutlineUsePalette"], "false"); + } + + #[test] + fn a_border_thicker_than_the_effect_can_draw_is_the_thickest_it_can() { + let s = settings(&BorderLook { + width: 400, + radius: 0, + focused: (0, 0, 0), + unfocused: (0, 0, 0), + }); + assert_eq!(s["OuterOutlineThickness"], MAX_OUTLINE.to_string()); + + let s = settings(&BorderLook { + width: -3, + radius: 0, + focused: (0, 0, 0), + unfocused: (0, 0, 0), + }); + assert_eq!(s["OuterOutlineThickness"], "0"); + } +} diff --git a/komorebi/src/kwin/kwinrc.rs b/komorebi/src/kwin/kwinrc.rs index 52ab76c7..d513f914 100644 --- a/komorebi/src/kwin/kwinrc.rs +++ b/komorebi/src/kwin/kwinrc.rs @@ -1,5 +1,5 @@ -//! KWin's configuration file, `kwinrc`, for the setting komorebi changes: per-output virtual -//! desktops. +//! KWin's configuration file, `kwinrc`, for the few settings komorebi changes: per-output virtual +//! desktops and the settings of the border effect. //! //! These are the user's settings, changed on their behalf, so [`Kwinrc::set`] records the value of //! every key the first time komorebi changes it, in a backup file, and [`Kwinrc::restore`] puts the @@ -22,6 +22,7 @@ //! | A key komorebi changed gets back the value it had before komorebi first changed it, and a key komorebi added is removed | [`Kwinrc::set`] records only the first value of a key; [`Kwinrc::restore`] | `kwin::kwinrc::tests::what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed` | //! | A crash loses none of the recorded values | the backup file, read by the next run | `kwin::kwinrc::tests::a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run` | //! | Only the line of the key changes; the rest of the file is left as it was | [`ini_set`], [`ini_unset`] | `kwin::kwinrc::tests::a_key_is_set_in_place_added_to_its_group_or_given_a_group`, `kwin::kwinrc::tests::a_key_is_removed_from_its_own_group_only` | +//! | One group can be put back while the others stay changed | [`Kwinrc::restore_group`] | `kwin::kwinrc::tests::one_group_can_be_put_back_while_the_others_stay_changed` | //! | KWin never reads a half-written file | [`Kwinrc`] writes a file beside `kwinrc` and renames it over it | no test | #![deny(missing_docs)] @@ -155,6 +156,37 @@ impl Kwinrc { Ok(true) } + /// Puts back what [`Kwinrc::set`] changed in one group, and returns true if and only if it + /// changed any key of the group. + /// + /// The other groups stay as komorebi changed them, and so does the backup of their values. + /// + /// # Errors + /// + /// Returns an error if `kwinrc` or the backup cannot be written. + pub fn restore_group(&self, group: &str) -> io::Result { + let mut backup = self.read_backup(); + let Some(keys) = backup.originals.remove(group) else { + return Ok(false); + }; + + let mut text = std::fs::read_to_string(&self.path).unwrap_or_default(); + for (key, original) in &keys { + text = match original { + Some(value) => ini_set(&text, group, key, value), + None => ini_unset(&text, group, key), + }; + } + self.write_file(&text)?; + + if backup.originals.is_empty() { + let _ = std::fs::remove_file(&self.backup); + } else { + self.write_backup(&backup)?; + } + Ok(true) + } + /// Returns the backup, or an empty one when there is no backup file or it cannot be read. fn read_backup(&self) -> Backup { std::fs::read_to_string(&self.backup) @@ -422,4 +454,30 @@ mod tests { assert_eq!(ini_value(&back, "Windows", "K").as_deref(), Some("orig")); let _ = std::fs::remove_dir_all(&d); } + + #[test] + fn one_group_can_be_put_back_while_the_others_stay_changed() { + let d = dir("group"); + let rc = Kwinrc::new(d.join("kwinrc"), d.join("backup.json")); + std::fs::write(d.join("kwinrc"), "[Round-Corners]\nSize=8\n").unwrap(); + + rc.set("Round-Corners", &[("Size", "20".into())]).unwrap(); + rc.set("Windows", &[("PerOutputVirtualDesktops", "true".into())]) + .unwrap(); + + assert!(rc.restore_group("Round-Corners").unwrap()); + let text = std::fs::read_to_string(d.join("kwinrc")).unwrap(); + assert_eq!( + ini_value(&text, "Round-Corners", "Size").as_deref(), + Some("8") + ); + assert!(rc.is_on("Windows", "PerOutputVirtualDesktops")); + + // nothing of it left to put back, and the other group still can be + assert!(!rc.restore_group("Round-Corners").unwrap()); + assert!(d.join("backup.json").exists()); + assert!(rc.restore().unwrap()); + assert!(!d.join("backup.json").exists()); + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index e3fc814f..a75234d6 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -52,16 +52,22 @@ //! [`WorkspaceChange`]: crate::window_manager_event::WindowManagerEvent::WorkspaceChange //! [`WorkspaceMove`]: crate::window_manager_event::WindowManagerEvent::WorkspaceMove //! +//! 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`]). +//! //! `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. #![deny(missing_docs)] +mod effects; mod kwinrc; pub mod state; use crate::DATA_DIR; use crate::backend::Backend; +use crate::backend::Look; use crate::backend::MonitorInfo; use crate::backend::WindowInfo; use crate::core::Rect; @@ -129,6 +135,8 @@ struct Shared { connection: Mutex>, /// the user's `kwinrc`, for the settings komorebi changes and puts back kwinrc: Option, + /// what komorebi has told the border effect, and has to undo when it exits + effects: tokio::sync::Mutex, } impl Shared { @@ -331,6 +339,7 @@ pub fn connect() -> eyre::Result> { alive: AtomicBool::new(true), connection: Mutex::new(None), kwinrc: kwinrc::Kwinrc::user(&DATA_DIR), + effects: tokio::sync::Mutex::new(effects::EffectsState::default()), }); let (started_tx, started_rx) = std::sync::mpsc::channel::>(); @@ -877,6 +886,20 @@ impl Backend for KWinBackend { Ok(()) } + fn apply_look(&self, look: &Look) -> eyre::Result { + let shared = self.shared.clone(); + let look = look.clone(); + + self.shared.block_on(async move { + let Some(kwinrc) = &shared.kwinrc else { + return Ok(false); + }; + let connection = shared.connection().await?; + let mut effects = shared.effects.lock().await; + effects.apply(&connection, kwinrc, &look).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, @@ -900,10 +923,17 @@ impl Backend for KWinBackend { tracing::warn!("could not remove the parking desktop: {error}"); } - // every setting of KWin's that komorebi changed + // the effects komorebi loaded, and every setting of KWin's it changed if let Ok(connection) = shared.connection().await && let Some(kwinrc) = &shared.kwinrc { + shared + .effects + .lock() + .await + .finish(&connection, kwinrc) + .await; + match kwinrc.restore() { Ok(true) => kwin_reconfigure(&connection).await, Ok(false) => {} @@ -961,6 +991,7 @@ mod tests { alive: AtomicBool::new(true), connection: Mutex::new(None), kwinrc: None, + effects: tokio::sync::Mutex::new(effects::EffectsState::default()), }); (runtime, KWinBackend { shared }) diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index be23ffb4..9695b297 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -12,6 +12,8 @@ //! [`window_manager_event_listener`]. //! //! On KDE Plasma the backend is [`kwin::KWinBackend`], which talks to a script it loads into KWin. +//! The compositor also draws what the windows look like: [`border_manager`] asks the backend for +//! the borders. //! //! The daemon also listens on a socket, `komorebi.sock` in [`struct@DATA_DIR`], for the messages //! in [`core::SocketMessage`]: [`process_command`] reads them and answers, with the window @@ -54,6 +56,7 @@ use std::sync::atomic::AtomicI32; pub mod ring; pub mod backend; +pub mod border_manager; pub mod container; pub mod core; pub mod desktop; diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index ee15ef6b..5ab071a2 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -10,10 +10,10 @@ //! The daemon starts from `komorebi.json`: the file `--config` names, or else the one in //! [`struct@HOME_DIR`] when there is one ([`komorebi::static_config`]), which it reloads whenever //! it changes. Without a file it runs on its defaults. It loads the monitors and the windows -//! that are open, gives each monitor the configuration the file has for it, tiles them, listens for -//! messages on `komorebi.sock` in [`struct@DATA_DIR`], handles the events the backend reports on -//! a thread of their own, and runs until it is stopped, with `SIGINT`, `SIGTERM` or a `Stop` -//! message. +//! that are open, gives each monitor the configuration the file has for it, asks for the borders +//! it draws ([`komorebi::border_manager`]), tiles the windows, listens for messages on +//! `komorebi.sock` in [`struct@DATA_DIR`], handles the events the backend reports on a thread of +//! their own, and runs until it is stopped, with `SIGINT`, `SIGTERM` or a `Stop` message. //! //! It logs to standard output and to a file a day in [`struct@LOG_DIR`], which `komorebic log` //! follows. @@ -31,6 +31,7 @@ use komorebi::HOME_DIR; use komorebi::LOG_DIR; use komorebi::backend; use komorebi::backend::fake::FakeBackend; +use komorebi::border_manager; use komorebi::core::pathext::replace_env_in_path; use komorebi::process_command::listen_for_commands; use komorebi::process_event::listen_for_events; @@ -227,6 +228,10 @@ fn main() -> eyre::Result<()> { // them): the compositor needs a desktop for each wm.lock().sync_workspace_desktops(); + // how windows are to look (borders) is handed to the compositor before the first layout, which + // leaves room for a border that is being drawn + border_manager::send_notification(); + wm.lock().retile_all(false)?; listen_for_commands(wm.clone()); diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 420d3645..d2e1484b 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -3,8 +3,8 @@ //! A monitor has the bounds and the work area the backend reports for it //! ([`MonitorInfo`](crate::backend::MonitorInfo)), and shows one of its workspaces, the focused //! one. Before the focused workspace is tiled it is given the monitor's work area, the monitor's -//! padding (or [`DEFAULT_CONTAINER_PADDING`] and [`DEFAULT_WORKSPACE_PADDING`]) and the work area -//! offset ([`WorkspaceGlobals`]). +//! padding (or [`DEFAULT_CONTAINER_PADDING`] and [`DEFAULT_WORKSPACE_PADDING`]), the work area +//! offset and, while the compositor draws borders, the room they take ([`WorkspaceGlobals`]). //! //! Workspace `i` of a monitor is the compositor's virtual desktop `i` on that monitor. Showing //! another workspace ([`Monitor::load_focused_workspace`]) puts every window on the desktop of the @@ -14,6 +14,9 @@ use crate::DEFAULT_CONTAINER_PADDING; use crate::DEFAULT_WORKSPACE_PADDING; use crate::backend::backend; +use crate::border_manager::BORDER_DRAWN; +use crate::border_manager::BORDER_OFFSET; +use crate::border_manager::BORDER_WIDTH; use crate::container::Container; use crate::core::DefaultLayout; use crate::core::FloatingLayerBehaviour; @@ -183,6 +186,15 @@ impl Monitor { let workspace_padding = self .workspace_padding .or(Some(DEFAULT_WORKSPACE_PADDING.load(Ordering::Relaxed))); + // a border the compositor draws outside the window takes room that the window leaves + let (border_width, border_offset) = if BORDER_DRAWN.load(Ordering::SeqCst) { + ( + BORDER_WIDTH.load(Ordering::SeqCst), + BORDER_OFFSET.load(Ordering::SeqCst), + ) + } else { + (0, 0) + }; let work_area = self.work_area_size; let work_area_offset = self.work_area_offset.or(offset); let window_based_work_area_offset = self.window_based_work_area_offset; @@ -193,6 +205,8 @@ impl Monitor { workspace.globals = WorkspaceGlobals { container_padding, workspace_padding, + border_width, + border_offset, work_area, work_area_offset, window_based_work_area_offset, @@ -452,6 +466,7 @@ impl Monitor { let workspace_padding = self .workspace_padding .or(Some(DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst))); + let (border_width, border_offset) = (0, 0); let work_area = self.work_area_size; let work_area_offset = self.work_area_offset.or(offset); let window_based_work_area_offset = self.window_based_work_area_offset; @@ -462,6 +477,8 @@ impl Monitor { workspace.globals = WorkspaceGlobals { container_padding, workspace_padding, + border_width, + border_offset, work_area, work_area_offset, window_based_work_area_offset, diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 4e93cd18..ab1709dd 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -8,6 +8,8 @@ //! //! - **State**: the window manager's [`State`], as JSON. //! - **MonitorInformation**: the id, the name and the bounds of each monitor, as JSON. +//! - **VisibleWindows**: what the compositor says about each window that can be seen on the +//! workspace each monitor shows, by the id of the monitor, as JSON. //! - **Query**: one value as text, the answer to a [`StateQuery`]. //! - **GlobalState**: the ignore and the manage rules and the data directory ([`GlobalState`]), as //! JSON. @@ -174,6 +176,10 @@ //! **CycleMoveWorkspaceToMonitor** and **SwapWorkspacesToMonitorNumber** move workspaces //! between monitors. **DisplayIndexPreference** gives a monitor an index, and **EagerFocus** //! focuses the first window of an executable on any workspace of any monitor. +//! - **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. //! - **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 @@ -196,6 +202,7 @@ use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; use crate::WORKSPACE_MATCHING_RULES; use crate::backend::backend; +use crate::border_manager; use crate::core::ApplicationIdentifier; use crate::core::Axis; use crate::core::Layout; @@ -227,6 +234,7 @@ use color_eyre::eyre; use color_eyre::eyre::Context; use color_eyre::eyre::OptionExt; use parking_lot::Mutex; +use std::collections::HashMap; use std::fs::File; use std::fs::OpenOptions; use std::io::BufRead; @@ -235,6 +243,7 @@ use std::num::NonZeroUsize; use std::os::unix::net::UnixStream; use std::str::FromStr; use std::sync::Arc; +use std::sync::atomic::Ordering; use std::time::Duration; use version::build; @@ -556,12 +565,14 @@ impl WindowManager { } SocketMessage::UnstackWindow => { self.remove_window_from_container()?; + border_manager::destroy_all_borders()?; } SocketMessage::StackAll => { self.stack_all()?; } SocketMessage::UnstackAll => { self.unstack_all(true)?; + border_manager::destroy_all_borders()?; } SocketMessage::CycleStack(direction) => { self.cycle_container_window_in_direction(direction)?; @@ -1323,6 +1334,21 @@ impl WindowManager { tracing::info!("replying to global state done"); } + SocketMessage::VisibleWindows => { + let mut monitor_visible_windows = HashMap::new(); + + for monitor in self.monitors() { + if let Some(ws) = monitor.focused_workspace() { + monitor_visible_windows + .insert(monitor.id, ws.visible_window_details().clone()); + } + } + + let visible_windows_state = serde_json::to_string_pretty(&monitor_visible_windows) + .unwrap_or_else(|error| error.to_string()); + + reply.write_all(visible_windows_state.as_bytes())?; + } SocketMessage::MonitorInformation => { let mut monitors = vec![]; for monitor in self.monitors() { @@ -1909,6 +1935,20 @@ impl WindowManager { reply.write_all(schema.as_bytes())?; } } + SocketMessage::Border(enable) => { + border_manager::BORDER_ENABLED.store(enable, Ordering::SeqCst); + if !enable { + border_manager::destroy_all_borders()?; + } + } + SocketMessage::BorderWidth(width) => { + border_manager::BORDER_WIDTH.store(width, Ordering::SeqCst); + border_manager::destroy_all_borders()?; + } + SocketMessage::BorderOffset(offset) => { + border_manager::BORDER_OFFSET.store(offset, Ordering::SeqCst); + border_manager::destroy_all_borders()?; + } } self.update_known_window_ids(); @@ -1921,6 +1961,8 @@ impl WindowManager { initial_state.has_been_modified(self.as_ref()), )?; + border_manager::send_notification(); + tracing::info!("processed command: {message}"); Ok(()) diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 98828607..39ba632a 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -48,7 +48,8 @@ //! [`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`]). +//! 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. //! //! [`Window::should_manage`]: crate::window::Window::should_manage //! [`Monitor::assign_windows_to_workspaces`]: crate::monitor::Monitor::assign_windows_to_workspaces @@ -60,6 +61,7 @@ use crate::NotificationEvent; use crate::REGEX_IDENTIFIERS; use crate::UNMANAGED_WINDOW_IDS; use crate::backend::backend; +use crate::border_manager; use crate::core::DefaultLayout; use crate::core::Layout; use crate::core::WindowContainerBehaviour; @@ -507,6 +509,8 @@ impl WindowManager { initial_state.has_been_modified(self.as_ref()), )?; + border_manager::send_notification(); + Ok(()) } } diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index 1f3a2ed3..b06b4f81 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -37,6 +37,7 @@ use crate::LAYOUT_DEFAULTS; use crate::MANAGE_IDENTIFIERS; use crate::REGEX_IDENTIFIERS; use crate::WORKSPACE_MATCHING_RULES; +use crate::border_manager; use crate::core::Axis; use crate::core::CrossBoundaryBehaviour; use crate::core::DefaultLayout; @@ -407,6 +408,32 @@ pub struct StaticConfig { /// need them: which windows to ignore, to manage and to float #[serde(skip_serializing_if = "Option::is_none")] pub app_specific_configuration_path: Option, + /// Width of window borders + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "active_window_border_width")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_WIDTH)))] + pub border_width: Option, + /// Offset of window borders + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "active_window_border_offset")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_OFFSET)))] + pub border_offset: Option, + /// Radius of window borders + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_RADIUS)))] + pub border_radius: Option, + /// Display window borders + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "active_window_border")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_ENABLED)))] + pub border: Option, + // /// Active window border style (default: System) + // #[serde(skip_serializing_if = "Option::is_none")] + // #[serde(alias = "active_window_border_style")] + // pub border_style: Option, + // /// Active window border implementation (default: Komorebi) + // #[serde(skip_serializing_if = "Option::is_none")] + // pub border_implementation: Option, /// Global default workspace padding #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_WORKSPACE_PADDING)))] @@ -528,6 +555,7 @@ impl From<&WindowManager> for StaticConfig { } Self { + // invisible_borders: None, resize_delta: Option::from(value.resize_delta), window_container_behaviour: Option::from( value.window_management_behaviour.current_behaviour, @@ -558,6 +586,13 @@ impl From<&WindowManager> for StaticConfig { // minimum_window_width: Some(window::MINIMUM_WIDTH.load(Ordering::SeqCst)), mouse_follows_focus: Option::from(value.mouse_follows_focus), app_specific_configuration_path: None, + border_width: Option::from(border_manager::BORDER_WIDTH.load(Ordering::SeqCst)), + border_offset: Option::from(border_manager::BORDER_OFFSET.load(Ordering::SeqCst)), + border_radius: Option::from(border_manager::BORDER_RADIUS.load(Ordering::SeqCst)), + border: Option::from(border_manager::BORDER_ENABLED.load(Ordering::SeqCst)), + // border_style: Option::from(STYLE.load()), + // border_z_order: None, + // border_implementation: Option::from(IMPLEMENTATION.load()), default_workspace_padding: Option::from( DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst), ), @@ -645,6 +680,47 @@ impl StaticConfig { LAYOUT_DEFAULTS.lock().clear(); } + if let Some(border_width) = self.border_width { + border_manager::BORDER_WIDTH.store(border_width, Ordering::SeqCst); + } + + if let Some(border_offset) = self.border_offset { + border_manager::BORDER_OFFSET.store(border_offset, Ordering::SeqCst); + } + + if let Some(border_radius) = self.border_radius { + border_manager::BORDER_RADIUS.store(border_radius, Ordering::SeqCst); + } + + if let Some(border_enabled) = self.border { + border_manager::BORDER_ENABLED.store(border_enabled, Ordering::SeqCst); + } + + // STYLE.store(self.border_style.unwrap_or_default()); + // + // if !*WINDOWS_11 + // && matches!( + // self.border_implementation.unwrap_or_default(), + // BorderImplementation::Windows + // ) + // { + // tracing::error!( + // "BorderImplementation::Windows is only supported on Windows 11 and above" + // ); + // } else { + // IMPLEMENTATION.store(self.border_implementation.unwrap_or_default()); + // match IMPLEMENTATION.load() { + // BorderImplementation::Komorebi => { + // border_manager::destroy_all_borders()?; + // } + // BorderImplementation::Windows => { + // // TODO: figure out how to call wm.remove_all_accents here + // } + // } + // + // border_manager::send_notification(None); + // } + // let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); let mut manage_identifiers = MANAGE_IDENTIFIERS.lock(); @@ -1039,6 +1115,10 @@ impl StaticConfig { wm.enforce_workspace_rules()?; + if value.border == Some(true) { + border_manager::BORDER_ENABLED.store(true, Ordering::SeqCst); + } + Ok(()) } @@ -1153,6 +1233,10 @@ impl StaticConfig { wm.enforce_workspace_rules()?; + if let Some(border_enabled) = value.border { + border_manager::BORDER_ENABLED.store(border_enabled, Ordering::SeqCst); + } + wm.window_management_behaviour.current_behaviour = value.window_container_behaviour.unwrap_or_default(); wm.window_management_behaviour.float_override = value.float_override.unwrap_or_default(); @@ -1185,7 +1269,7 @@ impl StaticConfig { wm.update_focused_workspace_by_monitor_idx(i)?; } - // to apply the new layouts, padding and offsets + // to update the borders wm.retile_all(true)?; Ok(()) diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 639594b4..a073f5b5 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -56,6 +56,7 @@ use crate::SUBSCRIPTION_SOCKETS; use crate::UNMANAGED_WINDOW_IDS; use crate::WORKSPACE_MATCHING_RULES; use crate::backend::backend; +use crate::border_manager; use crate::container::Container; use crate::core::Arrangement; use crate::core::Axis; @@ -1937,7 +1938,8 @@ impl WindowManager { } /// Tiles the focused workspace of every monitor, without the resize adjustments of its - /// containers unless `preserve_resize_dimensions` is set + /// containers unless `preserve_resize_dimensions` is set, and asks the backend for the look + /// again ([`border_manager::destroy_all_borders`]) #[tracing::instrument(skip(self))] pub fn retile_all(&mut self, preserve_resize_dimensions: bool) -> eyre::Result<()> { let offset = self.work_area_offset; @@ -1964,6 +1966,8 @@ impl WindowManager { workspace.update()?; } + border_manager::destroy_all_borders()?; + Ok(()) } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 937ec7de..bedb8767 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -27,6 +27,7 @@ use crate::lockable_sequence::LockableSequence; use crate::ring::Ring; use crate::static_config::WorkspaceConfig; use crate::window::Window; +use crate::window::WindowDetails; use color_eyre::eyre; use color_eyre::eyre::OptionExt; use serde::Deserialize; @@ -182,10 +183,13 @@ pub enum WorkspaceWindowLocation { #[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq)] /// The work area a monitor gives the workspace it shows, the padding and the offset the -/// workspace falls back to when it sets none of its own, and the monitor's window-based offset +/// workspace falls back to when it sets none of its own, the monitor's window-based offset, and +/// the room around each window that a border drawn by the compositor takes pub struct WorkspaceGlobals { pub container_padding: Option, pub workspace_padding: Option, + pub border_width: i32, + pub border_offset: i32, pub work_area: Rect, pub work_area_offset: Option, pub window_based_work_area_offset: Option, @@ -1446,9 +1450,11 @@ impl Workspace { /// Containers that have no windows left are dropped first, except the one a preselection /// reserved, and so is a window that is in more than one container. A tile is clamped to the /// work area, so it cannot bleed onto a neighboring monitor, except in the scrolling layout, - /// whose strip runs past the edges of the work area. A window whose tile is out of view while - /// part of the window is in view is first centered in the work area. A workspace whose tiling - /// is off ([`Workspace::tile`] is false) moves no window. + /// whose strip runs past the edges of the work area. Each tile then gives up the room a border + /// drawn by the compositor takes on every side, the border's width and its offset + /// ([`WorkspaceGlobals`]; nothing when no border is drawn). A window whose tile is out of view + /// while part of the window is in view is first centered in the work area. A workspace whose + /// tiling is off ([`Workspace::tile`] is false) moves no window. /// /// While the workspace has a monocle container ([`Workspace::monocle_container`]), the window /// in front of it is put on the work area, less the container padding, and the other containers @@ -1482,6 +1488,8 @@ impl Workspace { .workspace_padding .or(self.globals.workspace_padding) .unwrap_or_default(); + let border_width = self.globals.border_width; + let border_offset = self.globals.border_offset; let work_area = self.globals.work_area; let mut rules_work_area_offset = None; @@ -1571,6 +1579,8 @@ impl Workspace { if let Some(container) = self.monocle_container.as_mut() { if let Some(window) = container.focused_window_mut() { adjusted_work_area.add_padding(container_padding); + adjusted_work_area.add_padding(border_offset); + adjusted_work_area.add_padding(border_width); window.set_position(&adjusted_work_area)?; }; } else if let Some(window) = self.maximized_window { @@ -1637,6 +1647,9 @@ impl Workspace { } } + layout.add_padding(border_offset); + layout.add_padding(border_width); + for window in container.windows_mut() { let current_rect = window.rect().unwrap_or_default(); let current_percentage = @@ -1712,6 +1725,40 @@ impl Workspace { vec } + + /// What the compositor says about each window [`Workspace::visible_windows`] has, as + /// `komorebic visible-windows` shows it: the maximized window, the one at the top of the + /// monocle container, the one at the top of each container, and every floating window. A + /// container that has no window is left out. + pub fn visible_window_details(&self) -> Vec { + let mut vec: Vec = vec![]; + + if let Some(maximized) = &self.maximized_window { + let details = maximized.into(); + vec.push(details); + } + + if let Some(monocle) = &self.monocle_container + && let Some(focused) = monocle.focused_window() + { + let details = focused.into(); + vec.push(details); + } + + for container in self.containers() { + if let Some(focused) = container.focused_window() { + let details = focused.into(); + vec.push(details); + } + } + + for window in self.floating_windows() { + let details = window.into(); + vec.push(details); + } + + vec + } } impl Workspace { @@ -2748,6 +2795,55 @@ mod tests { assert!(contains); } + #[test] + fn test_visible_windows() { + let mut workspace = Workspace::default(); + + { + // Create and add a default Container with 2 windows + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(100)); + container.windows_mut().push_back(Window::from(200)); + workspace.add_container_to_back(container); + } + + { + // visible_windows should return None and 100 + let visible_windows = workspace.visible_windows(); + assert_eq!(visible_windows.len(), 2); + assert!(visible_windows[0].is_none()); + assert_eq!(visible_windows[1].unwrap().id, 100); + } + + { + // Create and add a default Container with 1 window + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(300)); + workspace.add_container_to_back(container); + } + + { + // visible_windows should return None, 100, and 300 + let visible_windows = workspace.visible_windows(); + assert_eq!(visible_windows.len(), 3); + assert!(visible_windows[0].is_none()); + assert_eq!(visible_windows[1].unwrap().id, 100); + assert_eq!(visible_windows[2].unwrap().id, 300); + } + + // Maximize window 200 + workspace.maximized_window = Some(Window::from(200)); + + { + // visible_windows should return 200, 100, and 300 + let visible_windows = workspace.visible_windows(); + assert_eq!(visible_windows.len(), 3); + assert_eq!(visible_windows[0].unwrap().id, 200); + assert_eq!(visible_windows[1].unwrap().id, 100); + assert_eq!(visible_windows[2].unwrap().id, 300); + } + } + #[test] fn test_layout_boundary_clamping() { use crate::core::Rect; diff --git a/komorebi/tests/border_commands.rs b/komorebi/tests/border_commands.rs new file mode 100644 index 00000000..ba830457 --- /dev/null +++ b/komorebi/tests/border_commands.rs @@ -0,0 +1,59 @@ +//! The messages that set the border are carried out, and the compositor is asked for the look they +//! make. +//! +//! This file has one test because it changes the process-wide border settings, which every other +//! test that tiles windows would see. + +use komorebi::backend::BorderLook; +use komorebi::backend::Look; +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::border_manager; +use komorebi::core::SocketMessage; +use komorebi::window_manager::WindowManager; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +#[test] +fn the_border_messages_set_the_border_and_the_compositor_is_asked_for_it() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.set_borders_drawn(true); + + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = std::path::PathBuf::from(format!("/tmp/kmb-bcmd-{}.sock", std::process::id())); + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + let send = |wm: &mut WindowManager, message| { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); + }; + let last_look = || { + fake.commands() + .into_iter() + .rev() + .find_map(|command| match command { + Command::ApplyLook(look) => Some(look), + _ => None, + }) + .expect("the compositor was asked for a look") + }; + + send(&mut wm, SocketMessage::BorderWidth(8)); + send(&mut wm, SocketMessage::BorderOffset(3)); + assert_eq!(border_manager::BORDER_WIDTH.load(Ordering::SeqCst), 8); + assert_eq!(border_manager::BORDER_OFFSET.load(Ordering::SeqCst), 3); + assert!(border_manager::BORDER_DRAWN.load(Ordering::SeqCst)); + let border: BorderLook = last_look().border.expect("borders are on"); + assert_eq!(border.width, 8); + + send(&mut wm, SocketMessage::Border(false)); + assert_eq!(last_look(), Look::default()); + assert!(!border_manager::BORDER_DRAWN.load(Ordering::SeqCst)); + + send(&mut wm, SocketMessage::Border(true)); + assert_eq!(last_look().border, Some(border)); + assert!(border_manager::BORDER_DRAWN.load(Ordering::SeqCst)); +} diff --git a/komorebi/tests/border_config.rs b/komorebi/tests/border_config.rs new file mode 100644 index 00000000..80079462 --- /dev/null +++ b/komorebi/tests/border_config.rs @@ -0,0 +1,97 @@ +//! The border keys of `komorebi.json` are the border settings: the file sets them when the daemon +//! starts and when it is read again, a key it leaves out leaves the setting as it is, and the +//! settings come out again in the configuration the daemon generates. +//! +//! This file has one test because it changes the process-wide border settings, which every other +//! test that tiles windows would see. + +use color_eyre::eyre; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::border_manager; +use komorebi::static_config::StaticConfig; +use komorebi::window_manager::WindowManager; +use parking_lot::Mutex; +use std::os::unix::net::UnixListener; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +fn write_config(name: &str, json: &str) -> PathBuf { + let path = PathBuf::from(format!("/tmp/kmb-{name}-{}.json", std::process::id())); + std::fs::write(&path, json).unwrap(); + path +} + +#[test] +fn the_border_keys_of_the_file_are_the_border_settings() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.set_borders_drawn(true); + + let path = write_config( + "set", + r#"{ "border": true, "border_width": 6, "border_offset": 2, "border_radius": 12 }"#, + ); + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = PathBuf::from(format!("/tmp/kmb-config-{}.sock", std::process::id())); + let listener = UnixListener::bind(&socket).unwrap(); + + let wm = with_backend(fake.clone(), || -> eyre::Result { + let mut wm = StaticConfig::preload(&path, receiver, Some(listener))?; + wm.init()?; + Ok(wm) + }) + .unwrap(); + let wm = Arc::new(Mutex::new(wm)); + StaticConfig::postload(&path, &wm).unwrap(); + let _ = std::fs::remove_file(&socket); + + // the file made the settings, and the settings make the look + assert_eq!(border_manager::BORDER_WIDTH.load(Ordering::SeqCst), 6); + assert_eq!(border_manager::BORDER_OFFSET.load(Ordering::SeqCst), 2); + assert_eq!(border_manager::BORDER_RADIUS.load(Ordering::SeqCst), 12); + let border = border_manager::current_look() + .border + .expect("borders are on"); + assert_eq!((border.width, border.radius), (6, 12)); + + // and they come out again in the generated configuration + let generated = StaticConfig::from(&*wm.lock()); + assert_eq!(generated.border, Some(true)); + assert_eq!(generated.border_width, Some(6)); + assert_eq!(generated.border_offset, Some(2)); + assert_eq!(generated.border_radius, Some(12)); + + // the old names of the keys are the same keys + let aliased = StaticConfig::read_raw( + r#"{ "active_window_border": false, "active_window_border_width": 4, + "active_window_border_offset": 1 }"#, + ) + .unwrap(); + assert_eq!(aliased.border, Some(false)); + assert_eq!(aliased.border_width, Some(4)); + assert_eq!(aliased.border_offset, Some(1)); + + // a file that is read again changes what it sets, with borders off asking for no border + let other = write_config("other", r#"{ "border": false, "border_width": 3 }"#); + with_backend(fake.clone(), || { + StaticConfig::reload(&other, &mut wm.lock()).unwrap(); + }); + assert_eq!(border_manager::BORDER_WIDTH.load(Ordering::SeqCst), 3); + assert!(!border_manager::BORDER_ENABLED.load(Ordering::SeqCst)); + assert_eq!(border_manager::current_look().border, None); + + // and one that leaves the keys out leaves the settings as they were + let empty = write_config("empty", "{}"); + with_backend(fake.clone(), || { + StaticConfig::reload(&empty, &mut wm.lock()).unwrap(); + }); + assert_eq!(border_manager::BORDER_WIDTH.load(Ordering::SeqCst), 3); + assert_eq!(border_manager::BORDER_OFFSET.load(Ordering::SeqCst), 2); + assert_eq!(border_manager::BORDER_RADIUS.load(Ordering::SeqCst), 12); + assert!(!border_manager::BORDER_ENABLED.load(Ordering::SeqCst)); + + for file in [path, other, empty] { + let _ = std::fs::remove_file(file); + } +} diff --git a/komorebi/tests/borders.rs b/komorebi/tests/borders.rs new file mode 100644 index 00000000..1bb8dea9 --- /dev/null +++ b/komorebi/tests/borders.rs @@ -0,0 +1,73 @@ +//! The layout leaves room for a border the compositor draws outside each window, and only then. +//! +//! This file has one test because it changes the process-wide border settings, which every other +//! test that tiles windows would see. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::border_manager; +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; +use std::sync::atomic::Ordering; + +#[test] +fn a_border_the_compositor_draws_takes_room_around_each_window_and_none_is_taken_without_one() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.set_borders_drawn(true); + + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = std::path::PathBuf::from(format!("/tmp/kmb-borders-{}.sock", std::process::id())); + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + // opened after the window manager started, so that it is managed (and tiled) by this event + fake.open_window(90_001, "foot", "foot", "terminal"); + with_backend(fake.clone(), || { + wm.process_event(WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(90_001), + )) + .unwrap(); + }); + let without = fake.rect_of(90_001).unwrap(); + + // borders on, and the compositor says it is drawing them + border_manager::BORDER_WIDTH.store(10, Ordering::SeqCst); + border_manager::BORDER_OFFSET.store(2, Ordering::SeqCst); + with_backend(fake.clone(), || { + border_manager::send_notification(); + wm.retile_all(false).unwrap(); + }); + assert!(border_manager::BORDER_DRAWN.load(Ordering::SeqCst)); + + let with = fake.rect_of(90_001).unwrap(); + let room = 10 + 2; + assert_eq!(with.left, without.left + room, "{without:?} -> {with:?}"); + assert_eq!(with.top, without.top + room, "{without:?} -> {with:?}"); + assert_eq!( + with.right, + without.right - 2 * room, + "{without:?} -> {with:?}" + ); + assert_eq!( + with.bottom, + without.bottom - 2 * room, + "{without:?} -> {with:?}" + ); + + // borders off: the room is given back + border_manager::BORDER_ENABLED.store(false, Ordering::SeqCst); + with_backend(fake.clone(), || { + border_manager::send_notification(); + wm.retile_all(false).unwrap(); + }); + assert!(!border_manager::BORDER_DRAWN.load(Ordering::SeqCst)); + assert_eq!(fake.rect_of(90_001).unwrap(), without); +} diff --git a/komorebi/tests/config_parity.rs b/komorebi/tests/config_parity.rs index 9d383ea2..b86afbbf 100644 --- a/komorebi/tests/config_parity.rs +++ b/komorebi/tests/config_parity.rs @@ -43,12 +43,8 @@ const WINDOWS_ONLY: &[&str] = &[ /// ignored until then. Each comment says which commit of the plan brings the feature, and takes /// the key off this list. const NOT_YET: &[&str] = &[ - // borders drawn by the compositor (43) - "border", + // a color for each kind of window's border, whose type is komorebi-themes' (49) "border_colours", - "border_offset", - "border_radius", - "border_width", // animation (45) "animation", // transparency (47) diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 469fa5cc..f52bba59 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -66,15 +66,19 @@ //! 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. //! //! `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 //! daemon stops, `session-float-rules` shows those rules and `clear-session-float-rules` removes -//! them, and `global-state` shows the rules the daemon has. `initial-workspace-rule`, -//! `initial-named-workspace-rule`, `workspace-rule` and `named-workspace-rule` send the windows of -//! an application to a workspace, when they open or always, `clear-workspace-rules`, -//! `clear-named-workspace-rules` and `clear-all-workspace-rules` take those rules away, and -//! `enforce-workspace-rules` applies them to the windows that are open. +//! them, and `global-state` shows the rules the daemon has. `visible-windows` shows the windows +//! that can be seen on the workspace each monitor shows. +//! +//! `initial-workspace-rule`, `initial-named-workspace-rule`, `workspace-rule` and +//! `named-workspace-rule` send the windows of an application to a workspace, when they open or +//! always, `clear-workspace-rules`, `clear-named-workspace-rules` and `clear-all-workspace-rules` +//! take those rules away, and `enforce-workspace-rules` applies them to the windows that are open. //! //! `workspace-layout-rule` and `named-workspace-layout-rule` make a workspace change layout once //! it has so many windows, and `clear-workspace-layout-rules` and @@ -719,6 +723,24 @@ struct LayoutRatios { rows: Option>, } +#[derive(Parser)] +struct Border { + #[clap(value_enum)] + boolean_state: BooleanState, +} + +#[derive(Parser)] +struct BorderWidth { + /// Desired width of the window border + width: i32, +} + +#[derive(Parser)] +struct BorderOffset { + /// Desired offset of the window border + offset: i32, +} + #[derive(Parser)] struct Docgen { /// Output directory for generated documentation files @@ -762,6 +784,8 @@ enum SubCommand { State, /// Show a JSON representation of the current global state GlobalState, + /// Show a JSON representation of visible windows + VisibleWindows, /// Show information about connected monitors #[clap(alias = "monitor-info")] MonitorInformation, @@ -1132,6 +1156,24 @@ enum SubCommand { ClearAllWorkspaceRules, /// Enforce all workspace rules, including initial workspace rules that have already been applied EnforceWorkspaceRules, + /// Enable or disable borders + #[clap(arg_required_else_help = true)] + #[clap(alias = "active-window-border")] + Border(Border), + /// Set the border width + #[clap(arg_required_else_help = true)] + #[clap(alias = "active-window-border-width")] + BorderWidth(BorderWidth), + /// Set the border offset + #[clap(arg_required_else_help = true)] + #[clap(alias = "active-window-border-offset")] + BorderOffset(BorderOffset), + // /// Set the border style + // #[clap(arg_required_else_help = true)] + // BorderStyle(BorderStyle), + // /// Set the border implementation + // #[clap(arg_required_else_help = true)] + // BorderImplementation(BorderImplementation), /// Enable or disable mouse follows focus on all workspaces #[clap(arg_required_else_help = true)] MouseFollowsFocus(MouseFollowsFocus), @@ -1623,6 +1665,9 @@ fn main() -> eyre::Result<()> { SubCommand::Query(args) => { print_query(&SocketMessage::Query(args.state_query)); } + SubCommand::VisibleWindows => { + print_query(&SocketMessage::VisibleWindows); + } SubCommand::MonitorInformation => { print_query(&SocketMessage::MonitorInformation); } @@ -1936,6 +1981,15 @@ fn main() -> eyre::Result<()> { SubCommand::LoadResize(args) => { send_message(&SocketMessage::Load(args.path))?; } + SubCommand::Border(args) => { + send_message(&SocketMessage::Border(args.boolean_state.into()))?; + } + SubCommand::BorderWidth(args) => { + send_message(&SocketMessage::BorderWidth(args.width))?; + } + SubCommand::BorderOffset(args) => { + send_message(&SocketMessage::BorderOffset(args.offset))?; + } } Ok(()) diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 2c4b823f..085e6447 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -476,6 +476,39 @@ fn global_state_and_session_float_rules_print_the_answer_of_the_daemon() { } } +#[test] +fn the_border_subcommands_send_what_they_are_given() { + sends(&["border", "enable"], r#"{"type":"Border","content":true}"#); + sends( + &["border", "disable"], + r#"{"type":"Border","content":false}"#, + ); + sends( + &["active-window-border", "enable"], + r#"{"type":"Border","content":true}"#, + ); + sends( + &["border-width", "8"], + r#"{"type":"BorderWidth","content":8}"#, + ); + sends( + &["border-offset", "2"], + r#"{"type":"BorderOffset","content":2}"#, + ); +} + +#[test] +fn visible_windows_prints_the_answer_of_the_daemon() { + let runtime = Runtime::new(); + let daemon = runtime.serve("{}"); + + let output = runtime.komorebic(&["visible-windows"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!(daemon.join().unwrap(), r#"{"type":"VisibleWindows"}"#); + assert_eq!(stdout(&output), "{}\n"); +} + #[test] fn the_subcommands_about_the_focused_window_and_pausing_send_their_message() { sends(&["minimize"], r#"{"type":"Minimize"}"#); @@ -982,6 +1015,9 @@ 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-offset.md", + "border-width.md", + "border.md", "cancel-preselect.md", "change-layout.md", "clear-all-workspace-rules.md", @@ -1112,6 +1148,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "unstack-all.md", "unstack.md", "unsubscribe-socket.md", + "visible-windows.md", "workspace-layout-rule.md", "workspace-layout.md", "workspace-name.md", diff --git a/nix/kde-rounded-corners.nix b/nix/kde-rounded-corners.nix new file mode 100644 index 00000000..face87d3 --- /dev/null +++ b/nix/kde-rounded-corners.nix @@ -0,0 +1,26 @@ +{ kde-rounded-corners, fetchFromGitHub }: + +# nixpkgs ships 0.10.0, which draws its outline in the wrong place on KWin 6.8: 6.8 inverted the +# texture coordinates of the offscreen window, and with Breeze's shadow (deeper below a window than +# above it) the whole ring lands about 24px too low, across the title bar. 0.11.0 is the release +# that handles it ("KWin 6.8 compatibility for inverted texture coordinates"). +kde-rounded-corners.overrideAttrs (old: { + version = "0.11.0"; + + src = fetchFromGitHub { + owner = "matinlotfali"; + repo = "KDE-Rounded-Corners"; + rev = "v0.11.0"; + hash = "sha256-rdVXukBh7doyuZaFGVQghwKqkWGtuLOXxJgvZbZG0hQ="; + }; + + # KWin loads every effect that is enabled by default when it starts, with the settings the effect + # has then, and at its defaults this one draws a one pixel black outline inside every window, + # over its title bar. Disabled by default, it stays unloaded until it is asked for (`loadEffect` + # on KWin's `/Effects`), which can happen after its settings are written. KWin reads the flag + # from the metadata compiled into the plugin. + postPatch = (old.postPatch or "") + '' + substituteInPlace src/metadata.json \ + --replace-fail '"EnabledByDefault": true' '"EnabledByDefault": false' + ''; +}) diff --git a/nix/komorebi-options.nix b/nix/komorebi-options.nix index e2f71bba..c5bb9ac1 100644 --- a/nix/komorebi-options.nix +++ b/nix/komorebi-options.nix @@ -1,4 +1,4 @@ -# schema-sha256: ca218a3bc93a1cc9466eca3ca51409ffb233df8af2cb56de31ee7b86133c8a0c +# schema-sha256: 0f59fbd881e4247d5ffb1355b24b65f5f58302e74a8908b31837919445376113 { lib, ... }: let defaultLayout = ( @@ -173,6 +173,26 @@ in default = null; description = "Path to an applications.json, or a list of them, with rules for the applications that\nneed them: which windows to ignore, to manage and to float"; }; + border = lib.mkOption { + type = (lib.types.nullOr lib.types.bool); + default = true; + description = "Display window borders"; + }; + border_offset = lib.mkOption { + type = (lib.types.nullOr lib.types.int); + default = 0; + description = "Offset of window borders"; + }; + border_radius = lib.mkOption { + type = (lib.types.nullOr lib.types.int); + default = 10; + description = "Radius of window borders"; + }; + border_width = lib.mkOption { + type = (lib.types.nullOr lib.types.int); + default = 10; + description = "Width of window borders"; + }; cross_boundary_behaviour = lib.mkOption { type = ( lib.types.nullOr ( diff --git a/nix/nixos-module.nix b/nix/nixos-module.nix index 01c2b2f7..67f9b67e 100644 --- a/nix/nixos-module.nix +++ b/nix/nixos-module.nix @@ -217,6 +217,29 @@ in }; }; + effects.borders = { + enable = lib.mkOption { + type = lib.types.bool; + default = true; + description = '' + Install the KWin effect that draws komorebi's borders, KDE Rounded Corners. This is + installation only: whether borders are drawn is komorebi's setting (`komorebic border`), + which asks KWin to load the effect when it is on. KWin finds effects when it starts, so + an effect installed by a switch to a new system is found after the next login. + + Without the effect, komorebi draws no border and leaves no room for one. + ''; + }; + + package = lib.mkPackageOption pkgs "kde-rounded-corners-komorebi" { + extraDescription = '' + It must have `lib/qt-6/plugins/kwin/effects/plugins/kwin4_effect_shapecorners.so`, built + against the KWin of the system and not loaded by default. The default is KDE Rounded + Corners 0.11.0, which draws correctly on KWin 6.8. + ''; + }; + }; + internal.configAttrs = lib.mkOption { type = lib.types.nullOr lib.types.attrs; readOnly = true; @@ -274,9 +297,21 @@ in ) "services.komorebi.config is ignored: services.komorebi.configFile is set." ++ lib.optional (cfg.configFile != null && cfg.applicationSpecificConfiguration.sources != [ ]) - "services.komorebi.applicationSpecificConfiguration is ignored: services.komorebi.configFile is set."; + "services.komorebi.applicationSpecificConfiguration is ignored: services.komorebi.configFile is set." + ++ + lib.optional + ( + cfg.configFile == null + && cfg.config != null + && (cfg.config.border or null) == true + && !cfg.effects.borders.enable + ) + "services.komorebi.config sets border to true, but services.komorebi.effects.borders.enable is false: without the effect, komorebi draws no border."; - environment.systemPackages = [ cfg.package ]; + environment.systemPackages = [ + cfg.package + ] + ++ lib.optional cfg.effects.borders.enable cfg.effects.borders.package; # A user unit, so it runs for every user who logs in to Plasma. plasma-workspace.target is # the target of a Plasma session's services, and plasma-core.target, which it requires, is diff --git a/nix/tests/effects.nix b/nix/tests/effects.nix new file mode 100644 index 00000000..e6c96a5b --- /dev/null +++ b/nix/tests/effects.nix @@ -0,0 +1,55 @@ +# Install checks of the KWin effects komorebi drives: each package is built and its files are +# inspected the way KWin finds them, without a session. Whether an effect loads in a real KWin is a +# question for the VM tests. +{ pkgs, packages }: +let + inherit (pkgs.kdePackages) kwin qttools; +in +{ + kde-rounded-corners-komorebi-install = + pkgs.runCommand "kde-rounded-corners-komorebi-install" + { + nativeBuildInputs = [ + pkgs.jq + pkgs.patchelf + # qtplugininfo reads a plugin's metadata as Qt and KWin read it + qttools + ]; + } + '' + fail() { + echo "FAIL: $*" >&2 + exit 1 + } + plugin=${packages.kde-rounded-corners-komorebi}/lib/qt-6/plugins/kwin/effects/plugins/kwin4_effect_shapecorners.so + + [ -f "$plugin" ] || fail "no plugin at $plugin" + echo "ok: the plugin is where KWin looks for effect plugins" + + # The metadata is compiled into the plugin; KWin does not read metadata.json at run time. + qtplugininfo --full-json "$plugin" > metadata.json || fail "qtplugininfo cannot read $plugin" + if ! jq -e '.MetaData.KPlugin.EnabledByDefault == false' metadata.json > /dev/null; then + cat metadata.json + fail "the plugin's metadata does not say EnabledByDefault false" + fi + echo "ok: the plugin's metadata says EnabledByDefault false" + + # The plugin is loaded into KWin, so it has to link the libkwin of that KWin: the dynamic + # loader takes the first directory of the RUNPATH that has the library. + needed=$(patchelf --print-needed "$plugin" | grep -m 1 -x 'libkwin\.so\.[0-9]*') || + fail "the plugin does not link libkwin" + found= + IFS=: read -r -a dirs <<< "$(patchelf --print-rpath "$plugin")" + for dir in "''${dirs[@]}"; do + if [ -e "$dir/$needed" ]; then + found=$dir/$needed + break + fi + done + [ "$found" = "${kwin}/lib/$needed" ] || + fail "$needed resolves to '$found', not to the KWin of this nixpkgs (${kwin})" + echo "ok: $needed is ${kwin}/lib/$needed" + + touch $out + ''; +} diff --git a/nix/tests/komorebi-example.nix b/nix/tests/komorebi-example.nix index 4946b043..31e89b48 100644 --- a/nix/tests/komorebi-example.nix +++ b/nix/tests/komorebi-example.nix @@ -7,6 +7,9 @@ cross_monitor_move_behaviour = "Insert"; default_workspace_padding = 15; default_container_padding = 15; + border = true; + border_width = 6; + border_offset = 5; floating_window_aspect_ratio = "Widescreen"; floating_layer_behaviour = "Float"; resize_delta = 100; diff --git a/nix/tests/nixos-module.nix b/nix/tests/nixos-module.nix index 1110b780..0d2c0c1d 100644 --- a/nix/tests/nixos-module.nix +++ b/nix/tests/nixos-module.nix @@ -11,6 +11,8 @@ module, # the flake's komorebi-full for a system, which the overlay has to provide komorebiFor, + # the flake's KDE Rounded Corners for a system, which the overlay has to provide as well + borderEffectFor, }: let inherit (pkgs) lib; @@ -208,6 +210,54 @@ let } ); + noBorderEffect = eval { + imports = [ plasma ]; + services.komorebi = { + enable = true; + effects.borders.enable = false; + }; + }; + + # borders asked for in the configuration, and the effect that draws them left out + borderWithoutEffect = eval { + imports = [ plasma ]; + services.komorebi = { + enable = true; + config.border = true; + effects.borders.enable = false; + }; + }; + + # the same, with the effect installed, and with borders turned off in the configuration + borderWithEffect = eval { + imports = [ plasma ]; + services.komorebi = { + enable = true; + config.border = true; + }; + }; + + noBorderWithoutEffect = eval { + imports = [ plasma ]; + services.komorebi = { + enable = true; + config.border = false; + effects.borders.enable = false; + }; + }; + + # a package that is not the overlay's: any package will do, since nothing is built + otherBorderEffect = eval ( + { pkgs, ... }: + { + imports = [ plasma ]; + services.komorebi = { + enable = true; + effects.borders.package = pkgs.hello; + }; + } + ); + unknownLevel = eval { imports = [ plasma ]; services.komorebi = { @@ -279,6 +329,39 @@ let name = "the package is installed in the system profile"; ok = lib.elem enabled.services.komorebi.package enabled.environment.systemPackages; } + { + name = "the default border effect is the flake's KDE Rounded Corners, from the overlay"; + ok = enabled.services.komorebi.effects.borders.package.outPath == (borderEffectFor system).outPath; + } + { + name = "the border effect is installed in the system profile"; + ok = lib.elem enabled.services.komorebi.effects.borders.package enabled.environment.systemPackages; + } + { + name = "with the border effect off, komorebi is installed and the effect is not"; + ok = + lib.elem noBorderEffect.services.komorebi.package noBorderEffect.environment.systemPackages + && !(lib.elem noBorderEffect.services.komorebi.effects.borders.package noBorderEffect.environment.systemPackages); + } + { + name = "another border effect is the one installed"; + ok = + lib.elem otherBorderEffect.services.komorebi.effects.borders.package otherBorderEffect.environment.systemPackages + && !(lib.elem enabled.services.komorebi.effects.borders.package otherBorderEffect.environment.systemPackages); + } + { + name = "a configuration that draws borders, without the effect that draws them, is warned about"; + ok = lib.any (lib.hasInfix "effects.borders.enable is false") borderWithoutEffect.warnings; + got = borderWithoutEffect.warnings; + } + { + name = "borders with the effect, and no borders without it, are not warned about"; + ok = + !(lib.any (lib.hasInfix "effects.borders") borderWithEffect.warnings) + && !(lib.any (lib.hasInfix "effects.borders") noBorderWithoutEffect.warnings) + && !(lib.any (lib.hasInfix "effects.borders") noBorderEffect.warnings); + got = borderWithEffect.warnings ++ noBorderWithoutEffect.warnings ++ noBorderEffect.warnings; + } { name = "disabled, every assertion holds"; ok = failed disabled == [ ]; @@ -290,7 +373,9 @@ let } { name = "disabled, nothing is installed"; - ok = !(lib.elem disabled.services.komorebi.package disabled.environment.systemPackages); + ok = + !(lib.elem disabled.services.komorebi.package disabled.environment.systemPackages) + && !(lib.elem disabled.services.komorebi.effects.borders.package disabled.environment.systemPackages); } { name = "without Plasma 6, an assertion fails and names the option to set"; diff --git a/nix/tests/vm/lib/komorebi_vm/__init__.py b/nix/tests/vm/lib/komorebi_vm/__init__.py index 90b8e7ef..aa051786 100644 --- a/nix/tests/vm/lib/komorebi_vm/__init__.py +++ b/nix/tests/vm/lib/komorebi_vm/__init__.py @@ -8,6 +8,8 @@ A suite imports what it needs from here: and the komorebi daemon that runs in it. * [`daemon`](komorebi_vm.daemon) reads what the daemon logs about the events it handles and the frames it asks for. +* [`pixels`](komorebi_vm.pixels) reads a screenshot: the color of a pixel, and + the ring around a window. * [`latency`](komorebi_vm.latency) times the daemon's commands from a recording of the session bus. @@ -16,9 +18,9 @@ protocol, not on the test driver, so `nix/tests/vm/lib/tests` can run it against a fake machine (the `vm-lib` check does). """ -from komorebi_vm import daemon, latency +from komorebi_vm import daemon, latency, pixels from komorebi_vm.checks import Checks from komorebi_vm.kde import Kde, Rect from komorebi_vm.machine import Machine -__all__ = ["Checks", "Kde", "Machine", "Rect", "daemon", "latency"] +__all__ = ["Checks", "Kde", "Machine", "Rect", "daemon", "latency", "pixels"] diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index 057f7206..0bd87456 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -1,6 +1,7 @@ """A KWin session inside a test machine, and the tools to look at it.""" import json +import re import shlex import time from collections.abc import Callable @@ -117,9 +118,12 @@ class Kde: """Attaches to the user's Plasma session once its desktop is up. The session is up when the shell is running, the user manager knows the - Wayland socket, and the splash screen has gone. The last condition is - the one a screenshot test depends on: a splash screen already has - thousands of colors on it. NixOS wraps its programs, so the processes + Wayland socket, the splash screen has gone, and the shell has made its + panel. The splash screen is the condition a screenshot test depends on: + it already has thousands of colors on it. The panel is the one a test of + where a window is depends on: it takes room from the windows, and + komorebi tiles the room that is left, if it starts after the panel. + NixOS wraps its programs, so the processes are found by their command lines (`pgrep -x` would see only the wrapper's name), with the first letter in brackets so that the pattern does not match the shell that runs `pgrep`. @@ -145,8 +149,51 @@ class Kde: kde._wayland_display = display() if not kde.wait_for(lambda: kde.run("pgrep -f '[k]splashqml'")[0] != 0, timeout=timeout): raise AssertionError("the splash screen did not go away") + if not kde.wait_for(lambda: kde.panels() > 0, timeout=timeout): + raise AssertionError("the shell never made a panel") return kde + def panels(self) -> int: + """Returns how many panels the Plasma shell has made, or 0 when it does not answer. + + A panel takes room from the windows: the work area komorebi tiles is the screen less the + panel. A test that reads where a tiled window ends has to wait for the panel, or komorebi + tiles the window under it, and the bottom of a border is hidden by the panel. + """ + status, out = self.run( + "busctl --user call org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell" + " evaluateScript s 'print(panels().length)'" + ) + found = re.search(r'^s "(\d+)', out.strip()) + return int(found.group(1)) if status == 0 and found else 0 + + def panel_has_room(self) -> bool: + """Returns true if and only if the daemon's work area is not the whole of its first monitor. + + That is the daemon having learned that the panel takes room from the windows. It is not + true when the daemon does not answer, or answers with something that is not its state. + """ + try: + monitor = self.state()["monitors"]["elements"][0] + except (AssertionError, ValueError, KeyError, IndexError): + return False + return monitor["work_area_size"] != monitor["size"] + + def wait_for_panel_room(self, timeout: float = 30) -> bool: + """Waits until the daemon has the panel's room, and says whether it has. + + The shell makes its panel (`Kde.panels`), KWin takes room for it a while later, and the + daemon learns of that up to a second after, because the bridge looks at the work area once + a second. A daemon that tiles before then puts the windows under the panel and tiles them + again, and a test that reads where a window is, or what is round it, in between, reads + the wrong tile. The windows are opened after this. + + It is a wait and not a check: a session may never take the room (a machine too slow to + lay the panel out, which TCG often is), so this ends after `timeout` seconds (times + `scale`) and the test goes on, whichever it was. The daemon has to be running. + """ + return self.wait_for(self.panel_has_room, timeout=timeout) + @property def runtime(self) -> str: """The test user's runtime directory.""" @@ -490,6 +537,41 @@ class Kde: return value.strip() return None + def kwinrc_group(self, group: str) -> dict[str, str]: + """Every key of `[group]` of the user's `kwinrc` with its value, empty when there is none. + + A suite that wants to know that komorebi put the user's settings back compares this before + and after. + """ + status, text = self.machine.execute(f"cat /home/{self.user}/.config/kwinrc") + keys: dict[str, str] = {} + if status != 0: + return keys + current = None + for line in text.splitlines(): + line = line.strip() + if line.startswith("[") and line.endswith("]"): + current = line[1:-1] + elif current == group and "=" in line: + name, value = line.split("=", 1) + keys[name.strip()] = value.strip() + return keys + + def effect_supported(self, name: str) -> bool: + """Returns true if and only if KWin found the effect installed when it started.""" + return self._effects("isEffectSupported", name) + + def effect_loaded(self, name: str) -> bool: + """Returns true if and only if KWin has the effect loaded.""" + return self._effects("isEffectLoaded", name) + + def unload_effect(self, name: str) -> None: + """Asks KWin to unload the effect, whoever loaded it.""" + self.sh( + "busctl --user call org.kde.KWin /Effects org.kde.kwin.Effects unloadEffect s" + f" {shlex.quote(name)}" + ) + def kwin_script(self, name: str, source: str, *, keep: bool = False) -> list[str]: """Runs `source` as the KWin script `name` and returns the lines it reported. @@ -530,6 +612,14 @@ class Kde: """The number of outputs KWin has enabled.""" return int(self.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'")) + def _effects(self, method: str, name: str) -> bool: + """Asks KWin's `/Effects` object a yes or no question about the effect `name`.""" + status, out = self.run( + f"busctl --user call org.kde.KWin /Effects org.kde.kwin.Effects {method} s" + f" {shlex.quote(name)}" + ) + return status == 0 and out.strip() == "b true" + def _workspace(self, workspace: int) -> dict[str, Any]: return self.state()["monitors"]["elements"][0]["workspaces"]["elements"][workspace] diff --git a/nix/tests/vm/lib/komorebi_vm/pixels.py b/nix/tests/vm/lib/komorebi_vm/pixels.py new file mode 100644 index 00000000..b796ab4e --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/pixels.py @@ -0,0 +1,46 @@ +"""Reading what a screenshot shows: the color of a pixel, and the ring around a window.""" + +from PIL import Image + +from komorebi_vm.kde import Rect + +Color = tuple[int, int, int] + + +def pixel(image: Image.Image, x: int, y: int) -> Color: + """The color of the pixel at `(x, y)`, as red, green and blue.""" + value = image.convert("RGB").getpixel((x, y)) + assert isinstance(value, tuple) + return (int(value[0]), int(value[1]), int(value[2])) + + +def near(a: Color, b: Color, tolerance: int = 12) -> bool: + """Returns true if and only if the two colors differ by at most `tolerance` on every channel. + + A screenshot is of a compositor that blends the shadow and the edge of a border into what is + behind it, so a color is never asked for exactly. + """ + return all(abs(x - y) <= tolerance for x, y in zip(a, b, strict=True)) + + +def ring(image: Image.Image, frame: Rect, color: Color, margin: int = 5) -> list[str]: + """Returns what is wrong with the ring around a window: a line for each side that has none. + + The ring is looked for `margin` pixels outside the middle of each of the four edges of + `frame`, which is the window with its title bar, as KWin reports it. A side where that pixel is + not near `color` is named, with the pixel it has. An empty list is a ring all round. + """ + middle_x = frame.x + frame.w // 2 + middle_y = frame.y + frame.h // 2 + sides = { + "above": (middle_x, frame.y - margin), + "below": (middle_x, frame.y + frame.h + margin), + "left": (frame.x - margin, middle_y), + "right": (frame.x + frame.w + margin, middle_y), + } + wrong = [] + for name, (x, y) in sides.items(): + found = pixel(image, x, y) + if not near(found, color): + wrong.append(f"{name}: ({x}, {y}) is {found}, not {color}") + return wrong diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index fab5d3bb..db423e3b 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -108,6 +108,7 @@ def test_session_attaches_to_the_users_bus_and_the_display_the_manager_reports( ) -> None: machine.reply("show-environment", output="PATH=/bin\nWAYLAND_DISPLAY=wayland-1\n") machine.reply("[k]splashqml", status=1) + machine.reply("panels().length", output='s "1\\n"\n') kde = Kde.session(machine, timeout=0) @@ -123,6 +124,71 @@ def test_session_waits_for_the_splash_screen_to_go(machine: FakeMachine) -> None Kde.session(machine, timeout=0) +def test_session_waits_for_the_panel_to_be_made(machine: FakeMachine) -> None: + machine.reply("show-environment", output="WAYLAND_DISPLAY=wayland-1\n") + machine.reply("[k]splashqml", status=1) + machine.reply("panels().length", output='s "0\\n"\n') + + with pytest.raises(AssertionError, match="panel"): + Kde.session(machine, timeout=0) + + +def test_the_panels_are_counted_from_the_shells_answer(machine: FakeMachine) -> None: + kde = Kde(machine, "main") + machine.reply("panels().length", output='s "2\\n"\n') + assert kde.panels() == 2 + + machine.replies.clear() + machine.reply("panels().length", status=1, output="Failed to call method\n") + assert kde.panels() == 0 + + +def a_state_with_a_work_area(area_bottom: int) -> str: + """What `komorebic state` prints for a monitor of 1280x800 with a work area this high.""" + monitor = { + "size": {"left": 0, "top": 0, "right": 1280, "bottom": 800}, + "work_area_size": {"left": 0, "top": 0, "right": 1280, "bottom": area_bottom}, + } + return json.dumps({"monitors": {"elements": [monitor], "focused": 0}}) + + +def test_the_panel_has_room_when_the_work_area_is_less_than_the_monitor( + machine: FakeMachine, +) -> None: + kde = Kde(machine, "main") + + machine.reply("komorebic state", output=a_state_with_a_work_area(738)) + assert kde.panel_has_room() + assert kde.wait_for_panel_room(timeout=0) + + +def test_the_panel_has_no_room_while_the_work_area_is_the_whole_monitor( + machine: FakeMachine, +) -> None: + machine.reply("komorebic state", output=a_state_with_a_work_area(800)) + kde = Kde(machine, "main", scale=0.0) + + assert not kde.panel_has_room() + # the wait ends when the time is up, and says the room did not come + assert not kde.wait_for_panel_room(timeout=100) + + +def test_a_daemon_that_does_not_answer_properly_has_no_panel_room_and_does_not_fail_the_test( + machine: FakeMachine, +) -> None: + kde = Kde(machine, "main", scale=0.0) + + # not running, or too busy to answer in its second: komorebic prints a line with nothing in it + machine.reply("komorebic state", status=1, output="") + assert not kde.panel_has_room() + machine.replies.clear() + machine.reply("komorebic state", output="\n") + assert not kde.panel_has_room() + machine.replies.clear() + machine.reply("komorebic state", output="{}") + assert not kde.panel_has_room() + + def test_session_fails_when_the_shell_never_starts(machine: FakeMachine) -> None: machine.reply("[p]lasmashell", status=1) @@ -549,6 +615,48 @@ def test_kwinrc_is_none_without_a_file(machine: FakeMachine) -> None: assert Kde(machine, "main").kwinrc("Windows", "PerOutputVirtualDesktops") is None +def test_kwinrc_group_is_every_key_of_the_group_and_nothing_of_the_others( + machine: FakeMachine, +) -> None: + machine.reply( + "cat /home/komorebi/.config/kwinrc", + output="[Round-Corners]\nSize = 10\nOuterOutlineColor=1,2,3\n[Windows]\nSize=99\n", + ) + kde = Kde(machine, "main") + + assert kde.kwinrc_group("Round-Corners") == {"Size": "10", "OuterOutlineColor": "1,2,3"} + assert kde.kwinrc_group("Nowhere") == {} + + +def test_kwinrc_group_is_empty_without_a_file(machine: FakeMachine) -> None: + machine.reply("cat /home/komorebi/.config/kwinrc", status=1) + + assert Kde(machine, "main").kwinrc_group("Windows") == {} + + +def test_an_effect_is_supported_or_loaded_when_kwin_says_true(machine: FakeMachine) -> None: + machine.reply("isEffectSupported s kwin4_effect_shapecorners", output="b true\n") + machine.reply("isEffectLoaded s kwin4_effect_shapecorners", output="b false\n") + kde = Kde(machine, "main") + + assert kde.effect_supported("kwin4_effect_shapecorners") + assert not kde.effect_loaded("kwin4_effect_shapecorners") + + +def test_an_effect_is_not_supported_when_the_question_fails(machine: FakeMachine) -> None: + machine.reply("isEffectSupported", status=1, output="Failed to call") + + assert not Kde(machine, "main").effect_supported("kwin4_effect_shapecorners") + + +def test_unload_effect_asks_kwin_over_the_session_bus(machine: FakeMachine) -> None: + Kde(machine, "main").unload_effect("kwin4_effect_shapecorners") + + (command,) = machine.commands + assert "busctl --user call org.kde.KWin /Effects org.kde.kwin.Effects unloadEffect s" in command + assert "kwin4_effect_shapecorners" in command + + def test_a_kwin_script_is_loaded_run_and_unloaded_and_its_reports_returned( machine: FakeMachine, ) -> None: diff --git a/nix/tests/vm/lib/tests/test_pixels.py b/nix/tests/vm/lib/tests/test_pixels.py new file mode 100644 index 00000000..e1113e36 --- /dev/null +++ b/nix/tests/vm/lib/tests/test_pixels.py @@ -0,0 +1,65 @@ +from PIL import Image, ImageDraw + +from komorebi_vm import Rect +from komorebi_vm.pixels import near, pixel, ring + +BLUE = (66, 165, 245) +GRAY = (128, 128, 128) + + +def window_in_a_frame(frame: Rect, color: tuple[int, int, int], width: int) -> Image.Image: + """A screen of 200x200 with a black window and a border of `width` pixels outside it.""" + image = Image.new("RGB", (200, 200), (0, 0, 0)) + draw = ImageDraw.Draw(image) + draw.rectangle( + ( + frame.x - width, + frame.y - width, + frame.x + frame.w + width - 1, + frame.y + frame.h + width - 1, + ), + fill=color, + ) + draw.rectangle((frame.x, frame.y, frame.x + frame.w - 1, frame.y + frame.h - 1), fill=(9, 9, 9)) + return image + + +def test_a_pixel_is_red_green_and_blue() -> None: + image = Image.new("RGBA", (4, 4), (1, 2, 3, 255)) + + assert pixel(image, 2, 2) == (1, 2, 3) + + +def test_near_allows_a_difference_on_every_channel_up_to_the_tolerance() -> None: + assert near((10, 10, 10), (22, 0, 10)) + assert not near((10, 10, 10), (23, 10, 10)) + assert near((10, 10, 10), (30, 10, 10), tolerance=20) + + +def test_a_border_all_round_the_window_is_a_ring() -> None: + frame = Rect(60, 60, 80, 80) + + assert ring(window_in_a_frame(frame, BLUE, 10), frame, BLUE) == [] + + +def test_a_side_with_no_border_is_named_with_the_pixel_it_has() -> None: + frame = Rect(60, 60, 80, 80) + image = window_in_a_frame(frame, BLUE, 10) + ImageDraw.Draw(image).rectangle((130, 50, 150, 150), fill=(0, 0, 0)) + + assert ring(image, frame, BLUE) == ["right: (145, 100) is (0, 0, 0), not (66, 165, 245)"] + + +def test_the_ring_of_another_color_is_not_the_ring_asked_for() -> None: + frame = Rect(60, 60, 80, 80) + image = window_in_a_frame(frame, GRAY, 10) + + assert len(ring(image, frame, BLUE)) == 4 + + +def test_a_thin_border_is_not_found_further_out_than_it_is() -> None: + frame = Rect(60, 60, 80, 80) + image = window_in_a_frame(frame, BLUE, 3) + + assert len(ring(image, frame, BLUE)) == 4 + assert ring(image, frame, BLUE, margin=2) == [] diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 01cafca9..bb0b942f 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -325,6 +325,10 @@ mouse-follows-focus enable mouse-follows-focus disable toggle-mouse-follows-focus toggle-mouse-follows-focus +border enable +border-width 8 +border-offset 1 +border disable session-float-rule session-float-rules clear-session-float-rules @@ -442,6 +446,7 @@ print("== 4. what komorebic only prints") for args in [ "state", "global-state", + "visible-windows", "monitor-information", "data-directory", "configuration", diff --git a/nix/tests/vm/suites/look/default.nix b/nix/tests/vm/suites/look/default.nix new file mode 100644 index 00000000..a048421d --- /dev/null +++ b/nix/tests/vm/suites/look/default.nix @@ -0,0 +1,8 @@ +{ + tier = "slow"; + kind = "session"; + timeoutMinutes = 15; + # The module installs the border effect, and its unit starts komorebi when the session does. The + # test stops that daemon and starts its own runs of it, so that it sees what komorebi does to + # KWin from the first moment. +} diff --git a/nix/tests/vm/suites/look/test.py b/nix/tests/vm/suites/look/test.py new file mode 100644 index 00000000..ee28a13d --- /dev/null +++ b/nix/tests/vm/suites/look/test.py @@ -0,0 +1,174 @@ +# The border, in a real Plasma session whose machine has the border effect installed (the module +# does that): komorebi writes the effect's settings, loads it, and on exit puts everything back. +# +# What is checked is what is on the screen, not what komorebi wrote: the screenshot is read at the +# pixels just outside each window's frame. The runs of komorebi: +# +# 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. +import time + +from komorebi_vm import Checks, Kde, Rect, daemon, pixels + +UNIT = "komorebi.service" +# the daemon's log of the day, without colors, which every run of the unit adds to +LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" +ROUNDED_CORNERS = "kwin4_effect_shapecorners" +GROUP = "Round-Corners" +FOCUSED = (66, 165, 245) +UNFOCUSED = (128, 128, 128) + +start_all() +machine.wait_for_unit("multi-user.target") + +checks = Checks() +kde = Kde.session(machine, scale=SCALE) + + +def running() -> bool: + return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 + + +def answering() -> bool: + return kde.run("komorebic monitor-information")[0] == 0 + + +def asked(title: str) -> Rect | None: + """The frame the daemon last asked KWin for, for the window with this title.""" + 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) + # 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 border effect is written, loaded and told to read its settings as the daemon starts + time.sleep(2) + + +def stop_komorebi() -> None: + kde.systemctl("stop", UNIT) + close_windows() + + +print("== the effect is installed, and not loaded by anyone") +# the session started the module's unit when it logged in: this test starts its own runs +stop_komorebi() +checks.check("KDE Rounded Corners is installed", kde.effect_supported(ROUNDED_CORNERS)) +checks.check( + "and KWin does not load it by itself (it is built disabled by default)", + not kde.effect_loaded(ROUNDED_CORNERS), +) +before = kde.kwinrc_group(GROUP) + + +def put_back() -> None: + checks.check("komorebi exited", not running()) + checks.check("the border effect is unloaded again", not kde.effect_loaded(ROUNDED_CORNERS)) + checks.check(f"kwinrc [{GROUP}] is as it was", kde.kwinrc_group(GROUP) == before) + + +print("== A. komorebi starts, with the borders it has by default") +start_komorebi() +checks.check("the border effect is loaded", kde.effect_loaded(ROUNDED_CORNERS)) +rc = kde.kwinrc_group(GROUP) +checks.check( + "the border is the outer outline: 10 px, colored like the focused window", + rc.get("OuterOutlineThickness") == "10" and rc.get("OuterOutlineColor") == "66,165,245", +) +checks.check( + "nothing is drawn inside the window, over its title bar (the effect's default does)", + rc.get("OutlineThickness") == "0" and rc.get("SecondOutlineThickness") == "0", +) +checks.check( + "the unfocused window gets the other color", + rc.get("InactiveOuterOutlineColor") == "128,128,128", +) +checks.check("the corner radius is the border radius", rc.get("Size") == "10") + +print("== A. two windows, side by side") +colored_window("red", "ff0000") +time.sleep(1) +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") +red_frame, blue_frame = kde.rect(red), kde.rect(blue) +print(f" red: {red_frame} blue: {blue_frame}") +checks.check("they are next to each other", not red_frame.overlaps(blue_frame)) +image = kde.shot("tiled") + +print("== A. the border is just outside the frame, on all four sides") +wrong = pixels.ring(image, blue_frame, FOCUSED) +checks.check( + "the focused window (blue) has the focus color around it" + + "".join(f"\n {w}" for w in wrong), + wrong == [], +) +wrong = pixels.ring(image, red_frame, UNFOCUSED) +checks.check( + "the other window (red) has the unfocused color around it" + + "".join(f"\n {w}" for w in wrong), + wrong == [], +) +inside = pixels.pixel(image, blue_frame.x + 40, blue_frame.y + 5) +checks.check( + f"the border does not cover the title bar (inside the frame, near its top: {inside})", + not pixels.near(inside, FOCUSED), +) + +print("== B. the commands that set the border reach the effect") +kde.komorebic("border-width", "6") +checks.check( + "a narrower border is a thinner outline", + kde.wait_for(lambda: kde.kwinrc_group(GROUP).get("OuterOutlineThickness") == "6", timeout=10), +) +kde.komorebic("border", "disable") +checks.check( + "no border unloads the effect", kde.wait_for(lambda: not kde.effect_loaded(ROUNDED_CORNERS)) +) +checks.check(f"and puts kwinrc [{GROUP}] back as it was", kde.kwinrc_group(GROUP) == before) +kde.komorebic("border", "enable") +checks.check( + "a border again loads the effect, with the width that was set", + kde.wait_for(lambda: kde.effect_loaded(ROUNDED_CORNERS), timeout=10) + and kde.kwinrc_group(GROUP).get("OuterOutlineThickness") == "6", +) + +print("== B. the layout leaves the room the border takes") +room = asked("blue") +kde.komorebic("border-width", "0") +kde.komorebic("retile") + + +def grew() -> bool: + now = asked("blue") + return room is not None and now is not None and (now.w - room.w, now.h - room.h) == (20, 20) + + +checks.check( + f"without the 10 px of border on each side the tile is 20 px wider and higher ({room})", + kde.wait_for(grew, timeout=10), +) + +stop_komorebi() +put_back() + +checks.finish() diff --git a/nix/tests/vm/suites/module/default.nix b/nix/tests/vm/suites/module/default.nix index 2ac9d924..c4d40b09 100644 --- a/nix/tests/vm/suites/module/default.nix +++ b/nix/tests/vm/suites/module/default.nix @@ -4,8 +4,11 @@ timeoutMinutes = 10; # the module writes this as a komorebi.json, checks it against the schema, and the unit starts # the daemon with it, as `--config`: two named workspaces, and a padding that moves the tile of - # the first window away from the edge of the screen + # the first window away from the edge of the screen. No border: the module installs the effect + # that draws one, and a border that is drawn takes room around the window, which the test would + # have to add to the padding (the look suite measures that) node.services.komorebi.config = { + border = false; default_workspace_padding = 40; default_container_padding = 0; monitors = [ diff --git a/schema.json b/schema.json index 0977a436..b4d51310 100644 --- a/schema.json +++ b/schema.json @@ -15,6 +15,41 @@ } ] }, + "border": { + "description": "Display window borders", + "type": [ + "boolean", + "null" + ], + "default": true + }, + "border_offset": { + "description": "Offset of window borders", + "type": [ + "integer", + "null" + ], + "format": "int32", + "default": 0 + }, + "border_radius": { + "description": "Radius of window borders", + "type": [ + "integer", + "null" + ], + "format": "int32", + "default": 10 + }, + "border_width": { + "description": "Width of window borders", + "type": [ + "integer", + "null" + ], + "format": "int32", + "default": 10 + }, "cross_boundary_behaviour": { "description": "Determine what happens when an action is called on a window at a monitor boundary", "anyOf": [