diff --git a/README.md b/README.md index f4b535c5..ef070063 100644 --- a/README.md +++ b/README.md @@ -86,8 +86,8 @@ without a checkout of the toolchain. unlocked (`monitor_reconciliator`, `reconcile`, `kwin::power`), sends its subscribers a notification of each event, message and change of the monitors it handles (`notify_subscribers`), and is configured by a `komorebi.json` that - it reads and reads again when it changes (`static_config`), and checks it for - mistakes without the daemon (`check`). + it reads and reads again when it changes (`static_config`), and checks it, and + the desktop it runs on, for mistakes without the daemon (`check`). - [`komorebi-client`](komorebi-client): a library that sends messages to the daemon, reads its answers, subscribes to its notifications, and re-exports the types they are made of. @@ -280,7 +280,9 @@ module's `config` option is typed from that schema (`nix/komorebi-options.nix`, `check` reads the file the way the daemon does and says in words what is wrong with it: JSON that does not parse, with the line, a value komorebi does not read, a key that is not a setting (with the nearest one that is), a workspace that is not tiled, and an applications file that is not -there. It exits with status 1 if something is an error. +there. It also looks at the desktop (a Plasma session on Wayland, KWin 6 on the session bus, the +daemon and its script in KWin, and what starts komorebi at login), unless `--configuration-only` +leaves that out. It exits with status 1 if something is an error. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event, each message and each diff --git a/docs/cli/check.md b/docs/cli/check.md index 06f82a3c..6bb81417 100644 --- a/docs/cli/check.md +++ b/docs/cli/check.md @@ -1,5 +1,5 @@ ```text -Check komorebi configuration for common errors +Check komorebi configuration and the desktop it runs on for common errors Usage: check [OPTIONS] @@ -7,6 +7,9 @@ Options: -k, --komorebi-config Path to a static configuration JSON file + --configuration-only + Look at the configuration only, not at the desktop + -h, --help Print help diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 179ce098..5eec5f59 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -967,6 +967,28 @@ file's when it has none). [`check_configuration`] also returns the [`Wants`] of it draws borders, which animation style it asks for and whether it has wallpapers. `komorebic` prints [`Report::render`] and exits with status 1 if [`Report::has_errors`]. +[`check_environment`] looks at the desktop, with D-Bus calls of its own on the session bus (they +are in the table of [PLATFORM.md](PLATFORM.md#d-bus)), and `komorebic check --configuration-only` +leaves it out. It looks in this order at the session (`XDG_CURRENT_DESKTOP` and +`XDG_SESSION_TYPE`, each a warning when it is not what komorebi is made for), the session bus, KWin +on it (`NameHasOwner`), KWin's version (the line `KWin version:` of `supportInformation`), the daemon +(a connection to `komorebi.sock`) and its script (`isScriptLoaded`), the two effects, the Plasma +shell when the file has wallpapers (`NameHasOwner` of `org.kde.plasmashell`), and last at what +starts komorebi at login. A bus that cannot be connected to or does not answer, and no KWin on it, +are errors, and the looking stops there: everything after depends on them. Every call has two +seconds to answer, so a bus that never does cannot hold the check. + +The two effects are not part of KWin, and only komorebi's builds of them do everything komorebi +asks: a color for each kind of window (KDE Rounded Corners) and every `animation.style` (Geometry +Change). The stock builds have a color for the active window and one for the others, and one curve, +an exponential ease out. The check tells a build by what it contains: the plugin file of the border +effect has the name of the interface `org.komorebi.BorderColours1` (or its object is on the bus), +and the script of the animation effect reads a `Curve` setting. It looks for them where KWin looks, +which it reads from KWin's own environment (`/proc/PID/environ`, PID being the owner of +`org.kde.KWin`), because the shell the command is typed in has other directories than a session. +What the file asks of the effects is its [`Wants`]: a stock effect is a warning only when the file +asks for what it cannot do. + | Rule | Enforced by | Proof | Escape hatch | |---|---|---|---| | A key komorebi does not read does not stop a configuration from loading | serde: [`StaticConfig`] ignores unknown keys, and a key of another platform is a field nothing reads | `the_keys_that_do_nothing_on_kde_are_accepted_and_ignored`, `fixtures_load_round_trip_and_only_lose_windows_only_keys` | none | @@ -978,6 +1000,12 @@ prints [`Report::render`] and exits with status 1 if [`Report::has_errors`]. | The keys the check knows are the ones komorebi reads, at every level | framework path: [`known_keys`] reads them from the schema of [`StaticConfig`] | `the_keys_come_from_the_schema_at_every_level`, `a_whole_example_configuration_has_nothing_the_check_does_not_know` | built without the `schemars` feature, the check does not look at keys | | Placement rules that are not used while windows are appended are a note, and a workspace that creates containers is not told so whatever the file says | framework path: [`check_configuration`] reads the workspace's `window_container_behaviour` before the file's | `placement_rules_that_are_not_used_while_windows_are_appended_are_noted` | none | | A wallpaper that is not a file is an error, and a picture no theme can be made from is a warning | framework path: [`check_configuration`] looks at the wallpaper of each monitor and workspace once, and asks the theme generator for a palette when the wallpaper does not turn it off | `a_wallpaper_that_is_not_there_and_a_rules_file_that_is_not_there_are_found`, the `vm-check` VM suite for the warning | none | +| No session bus, or no KWin on it, is an error, and the desktop is looked at no further | framework path: [`check_environment`] returns at the first finding the rest depends on | `without_a_session_bus_the_desktop_is_an_error`, `vm-check` | none | +| An effect is komorebi's build because of what it contains, not because of its name | framework path: [`check_environment`] looks for the colors interface in the border effect's plugin file (or its object on the bus) and for a `Curve` setting in the animation effect's script | `the_border_effect_is_komorebis_when_it_has_the_colours_interface`, `the_effects_are_told_apart_by_what_they_contain` | none | +| Effects are looked for where KWin looks, not where the shell that runs the command would | framework path: [`check_environment`] reads KWin's environment from `/proc` | `vm-check` | none | +| A daemon that is running without its script in KWin is an error | framework path: [`check_environment`] compares the connection to the daemon's socket with KWin's answer to `isScriptLoaded` | `vm-check` | none | +| No call of the desktop check delays it by more than two seconds | convention: every call goes through one timeout (`within`) | `a_session_bus_that_never_answers_is_given_up_on` | none | +| `--configuration-only` leaves the desktop out | framework path: the section is pushed only without it | `configuration_only_leaves_the_desktop_out` | none | | `komorebic check` exits with status 1 if and only if a finding is an error | framework path: `komorebic` exits through [`Report::has_errors`] | `a_good_configuration_passes`, `a_typo_is_a_warning_with_the_word_that_was_meant_and_does_not_fail`, `a_file_that_is_not_json_fails_and_shows_the_line` | none | | The rules of an applications file and of the configuration add up | framework path: both are appended to the process-wide lists | `the_rules_of_the_configuration_and_of_the_file_add_up`, `every_file_of_a_list_is_read` | none | | `schema.json` and `schema.asc.json` are what the Rust types print | Nix check `schema-fresh`, and a test that compares them with `komorebic`'s output | `schema-fresh`, `the_schema_files_of_the_repository_are_what_the_subcommands_print` | `just jsonschema` | @@ -1251,8 +1279,9 @@ module's unit. see-through, and the opacity they are given. - [`kwin::effects`](../../komorebi/src/kwin/effects.rs): the KWin effect that draws the border, its settings and the state komorebi keeps of it. -- [`check`](../../komorebi/src/check.rs): the checks behind `komorebic check`, the [`Finding`]s - they return and the [`Report`] `komorebic` gathers them in. +- [`check`](../../komorebi/src/check.rs): the checks behind `komorebic check` (the configuration, + and the desktop it runs on), the [`Finding`]s they return and the [`Report`] `komorebic` gathers + them in. - [`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, @@ -1566,7 +1595,9 @@ A window is shown, and ends up on a tile: format. - [`komorebi/src/check.rs`](../../komorebi/src/check.rs): the checks of `komorebic check`, with their tests; [`komorebic/tests/check.rs`](../../komorebic/tests/check.rs) runs the command on - configurations and reads what it prints and its exit status. + configurations and on buses that are not there, and reads what it prints and its exit status; + [`nix/tests/vm/suites/check`](../../nix/tests/vm/suites/check/test.py), the desktop check against + a real KWin, with the daemon running, with its script gone, with no daemon and with no KWin. - [`komorebi/src/process_event.rs`](../../komorebi/src/process_event.rs): what each event does, and the thread that handles them. - [`komorebi/src/process_command.rs`](../../komorebi/src/process_command.rs): the socket, what @@ -1727,6 +1758,7 @@ A window is shown, and ends up on a tile: [`Report::render`]: ../../komorebi/src/check.rs [`Report::has_errors`]: ../../komorebi/src/check.rs [`check_configuration`]: ../../komorebi/src/check.rs +[`check_environment`]: ../../komorebi/src/check.rs [`check_keys`]: ../../komorebi/src/check.rs [`known_keys`]: ../../komorebi/src/check.rs [`snippet`]: ../../komorebi/src/check.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index c6eb23c0..9995c509 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -367,6 +367,15 @@ read the file (a daemon that is running keeps what it had), so the check shows t with status 1. A workspace that is only a name is a warning too: it is not tiled, which is easy to do without meaning to. +## Why is a daemon that runs without its script in KWin an error, and one that does not run a note? + +A daemon without its script in KWin cannot see a window, so it tiles nothing while it runs: that +is an error, the one finding of the desktop check that says a daemon which is running is broken. +A daemon that is not running is not broken, so it is a note, with the command that starts it. A +script that is still in KWin when its daemon is gone is a warning, since starting the daemon +replaces it. The check tells which of the three it is by connecting to the daemon's socket and by +asking KWin whether it has loaded `komorebi-bridge`. + ## Why does `nix/komorebi-options.nix` start with the hash of the schema? Because the check that the options are fresh cannot make them again. `schemars-nixgen` makes diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 432fbfde..e02cb8df 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -275,6 +275,23 @@ The property `desktops` is introspected as `a(iss)`, a position, an id and a nam desktop, and the value on the wire is `a(uss)`: komorebi reads it as that. It is read uncached, since a read right after `createDesktop` has to see the new desktop. +What `komorebic check` calls, in this order, each with two seconds to answer: + +| Name | Object | Interface | Member | For | +|---|---|---|---|---| +| `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `NameHasOwner(s) -> b` | whether `org.kde.KWin` is on the bus | +| `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `GetConnectionUnixProcessID(s) -> u` | the process that owns `org.kde.KWin`, whose environment says where KWin looks for effects | +| `org.kde.KWin` | `/KWin` | `org.kde.KWin` | `supportInformation() -> s` | KWin's version: the line `KWin version: X.Y.Z` of the text | +| `org.kde.KWin` | `/Scripting` | `org.kde.kwin.Scripting` | `isScriptLoaded(s) -> b` | whether the script `komorebi-bridge` is loaded | +| `org.kde.KWin` | `/Effects` | `org.kde.kwin.Effects` | `isEffectSupported(s) -> b` | whether the border effect (`kwin4_effect_shapecorners`) and the animation effect (`kwin4_effect_geometry_change`) are installed | +| `org.kde.KWin` | `/org/komorebi/BorderColours` | `org.freedesktop.DBus.Introspectable` | `Introspect() -> s` | whether komorebi's build of the border effect is loaded: its object has the interface `org.komorebi.BorderColours1` | +| `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `NameHasOwner(s) -> b` | whether `org.kde.plasmashell` is on the bus, when there are wallpapers | + +At time of writing (2026-10-27), the headless KWin of the VM tests (Plasma 6.8) answers +`supportInformation` with a text that has that line, and `vm-check` has `komorebic check` read the +major version from it. The check does not need the answer: without the line it says that KWin is +there and its version could not be read. + ## Files and directories | Path | What | Lifetime | @@ -296,13 +313,35 @@ since a read right after `createDesktop` has to see the new desktop. Without `XDG_RUNTIME_DIR` the bridge and the socket are in `komorebi` in the local data directory instead, with the logs (see [`XDG_DATA_HOME`](#xdg_data_home)). +## What `komorebic check` looks at + +Apart from the bus, it looks at the files that start komorebi at login, in this order, and says which +it found first: `$XDG_CONFIG_HOME/autostart/komorebi.desktop` (the autostart entry), +`$XDG_CONFIG_HOME/systemd/user/komorebi.service`, `/etc/systemd/user/komorebi.service` and +`/run/current-system/etc/systemd/user/komorebi.service`, where the NixOS module's unit is. Whether +the daemon is running is whether `komorebi.sock` in the runtime directory takes a connection, and +the session is the environment of the command itself: `XDG_CURRENT_DESKTOP` has to name KDE, and +`XDG_SESSION_TYPE` or `WAYLAND_DISPLAY` Wayland. + +The effects are looked for where KWin looks, which is not where the shell that runs the command +looks: KWin is started by the session, with a `QT_PLUGIN_PATH`, an `XDG_DATA_HOME` and an +`XDG_DATA_DIRS` of its own. `komorebic check` reads them from `/proc/PID/environ`, PID being what +the bus says owns `org.kde.KWin`, and falls back to its own environment and to the places NixOS and +the common distributions put plugins and data. The border effect is a plugin file, +`kwin/effects/plugins/kwin4_effect_shapecorners.so`, in a Qt plugin directory, and the animation +effect a script, `kwin/effects/kwin4_effect_geometry_change/contents/code/main.js`, in a data +directory, where KWin takes the user's before the system's. A build is komorebi's by what it +contains: the plugin file has the name of the interface `org.komorebi.BorderColours1` (or its object +is on the bus), and the script reads a setting called `Curve`. + ## Environment variables ### `DBUS_SESSION_BUS_ADDRESS` The address of the session bus. If it is not set, komorebi uses `$XDG_RUNTIME_DIR/bus`, where systemd puts the session bus, and `/run/user//bus` when `XDG_RUNTIME_DIR` is not set -either. An address with no bus behind it is the first error under [No KWin](#no-kwin). +either. An address with no bus behind it is the first error under [No KWin](#no-kwin), and the one +`komorebic check` reports as "could not connect to the session bus". ### `KOMOREBI_CONFIG_HOME` diff --git a/docs/index.md b/docs/index.md index 1d3d75f0..6835610f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -76,7 +76,7 @@ changes size, is unplugged or is plugged in, and [Sleeping and locking](usage/sleeping-and-locking.md) what it does when the machine wakes up and the screen is unlocked. [Checking the setup](usage/checking-the-setup.md) explains how `komorebic check` finds the -mistakes in a configuration before the daemon does. +mistakes in a configuration, and what is missing from the desktop, before the daemon does. [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/usage/checking-the-setup.md b/docs/usage/checking-the-setup.md index 7de9520f..fd8f540f 100644 --- a/docs/usage/checking-the-setup.md +++ b/docs/usage/checking-the-setup.md @@ -1,17 +1,21 @@ # Checking the setup -[`komorebic check`](../cli/check.md) reads your configuration the way the daemon does, and says in -words what is wrong with it. It does not need the daemon to be running, and it changes nothing. +[`komorebic check`](../cli/check.md) reads your configuration the way the daemon does, looks at the +desktop komorebi has to run on, and says in words what is wrong. It does not need the daemon to be +running, and it changes nothing. ```sh komorebic check komorebic check --komorebi-config ~/mine.json +komorebic check --configuration-only ``` It reads `komorebi.json` in the [config home](configuration.md#where-the-file-is), or the file `--komorebi-config` names (`-k`; environment variables in the path are replaced). It prints a -section of findings, then the number of errors and warnings, and exits with status 1 if and only if -a finding is an error, so a script can run it before it starts the daemon. +section of findings for the configuration and one for the desktop, then the number of errors and +warnings, and exits with status 1 if and only if a finding is an error, so a script can run it +before it starts the daemon. `--configuration-only` leaves the desktop out, for a machine that is +not the one komorebi will run on: a build that checks a file, say. ## What a finding says @@ -77,3 +81,58 @@ The first section says where komorebi looks, and then what it finds in the file: The check takes the keys it knows from the schema of the types the daemon reads the file with, at every level, so it knows every setting komorebi reads. + +## The desktop + +The second section is about the desktop `komorebic check` runs in, which has to be the session +komorebi runs in: it asks the session bus of the environment it is run from, so run it in a +terminal of the Plasma session, not over ssh. It looks, in this order, at: + +- **The session.** A `warning` when `XDG_CURRENT_DESKTOP` does not name KDE, and one when the + session is not Wayland (`XDG_SESSION_TYPE` is not `wayland` and there is no `WAYLAND_DISPLAY`): + komorebi is made for KWin on Wayland and tried on nothing else. +- **The session bus, and KWin on it.** An `error` when it cannot connect to the session bus (the + hint says that `DBUS_SESSION_BUS_ADDRESS` has to be that of the desktop session, which it is not + over ssh), when the bus does not answer, and when KWin is not on it, since komorebi works through + KWin and nothing else. The check goes no further after one of them, because nothing after it can + be answered. +- **KWin's version.** `ok` for KWin 6 or newer, an `error` for an older one, and a `note` when + KWin does not say what version it is. +- **komorebi and its script.** komorebi is running when its socket takes a connection, and its + script is in KWin when KWin says it has loaded `komorebi-bridge`: + + | komorebi | script | Finding | + |---|---|---| + | running | in KWin | `ok` | + | running | not in KWin | `error`: it cannot see a window; `komorebic log` says why, and restarting komorebi loads the script again | + | not running | in KWin | `warning`: a script of a daemon that is gone is still in KWin, and starting komorebi replaces it | + | not running | not in KWin | `note`: `komorebic start` | + +- **The border effect.** The borders are drawn by an effect of KWin, KDE Rounded Corners, and + only komorebi's build of it has a color for each kind of window (the stock one has a color for the + active window and one for the others). `ok` when the effect is komorebi's build; a `warning` when + `border` is on and the effect is not installed, or is the stock one, and a `note` when `border` is + off. The build is told by what it contains (the name of its D-Bus interface in the plugin file, + or its object on the bus), not by its name. +- **The animation effect.** Windows are animated by Geometry Change, a script effect, and only + komorebi's build reads its curve from a setting (the stock one eases out exponentially and + nothing else). `ok` when the copy KWin uses is komorebi's build. A `warning` when `animation` is + on and the effect is not installed, and when it is the stock one and `animation.style` is any + other than `EaseOutExpo` (the style is ignored, and the default is `Linear`); a `note` when + animation is off. A `warning` too when a copy in your own data directory, which KWin takes before + the system's, is not the same build as the system's and hides it. +- **The Plasma shell.** Only when a monitor or a workspace has a + [wallpaper](wallpapers.md): `ok` when the shell is on the bus, a `warning` when it is not + (wallpapers will not be set; komorebi asks again for half a minute after it starts, for a shell + that is late). +- **What starts komorebi at login.** `ok` with the file that does it: the autostart entry + [`enable-autostart`](quickstart-and-autostart.md#starting-komorebi-with-plasma) writes, or a + systemd user unit (`~/.config/systemd/user`, `/etc/systemd/user`, or the one of the NixOS module). + A `note` when there is none. It is looked for after the rest, whatever the rest found. + +Effects are looked for where KWin looks: the check reads the environment of the process that owns +`org.kde.KWin` (`/proc/PID/environ`) for the plugin and data directories, so the answer is KWin's +and not that of the shell the command is typed in. + +Every question to the bus has two seconds to be answered, so a bus that never answers is an `error` +like one that is not there. diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md index fb48f273..c20fd9c0 100644 --- a/docs/usage/running-komorebi.md +++ b/docs/usage/running-komorebi.md @@ -33,7 +33,8 @@ running already, `komorebic start` does nothing. `komorebi` manages the windows of the Plasma Wayland session it is started in: it connects to KWin on the session bus and loads a script into it, so start it from a terminal in that session. Outside a Plasma session it exits with an error that says what is missing, which -`komorebic start` prints. +`komorebic start` prints. [`komorebic check`](checking-the-setup.md) says what is missing from the +session, and what is wrong with the configuration, without starting anything. `--config` gives the daemon the `komorebi.json` to read ([Configuration](configuration.md) says where it looks otherwise), and diff --git a/komorebi/src/check.rs b/komorebi/src/check.rs index 2a90f6bb..46230f05 100644 --- a/komorebi/src/check.rs +++ b/komorebi/src/check.rs @@ -1,4 +1,4 @@ -//! The checks behind `komorebic check`: the configuration komorebi reads. +//! The checks behind `komorebic check`: the configuration, and the desktop komorebi has to run on. //! //! Each check is a function that returns [`Finding`]s, so that each can be tested on its own. //! `komorebic` gathers them in a [`Report`], one [`Section`] at a time, prints @@ -10,10 +10,19 @@ //! - [`check_keys`] tells a key for another platform from a typo. One `komorebi.json` can be shared //! with komorebi on Windows and macOS, so a key that only they read is accepted and listed once //! as ignored; a key that no platform has is a warning, with the nearest key komorebi has. +//! - [`check_environment`] looks at the desktop: a KDE Plasma session on Wayland, KWin 6 on the +//! session bus, komorebi and its script in KWin, the border and animation effects, the Plasma +//! shell when there are wallpapers, and what starts komorebi at login. +//! +//! The two effects are not part of KWin, and only komorebi's builds of them do everything komorebi +//! asks: a color for each kind of window (KDE Rounded Corners) and every `animation.style` +//! (Geometry Change). The stock builds have a color for the active window and one for the others, +//! and one curve, an exponential ease out. The check tells a build by what it contains. //! //! A [`Finding`] has a [`Level`]: an error is something that stops komorebi, or a part of it, from -//! working (a file that is not JSON); a warning is something that will not do what was meant (a -//! typo, a workspace that is not tiled); a note is something to know. +//! working (a file that is not JSON, no KWin on the bus); a warning is something that will not do +//! what was meant (a typo, a stock effect asked for a curve it does not have, a workspace that is +//! not tiled); a note is something to know. //! //! # Example //! @@ -54,14 +63,21 @@ //! | The keys are the ones komorebi reads, at every level | [`known_keys`] reads them from the JSON schema of [`StaticConfig`] | `check::tests::the_keys_come_from_the_schema_at_every_level`, `check::tests::a_whole_example_configuration_has_nothing_the_check_does_not_know` | //! | Placement rules that no window can use are a note | [`check_configuration`] compares the `initial_window_placement_rules` of a workspace with its `window_container_behaviour`, or the file's when it has none: windows that are appended to a container have no place of their own | `check::tests::placement_rules_that_are_not_used_while_windows_are_appended_are_noted` | //! | A wallpaper that is not a file is an error, and a picture no theme can be made from is a warning | [`check_configuration`] looks at the wallpaper of each monitor and workspace once, and asks the theme generator for a palette when the wallpaper does not turn it off | `check::tests::a_wallpaper_that_is_not_there_and_a_rules_file_that_is_not_there_are_found` for the error, the `vm-check` VM suite for the warning | +//! | No session bus, or no KWin on it, is an error, and the desktop is looked at no further | [`check_environment`] stops at the first finding the rest depends on | `komorebic/tests/check.rs::without_a_session_bus_the_desktop_is_an_error`, the `vm-check` VM suite | +//! | komorebi running without its script in KWin is an error | [`check_environment`] compares the daemon's socket with KWin's answer to `isScriptLoaded` | the `vm-check` VM suite | +//! | An effect is komorebi's build because of what it contains, not because of its name | [`check_environment`] looks for the colors interface in the border effect, and for a `Curve` setting in the animation effect's script | `check::tests::the_border_effect_is_komorebis_when_it_has_the_colours_interface`, `check::tests::the_effects_are_told_apart_by_what_they_contain` | +//! | Effects are looked for where KWin looks, not where the shell that runs the command would | [`check_environment`] reads KWin's environment from `/proc` | the `vm-check` VM suite | +//! | No D-Bus call delays the check by more than two seconds | convention: every call [`check_environment`] makes goes through a timeout | `komorebic/tests/check.rs::a_session_bus_that_never_answers_is_given_up_on` | //! | `komorebic check` exits with status 1 if and only if a finding is an error | `komorebic`, through [`Report::has_errors`] | `komorebic/tests/check.rs` | #![deny(missing_docs)] +use crate::DATA_DIR; use crate::static_config::StaticConfig; use std::collections::BTreeSet; use std::path::Path; use std::path::PathBuf; +use std::time::Duration; /// How much a [`Finding`] matters. /// @@ -235,8 +251,7 @@ impl Report { } } -/// What a configuration asks of the desktop: the parts of it that have to be there for the file to -/// do what it says. +/// The parts of the desktop a configuration needs, which [`check_environment`] checks are there. /// /// Returned by [`check_configuration`]. The default asks for nothing. #[derive(Clone, Debug, Default)] @@ -859,9 +874,601 @@ fn check_meaning( findings } +// ---- the desktop ------------------------------------------------------------------------------ + +/// Returns true if and only if the file can be read and contains these bytes. +fn file_contains(path: &Path, needle: &[u8]) -> bool { + std::fs::read(path) + .map(|bytes| bytes.windows(needle.len()).any(|w| w == needle)) + .unwrap_or(false) +} + +/// Returns the environment of a process, from `/proc//environ`, or an empty map when it cannot +/// be read. The processes of the user who runs the check can be read. +fn environment_of(pid: u32) -> std::collections::HashMap { + std::fs::read(format!("/proc/{pid}/environ")) + .map(|bytes| { + bytes + .split(|b| *b == 0) + .filter_map(|entry| { + let entry = String::from_utf8_lossy(entry); + let (key, value) = entry.split_once('=')?; + Some((key.to_string(), value.to_string())) + }) + .collect() + }) + .unwrap_or_default() +} + +/// Returns the directories of a colon-separated list, such as `QT_PLUGIN_PATH`, without the empty +/// entries. +fn split_paths(value: Option<&String>) -> Vec { + value + .map(|v| { + v.split(':') + .filter(|p| !p.is_empty()) + .map(PathBuf::from) + .collect() + }) + .unwrap_or_default() +} + +/// Returns the paths at which KWin may find the plugin file of an effect, in the order they are +/// looked at. +/// +/// The directories are those of `QT_PLUGIN_PATH` in KWin's environment (`kwin_env`), then those of +/// `QT_PLUGIN_PATH` in this process's environment, then the places NixOS and the common +/// distributions put Qt 6 plugins, then `~/.local/lib/qt6/plugins`. Each path is +/// `/kwin/effects/plugins/`. +/// +/// ```rust +/// use std::collections::HashMap; +/// use std::path::Path; +/// +/// let kwin_env = HashMap::from([("QT_PLUGIN_PATH".to_string(), "/opt/qt/plugins".to_string())]); +/// let candidates = komorebi::check::plugin_candidates(&kwin_env, "kwin4_effect_shapecorners.so"); +/// +/// let first = Path::new("/opt/qt/plugins/kwin/effects/plugins/kwin4_effect_shapecorners.so"); +/// assert_eq!(candidates[0], first); +/// +/// let nixos = Path::new("/run/current-system/sw/lib/qt-6/plugins") +/// .join("kwin/effects/plugins/kwin4_effect_shapecorners.so"); +/// assert!(candidates.contains(&nixos)); +/// ``` +pub fn plugin_candidates( + kwin_env: &std::collections::HashMap, + file: &str, +) -> Vec { + let mut dirs = split_paths(kwin_env.get("QT_PLUGIN_PATH")); + dirs.extend(split_paths(std::env::var("QT_PLUGIN_PATH").ok().as_ref())); + for fixed in [ + "/run/current-system/sw/lib/qt-6/plugins", + "/usr/lib/qt6/plugins", + "/usr/lib64/qt6/plugins", + "/usr/lib/x86_64-linux-gnu/qt6/plugins", + "/usr/lib/aarch64-linux-gnu/qt6/plugins", + ] { + dirs.push(PathBuf::from(fixed)); + } + if let Some(home) = dirs::home_dir() { + dirs.push(home.join(".local/lib/qt6/plugins")); + } + + dirs.into_iter() + .map(|dir| dir.join("kwin/effects/plugins").join(file)) + .collect() +} + +/// Returns the paths at which KWin may find the script of a scripted effect, in the order KWin +/// looks: the user's data directory, then each of the system's. +/// +/// The user's directory is `XDG_DATA_HOME` in KWin's environment (`kwin_env`), else this process's +/// data directory; the system's are `XDG_DATA_DIRS` in KWin's environment, else `/usr/local/share` +/// and `/usr/share`. The places Nix installs to follow, which a process started outside a login +/// does not have in its `XDG_DATA_DIRS` but KWin, started by the session, does. A directory named +/// twice is looked at once. Each path is `/kwin/effects//contents/code/main.js`. +/// +/// ```rust +/// use std::collections::HashMap; +/// use std::path::Path; +/// +/// let kwin_env = HashMap::from([ +/// ("XDG_DATA_HOME".to_string(), "/home/me/.local/share".to_string()), +/// ("XDG_DATA_DIRS".to_string(), "/usr/share".to_string()), +/// ]); +/// let candidates = +/// komorebi::check::script_effect_candidates(&kwin_env, "kwin4_effect_geometry_change"); +/// +/// let script = "kwin/effects/kwin4_effect_geometry_change/contents/code/main.js"; +/// assert_eq!(candidates[0], Path::new("/home/me/.local/share").join(script)); +/// assert_eq!(candidates[1], Path::new("/usr/share").join(script)); +/// ``` +pub fn script_effect_candidates( + kwin_env: &std::collections::HashMap, + effect: &str, +) -> Vec { + let mut dirs = vec![]; + + match kwin_env.get("XDG_DATA_HOME").filter(|d| !d.is_empty()) { + Some(home) => dirs.push(PathBuf::from(home)), + None => dirs.extend(dirs::data_dir()), + } + + let system = split_paths(kwin_env.get("XDG_DATA_DIRS")); + if system.is_empty() { + dirs.push(PathBuf::from("/usr/local/share")); + dirs.push(PathBuf::from("/usr/share")); + } else { + dirs.extend(system); + } + + // where Nix puts what is installed, which a process started outside a login does not have in + // its XDG_DATA_DIRS but KWin, started by the session, does + dirs.push(PathBuf::from("/run/current-system/sw/share")); + dirs.push(PathBuf::from("/nix/var/nix/profiles/default/share")); + if let Some(home) = dirs::home_dir() { + dirs.push(home.join(".nix-profile/share")); + } + if let Ok(user) = std::env::var("USER") { + dirs.push(PathBuf::from(format!( + "/etc/profiles/per-user/{user}/share" + ))); + } + + // one copy is one copy, however many ways there are to name where it is + let mut seen = BTreeSet::new(); + dirs.retain(|dir| seen.insert(dir.clone())); + + dirs.into_iter() + .map(|dir| { + dir.join("kwin/effects") + .join(effect) + .join("contents/code/main.js") + }) + .collect() +} + +/// The plugin id of KDE Rounded Corners, the border effect. +const BORDER_EFFECT: &str = "kwin4_effect_shapecorners"; +/// The plugin id of Geometry Change, the animation effect. +const ANIMATION_EFFECT: &str = "kwin4_effect_geometry_change"; +/// The D-Bus interface of komorebi's build of the border effect, whose name is in its plugin file. +const COLOURS_INTERFACE: &[u8] = b"org.komorebi.BorderColours1"; + +/// Returns the findings about the border effect, KDE Rounded Corners: whether KWin has it, and +/// whether it is komorebi's build, which takes a color for each window. +/// +/// `supported` is KWin's answer to `isEffectSupported` (`None` when there was none). The build is +/// komorebi's when its object is on the bus (`on_bus`, true once the effect is loaded) or when the +/// plugin file KWin would load ([`plugin_candidates`]) contains the name of its interface. The +/// stock one has a color for the active window and one for the others. What is missing is a +/// [`Level::Warning`] when the configuration asks for borders, and a [`Level::Note`] when it does +/// not. +fn border_effect_findings( + supported: Option, + kwin_env: &std::collections::HashMap, + wants: &Wants, + on_bus: bool, +) -> Vec { + let mut findings = vec![]; + let installed = supported.unwrap_or(false); + + if !installed { + let finding = if wants.borders { + Finding::warning( + "the border effect (KDE Rounded Corners) is not installed: no borders will be drawn", + ) + } else { + Finding::note( + "the border effect (KDE Rounded Corners) is not installed (borders are off anyway)", + ) + }; + findings.push( + finding.hint("komorebi's nix/kde-rounded-corners.nix builds the one it is made for"), + ); + return findings; + } + + let candidates = plugin_candidates(kwin_env, "kwin4_effect_shapecorners.so"); + let plugin = candidates.iter().find(|p| p.exists()); + + let patched = on_bus || plugin.is_some_and(|plugin| file_contains(plugin, COLOURS_INTERFACE)); + + if patched { + findings.push(Finding::ok( + "the border effect is komorebi's build: every kind of window has its own color", + )); + } else if plugin.is_some() || wants.borders { + let finding = if wants.borders { + Finding::warning( + "the border effect is the stock one: borders have two colors, one for the focused window and one for the rest", + ) + } else { + Finding::note( + "the border effect is the stock one (borders are off, so it does not matter)", + ) + }; + findings.push( + finding.hint( + "single, stack, monocle, floating and locked-container colors need komorebi's build of KDE Rounded Corners (nix/kde-rounded-corners.nix)", + ), + ); + } else { + findings.push(Finding::note("the border effect is installed")); + } + + findings +} + +/// Returns the findings about the animation effect, Geometry Change: whether KWin has it, and +/// whether the copy KWin uses is komorebi's build, which reads its curve from a `Curve` setting. +/// +/// `supported` is KWin's answer to `isEffectSupported` (`None` when there was none). The copy KWin +/// uses is the first of [`script_effect_candidates`] that exists, and it is komorebi's build when +/// its script reads `Curve`. The stock one eases out exponentially and nothing else, which is a +/// [`Level::Warning`] only when the configuration asks for another `animation.style`. A later +/// copy that is not the same build as the one KWin uses is a warning too: the user's copy hides +/// the system's. +fn animation_effect_findings( + supported: Option, + kwin_env: &std::collections::HashMap, + wants: &Wants, +) -> Vec { + let mut findings = vec![]; + + if !supported.unwrap_or(false) { + let finding = if wants.animation.is_some() { + Finding::warning( + "the animation effect (Geometry Change) is not installed: windows will not be animated", + ) + } else { + Finding::note( + "the animation effect (Geometry Change) is not installed (animations are off anyway)", + ) + }; + findings.push(finding.hint( + "it is a KWin script effect: install the `kwin4_effect_geometry_change` package", + )); + return findings; + } + + let candidates = script_effect_candidates(kwin_env, ANIMATION_EFFECT); + let found: Vec<&PathBuf> = candidates.iter().filter(|p| p.exists()).collect(); + let curve = |path: &Path| file_contains(path, b"readConfig(\"Curve\""); + + match found.first() { + None => findings.push(Finding::note("the animation effect is installed")), + Some(first) => { + let patched = curve(first); + + if patched { + findings.push(Finding::ok( + "the animation effect is komorebi's build: every `animation.style` is a curve of its own", + )); + } else if wants + .animation + .as_deref() + .is_some_and(|s| s != "EaseOutExpo") + { + findings.push( + Finding::warning(format!( + "the animation effect is the stock one: `animation.style` \"{}\" is ignored, windows ease out exponentially", + wants.animation.clone().unwrap_or_default() + )) + .hint("komorebi's build (nix/kwin-effect-geometry-change.nix) reads the curve"), + ); + } else { + findings.push(Finding::note( + "the animation effect is the stock one: it eases out exponentially", + )); + } + + // KWin takes the first copy it finds, and the user's own comes before the system's + if let Some(shadowed) = found.iter().skip(1).find(|p| curve(p) != patched) { + findings.push( + Finding::warning(format!( + "{} is used, and shadows {}, which is not the same build", + first.display(), + shadowed.display() + )) + .hint("delete the copy in your home directory if it is not meant to be there, and log in again"), + ); + } + } + } + + findings +} + +/// Returns the output of the future, or `None` when it does not finish within two seconds. +async fn within(future: impl std::future::Future) -> Option { + tokio::time::timeout(Duration::from_secs(2), future) + .await + .ok() +} + +/// Returns the findings about the session, KWin, komorebi and its script, the effects and, when +/// there are wallpapers, the Plasma shell. +/// +/// It stops at the first finding everything after it depends on: no session bus, a bus that does +/// not answer, or no KWin on it. Every D-Bus call has two seconds to answer ([`within`]). +async fn desktop_findings(wants: &Wants) -> Vec { + use zbus::Connection; + use zbus::proxy::Proxy; + + let mut findings = vec![]; + + // the session + let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default(); + if desktop.to_uppercase().contains("KDE") { + findings.push(Finding::ok("this is a KDE Plasma session")); + } else { + findings.push(Finding::warning(format!( + "this does not look like a KDE Plasma session (XDG_CURRENT_DESKTOP is \"{desktop}\")" + ))); + } + + let wayland = std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland") + || std::env::var_os("WAYLAND_DISPLAY").is_some(); + if wayland { + findings.push(Finding::ok("it is a Wayland session")); + } else { + findings.push( + Finding::warning("this is not a Wayland session") + .hint("komorebi is made for and tried on KWin on Wayland"), + ); + } + + // the bus, and KWin on it + let connection = match within(Connection::session()).await { + Some(Ok(connection)) => connection, + _ => { + findings.push(Finding::error("could not connect to the session bus").hint( + "DBUS_SESSION_BUS_ADDRESS has to be that of the desktop session (not so over ssh)", + )); + return findings; + } + }; + + let Ok(dbus) = zbus::fdo::DBusProxy::new(&connection).await else { + findings.push(Finding::error("the session bus does not answer")); + return findings; + }; + + let has_owner = |name: &'static str| { + let dbus = dbus.clone(); + async move { + let name = zbus::names::BusName::try_from(name).ok()?; + within(dbus.name_has_owner(name)).await?.ok() + } + }; + + if has_owner("org.kde.KWin").await != Some(true) { + findings.push( + Finding::error("KWin is not on the session bus") + .hint("komorebi works through KWin and nothing else"), + ); + return findings; + } + + // KWin: which, and the environment it looks for effects in + let kwin_name = zbus::names::BusName::try_from("org.kde.KWin").ok(); + let kwin_pid = match kwin_name { + Some(name) => within(dbus.get_connection_unix_process_id(name)) + .await + .and_then(Result::ok), + None => None, + }; + let kwin_env = kwin_pid.map(environment_of).unwrap_or_default(); + + let kwin = Proxy::new(&connection, "org.kde.KWin", "/KWin", "org.kde.KWin") + .await + .ok(); + let information = match &kwin { + Some(kwin) => within(kwin.call::<_, _, String>("supportInformation", &())) + .await + .and_then(Result::ok) + .unwrap_or_default(), + None => String::new(), + }; + let version = information + .lines() + .find_map(|l| l.strip_prefix("KWin version: ")) + .map(str::trim); + + match version.and_then(|v| v.split('.').next()?.parse::().ok()) { + Some(major) if major >= 6 => findings.push(Finding::ok(format!( + "KWin {} is there", + version.unwrap_or_default() + ))), + Some(_) => findings.push( + Finding::error(format!("KWin {} is too old", version.unwrap_or_default())) + .hint("komorebi needs KWin 6 (Plasma 6)"), + ), + None => findings.push(Finding::note( + "KWin is there (its version could not be read)", + )), + } + + // komorebi itself, and its script in KWin + let running = std::os::unix::net::UnixStream::connect(DATA_DIR.join("komorebi.sock")).is_ok(); + let scripting = Proxy::new( + &connection, + "org.kde.KWin", + "/Scripting", + "org.kde.kwin.Scripting", + ) + .await + .ok(); + let script_loaded = match &scripting { + Some(scripting) => { + within(scripting.call::<_, _, bool>("isScriptLoaded", &("komorebi-bridge",))) + .await + .and_then(Result::ok) + } + None => None, + }; + + match (running, script_loaded) { + (true, Some(true)) => findings.push(Finding::ok( + "komorebi is running, and its script is in KWin", + )), + (true, _) => findings.push( + Finding::error("komorebi is running but its script is not in KWin") + .hint("see `komorebic log`; restarting komorebi loads it again"), + ), + (false, Some(true)) => findings.push( + Finding::warning("komorebi is not running, but a script of it is still in KWin") + .hint("starting komorebi replaces it"), + ), + (false, _) => { + findings.push(Finding::note("komorebi is not running").hint("`komorebic start`")) + } + } + + // the effects + let effects = Proxy::new( + &connection, + "org.kde.KWin", + "/Effects", + "org.kde.kwin.Effects", + ) + .await + .ok(); + let supported = |name: &'static str| { + let effects = effects.clone(); + async move { + let effects = effects?; + within(effects.call::<_, _, bool>("isEffectSupported", &(name,))) + .await + .and_then(Result::ok) + } + }; + + // komorebi's border effect puts an object on KWin's name once it is loaded + let colours_on_bus = match Proxy::new( + &connection, + "org.kde.KWin", + "/org/komorebi/BorderColours", + "org.freedesktop.DBus.Introspectable", + ) + .await + { + Ok(proxy) => within(proxy.call::<_, _, String>("Introspect", &())) + .await + .and_then(Result::ok) + .is_some_and(|xml| xml.contains("org.komorebi.BorderColours1")), + Err(_) => false, + }; + + findings.extend(border_effect_findings( + supported(BORDER_EFFECT).await, + &kwin_env, + wants, + colours_on_bus, + )); + findings.extend(animation_effect_findings( + supported(ANIMATION_EFFECT).await, + &kwin_env, + wants, + )); + + // the shell, for wallpapers + if wants.wallpapers { + if has_owner("org.kde.plasmashell").await == Some(true) { + findings.push(Finding::ok("the Plasma shell is there, for the wallpapers")); + } else { + findings.push( + Finding::warning("the Plasma shell is not on the bus: wallpapers will not be set") + .hint("komorebi asks for them again for half a minute after it starts, for a shell that is late"), + ); + } + } + + findings +} + +/// Returns what starts komorebi at login: an autostart entry +/// (`~/.config/autostart/komorebi.desktop`), else a systemd user unit (the user's, then +/// `/etc/systemd/user`, then NixOS's), else a [`Level::Note`] that nothing does. +fn autostart_findings() -> Vec { + let entry = dirs::config_dir().map(|d| d.join("autostart/komorebi.desktop")); + let unit = [ + dirs::config_dir().map(|d| d.join("systemd/user/komorebi.service")), + Some(PathBuf::from("/etc/systemd/user/komorebi.service")), + Some(PathBuf::from( + "/run/current-system/etc/systemd/user/komorebi.service", + )), + ]; + + if let Some(entry) = entry.filter(|e| e.exists()) { + vec![Finding::ok(format!( + "komorebi is started at login by {}", + entry.display() + ))] + } else if let Some(unit) = unit.into_iter().flatten().find(|u| u.exists()) { + vec![Finding::ok(format!( + "komorebi is started at login by {}", + unit.display() + ))] + } else { + vec![Finding::note("komorebi is not started at login").hint("`komorebic enable-autostart`")] + } +} + +/// Returns the findings about the desktop komorebi runs on, for a configuration that asks for +/// `wants`. +/// +/// It looks, in this order, at: the session (KDE Plasma, Wayland); the session bus and KWin on it, +/// and KWin's version (KWin 6 is needed); whether komorebi is running and its script is in KWin; +/// the border and animation effects, and whether each is komorebi's build; the Plasma shell, when +/// there are wallpapers; and what starts komorebi at login. No session bus, or no KWin on it, is a +/// [`Level::Error`], and the findings about the desktop stop there; the one about what starts +/// komorebi comes last in any case. +/// +/// Where KWin looks for effects is read from KWin's environment (`/proc//environ` of the +/// process that owns `org.kde.KWin`), so the answer is KWin's and not that of the shell the command +/// is typed in. Every D-Bus call has two seconds to answer. +/// +/// # Panics +/// +/// Panics when called from within a tokio runtime: it builds a runtime and blocks on it. +/// `komorebic` calls it from its synchronous `main`. +/// +/// # Example +/// +/// Covered by `komorebic/tests/check.rs::without_a_session_bus_the_desktop_is_an_error` and the +/// `vm-check` VM suite. The example needs a desktop session, so it is compiled and not run here: +/// +/// ```rust,no_run +/// use komorebi::check::Level; +/// use komorebi::check::Report; +/// use komorebi::check::Wants; +/// use komorebi::check::check_environment; +/// +/// let mut report = Report::default(); +/// report.push("The desktop", check_environment(&Wants::default())); +/// +/// assert_eq!(report.has_errors(), report.count(Level::Error) > 0); +/// ``` +pub fn check_environment(wants: &Wants) -> Vec { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + + let mut findings = match runtime { + Ok(runtime) => runtime.block_on(desktop_findings(wants)), + Err(error) => vec![Finding::error(format!("could not start to look: {error}"))], + }; + + findings.extend(autostart_findings()); + findings +} + #[cfg(test)] mod tests { use super::*; + use std::collections::HashMap; fn texts(findings: &[Finding]) -> String { findings @@ -1212,6 +1819,106 @@ mod tests { assert!(mistakes.is_empty(), "{}", texts(&findings)); } + #[test] + fn the_effects_are_told_apart_by_what_they_contain() { + let dir = std::env::temp_dir().join(format!("kmc-effects-{}", std::process::id())); + let stock = dir.join("system/kwin/effects/kwin4_effect_geometry_change/contents/code"); + let user = dir.join("home/kwin/effects/kwin4_effect_geometry_change/contents/code"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&stock).unwrap(); + std::fs::create_dir_all(&user).unwrap(); + std::fs::write( + stock.join("main.js"), + "this.curve = QEasingCurve[effect.readConfig(\"Curve\", \"OutExpo\")];", + ) + .unwrap(); + std::fs::write(user.join("main.js"), "curve: QEasingCurve.OutExpo").unwrap(); + + let env: HashMap = [ + ( + "XDG_DATA_HOME".to_string(), + dir.join("home").display().to_string(), + ), + ( + "XDG_DATA_DIRS".to_string(), + dir.join("system").display().to_string(), + ), + ] + .into(); + + let wants = Wants { + animation: Some("Linear".into()), + ..Wants::default() + }; + let findings = animation_effect_findings(Some(true), &env, &wants); + let text = texts(&findings); + + // the user's copy comes first, is the stock effect, and hides the one that has the curve + assert!(text.contains("Warning: the animation effect is the stock one: `animation.style` \"Linear\" is ignored"), "{text}"); + assert!( + text.contains("shadows") && text.contains("system/kwin/effects"), + "{text}" + ); + + // without the user's copy it is komorebi's build + std::fs::remove_file(user.join("main.js")).unwrap(); + let findings = animation_effect_findings(Some(true), &env, &wants); + assert_eq!(findings.len(), 1, "{}", texts(&findings)); + assert_eq!(findings[0].level, Level::Ok); + + // not installed: a warning when animations are on, a note when they are not + assert_eq!( + animation_effect_findings(Some(false), &env, &wants)[0].level, + Level::Warning + ); + assert_eq!( + animation_effect_findings(None, &env, &Wants::default())[0].level, + Level::Note + ); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn the_border_effect_is_komorebis_when_it_has_the_colours_interface() { + let dir = std::env::temp_dir().join(format!("kmc-border-{}", std::process::id())); + let plugins = dir.join("kwin/effects/plugins"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&plugins).unwrap(); + + let env: HashMap = + [("QT_PLUGIN_PATH".to_string(), dir.display().to_string())].into(); + let wants = Wants { + borders: true, + ..Wants::default() + }; + + std::fs::write( + plugins.join("kwin4_effect_shapecorners.so"), + b"\x7fELF stock effect", + ) + .unwrap(); + let findings = border_effect_findings(Some(true), &env, &wants, false); + assert_eq!(findings[0].level, Level::Warning, "{}", texts(&findings)); + + std::fs::write( + plugins.join("kwin4_effect_shapecorners.so"), + b"\x7fELF org.komorebi.BorderColours1 more", + ) + .unwrap(); + let findings = border_effect_findings(Some(true), &env, &wants, false); + assert_eq!(findings[0].level, Level::Ok, "{}", texts(&findings)); + + // or it is on the bus + std::fs::remove_file(plugins.join("kwin4_effect_shapecorners.so")).unwrap(); + assert_eq!( + border_effect_findings(Some(true), &HashMap::new(), &wants, true)[0].level, + Level::Ok + ); + + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn the_report_reads_as_text_and_counts() { let mut report = Report::default(); diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 87e08870..4ef20872 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -103,7 +103,8 @@ //! remove the entry that has Plasma start komorebi at login, `start` runs `komorebi` in the //! background, with the //! `komorebi.json` it is given with `--config`, `check` reads the `komorebi.json` the daemon would -//! and reports what is wrong with it, exiting with status 1 if something is an error, +//! and looks at the desktop, and reports what is wrong, exiting with status 1 if something is an +//! error, //! `configuration` shows the path of the //! `komorebi.json` the daemon reads, `log` follows its log, `data-directory` shows where its //! socket is, `completions` prints a completion script for a shell, and `static-config-schema`, @@ -835,6 +836,9 @@ struct Check { #[clap(action, short, long)] #[clap(value_parser = replace_env_in_path)] komorebi_config: Option, + /// Look at the configuration only, not at the desktop + #[clap(long)] + configuration_only: bool, } #[derive(Parser)] @@ -863,7 +867,7 @@ enum SubCommand { Start(Start), /// Stop the komorebi process Stop(Stop), - /// Check komorebi configuration for common errors + /// Check komorebi configuration and the desktop it runs on for common errors Check(Check), /// Show the path to komorebi.json #[clap(alias = "config")] @@ -1488,10 +1492,17 @@ fn main() -> eyre::Result<()> { None => HOME_DIR.join("komorebi.json"), }; - let (findings, _) = komorebi_client::check::check_configuration(&static_config); + let (findings, wants) = komorebi_client::check::check_configuration(&static_config); place.extend(findings); report.push("Configuration", place); + if !args.configuration_only { + report.push( + "The desktop", + komorebi_client::check::check_environment(&wants), + ); + } + print!("{}", report.render()); if report.has_errors() { diff --git a/komorebic/tests/check.rs b/komorebic/tests/check.rs index 391576ea..bfb7d1b4 100644 --- a/komorebic/tests/check.rs +++ b/komorebic/tests/check.rs @@ -15,7 +15,12 @@ fn check(config: Option<&str>, extra: &[&str]) -> (Output, String) { std::fs::create_dir_all(&dir).unwrap(); let mut command = Command::new(env!("CARGO_BIN_EXE_komorebic")); - command.arg("check").env("KOMOREBI_CONFIG_HOME", &dir); + command + .arg("check") + .arg("--configuration-only") + .env("KOMOREBI_CONFIG_HOME", &dir) + // there is no desktop to ask about, and nothing from this one to leak in + .env_remove("DBUS_SESSION_BUS_ADDRESS"); if let Some(config) = config { let path = dir.join("komorebi.json"); @@ -94,3 +99,108 @@ fn no_file_is_not_an_error() { assert!(output.status.success(), "{text}"); assert!(text.contains("starts with its defaults"), "{text}"); } + +#[test] +fn configuration_only_leaves_the_desktop_out() { + let (output, text) = check(None, &[]); + + assert!(output.status.success(), "{text}"); + assert!(!text.contains("The desktop"), "{text}"); +} + +/// Runs `komorebic check` with no `--configuration-only`, in a config home and a config directory +/// of its own, against the session bus at `bus`. +fn check_desktop(dir: &Path, bus: &Path) -> (Output, String) { + let output = Command::new(env!("CARGO_BIN_EXE_komorebic")) + .arg("check") + .env("KOMOREBI_CONFIG_HOME", dir) + .env("XDG_CONFIG_HOME", dir.join("config")) + // a bus that is not where the address says, whatever the environment has to offer: with + // no address, a connection looks for the user's bus in the runtime directory + .env( + "DBUS_SESSION_BUS_ADDRESS", + format!("unix:path={}", bus.display()), + ) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&output.stdout).into_owned(); + (output, text) +} + +fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("kmc-cli-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn without_a_session_bus_the_desktop_is_an_error() { + let dir = scratch("desktop"); + + let (output, text) = check_desktop(&dir, &dir.join("no-bus")); + + assert_eq!(output.status.code(), Some(1), "{text}"); + assert!(text.contains("The desktop"), "{text}"); + assert!( + text.contains("could not connect to the session bus"), + "{text}" + ); + + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_session_bus_that_never_answers_is_given_up_on() { + let dir = scratch("stuck"); + let bus = dir.join("stuck.bus"); + // it takes the connection and says nothing, so the handshake never ends + let listener = std::os::unix::net::UnixListener::bind(&bus).unwrap(); + let holder = std::thread::spawn(move || listener.accept().map(|(stream, _)| stream)); + + let started = std::time::Instant::now(); + let (output, text) = check_desktop(&dir, &bus); + + assert_eq!(output.status.code(), Some(1), "{text}"); + assert!( + text.contains("could not connect to the session bus"), + "{text}" + ); + assert!( + started.elapsed() < std::time::Duration::from_secs(10), + "{:?}", + started.elapsed() + ); + + let _ = holder.join(); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn what_starts_komorebi_at_login_is_said_whether_or_not_the_desktop_is_there() { + let dir = scratch("login"); + let no_bus = dir.join("no-bus"); + + let (_, text) = check_desktop(&dir, &no_bus); + assert!(text.contains("komorebi is not started at login"), "{text}"); + + let enabled = Command::new(env!("CARGO_BIN_EXE_komorebic")) + .arg("enable-autostart") + .env("KOMOREBI_CONFIG_HOME", &dir) + .env("XDG_CONFIG_HOME", dir.join("config")) + .output() + .unwrap(); + assert!(enabled.status.success(), "{enabled:?}"); + + let (_, text) = check_desktop(&dir, &no_bus); + let entry = dir.join("config/autostart/komorebi.desktop"); + assert!( + text.contains(&format!( + "komorebi is started at login by {}", + entry.display() + )), + "{text}" + ); + + let _ = std::fs::remove_dir_all(dir); +} diff --git a/nix/tests/vm/suites/check/default.nix b/nix/tests/vm/suites/check/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/check/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/check/test.py b/nix/tests/vm/suites/check/test.py new file mode 100644 index 00000000..e570a759 --- /dev/null +++ b/nix/tests/vm/suites/check/test.py @@ -0,0 +1,170 @@ +# `komorebic check` against a real (headless) KWin: what it finds of the desktop, and what it says +# when something is missing: no Plasma shell for the wallpapers, a stock effect shadowing komorebi's +# own, komorebi without its script in KWin, komorebi not running, no KWin on the bus. What only a +# real KWin can tell: that its version is read from what KWin says of itself, that the effects are +# komorebi's builds because of what they contain, that a daemon is told from its script by KWin's +# own answer, and that a bus with no KWin on it is an error with an exit status that says so. The +# configuration and the exit status are covered by `komorebi/src/check.rs` and +# `komorebic/tests/check.rs`, against no desktop. +import base64 +import json +import re +import shlex +import struct +import zlib + +from komorebi_vm import Checks, Kde + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(1920, 1080), scale=SCALE) + +CONFIG = "/tmp/check-config.json" +EMPTY_BUS = "/tmp/check-empty.bus" +FLAT = "/tmp/check-flat.png" + + +def flat_png() -> bytes: + """A picture of one color all over: a wallpaper no theme can be made from.""" + raw = b"".join(b"\x00" + bytes([200, 40, 40]) * 8 for _ in range(8)) + + def chunk(kind: bytes, data: bytes) -> bytes: + body = kind + data + return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF) + + header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0) + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(raw)) + + chunk(b"IEND", b"") + ) + + +kde.sh(f"echo {base64.b64encode(flat_png()).decode()} | base64 -d > {FLAT}") +# borders and animation, which want their effects; a wallpaper, which wants the Plasma shell and +# cannot make a theme; one workspace that is a layout and one that is only a name, which komorebi +# does not tile +kde.sh( + "printf %s " + + shlex.quote( + json.dumps( + { + "border": True, + "animation": {"enabled": True, "style": "Linear"}, + "monitors": [ + { + "wallpaper": {"path": FLAT}, + "workspaces": [{"name": "a", "layout": "BSP"}, {"name": "b"}], + } + ], + } + ) + ) + + f" > {CONFIG}" +) + + +def check(bus: str | None = None, data_home: str | None = None) -> tuple[int, str]: + """Runs `komorebic check` on the session's bus, or on the bus at `bus`, with `data_home` as the + user's data directory when KWin's environment does not name one.""" + prefix = f"DBUS_SESSION_BUS_ADDRESS=unix:path={bus} " if bus else "" + prefix += f"XDG_DATA_HOME={data_home} " if data_home else "" + status, out = kde.run(f"{prefix}komorebic check --komorebi-config {CONFIG}") + print(out) + return status, out + + +print("== 1. a desktop that is as it should be, with komorebi running") +kde.start_komorebi("--config", CONFIG) +checks.check( + "the daemon answers komorebic", + kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=30), +) +checks.check("its script is in KWin", kde.wait_for(kde.script_loaded, timeout=30)) +status, out = check() +checks.check("it passes: no errors", status == 0 and "\n0 error(s)" in out) +checks.check( + "it knows this is a KDE Plasma session on Wayland", + "this is a KDE Plasma session" in out and "it is a Wayland session" in out, +) +checks.check("it knows KWin 6", re.search(r"ok +KWin 6\.", out) is not None) +checks.check( + "it sees komorebi, and its script in KWin", + "komorebi is running, and its script is in KWin" in out, +) +checks.check( + "it says what starts komorebi at login", + re.search(r"ok +komorebi is started at login by ", out) is not None, +) +checks.check( + "the border effect is komorebi's build", + "the border effect is komorebi's build" in out, +) +checks.check( + "the animation effect is komorebi's build", + "the animation effect is komorebi's build" in out, +) +checks.check( + "the configuration is read, and the workspace that is only a name is found", + 'workspace 1 of monitor 0 ("b") has no `layout`' in out, +) +checks.check( + "wallpapers need the Plasma shell, which a headless KWin does not have", + "the Plasma shell is not on the bus" in out, +) +checks.check( + "a picture of one color cannot make a theme", + f"no theme can be made from {FLAT}" in out, +) + +print("== 2. the stock animation effect in the user's own directory hides komorebi's") +DATA = "/tmp/check-data" +STOCK = f"{DATA}/kwin/effects/kwin4_effect_geometry_change/contents/code" +kde.sh(f"mkdir -p {STOCK} && echo 'curve: QEasingCurve.OutExpo' > {STOCK}/main.js") +status, out = check(data_home=DATA) +checks.check( + "the effect is the stock one, and the style is ignored", + 'the animation effect is the stock one: `animation.style` "Linear" is ignored' in out, +) +checks.check("and it says which copy hides which", "shadows" in out) +kde.sh(f"rm -rf {DATA}") + +print("== 3. komorebi is running and its script is not in KWin") +kde.sh( + "busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting unloadScript s komorebi-bridge" +) +checks.check("KWin has let the script go", kde.wait_for(lambda: not kde.script_loaded())) +status, out = check() +checks.check( + "it is an error, and the exit status says so", + status == 1 + and re.search(r"error +komorebi is running but its script is not in KWin", out) is not None, +) + +print("== 4. komorebi is not running") +kde.stop_komorebi() +checks.check("the daemon is gone", kde.wait_for(lambda: not kde.komorebi_running(), timeout=30)) +status, out = check() +checks.check( + "a note, not an error", + status == 0 and re.search(r"note +komorebi is not running", out) is not None, +) + +print("== 5. there is no KWin on the bus") +pid = kde.sh(f"dbus-daemon --session --address=unix:path={EMPTY_BUS} --fork --print-pid").strip() +status, out = check(EMPTY_BUS) +kde.run(f"kill {pid}") +checks.check( + "KWin missing is an error, and the desktop is looked at no further", + status == 1 + and "KWin is not on the session bus" in out + and "komorebi is running" not in out + and "komorebi is not running" not in out, +) + +kde.stop() +checks.finish()