From 6f657e53e3b818e2cb8017bd2b0651286cf4c5e3 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 13:26:31 -0700 Subject: [PATCH] feat(cli): komorebic The daemon answers on its socket, but a person has no way to write a message on it. komorebic is that way: each subcommand that asks something of the daemon is one message, sent with komorebi-client, and a question's answer is printed. komorebic is a separate program because the daemon takes no input but its socket, so a key binding, a script and a terminal all drive it the same way. It has what the daemon can answer so far: state, monitor-information, query, retile and stop. Around them, start runs the komorebi on the PATH in the background and passes it what follows a --, such as --fake-backend to try it without a compositor; log follows the daemon's log, which the daemon now writes to a file a day in LOG_DIR as well as to stdout; data-directory shows where the socket is; completions prints a shell completion script. The hidden docgen writes each subcommand's help to docs/cli, in fences that name their language and wrapped at 100 columns whatever the width of the terminal, so that the pages are the same wherever they are generated; just docgen runs it. The user guide starts here: docs/index.md for KDE Plasma, and a page on running komorebi. tests/cli.rs runs each subcommand against a socket the test serves in place of the daemon. In the VM tests the guests get komorebic next to the daemon, and vm-core-e2e reads the daemon's state with it (the windows it manages, the one it focuses, after KWin restarts too) and stops it with komorebic stop, which unloads the bridge and removes the socket. In the VM test library, Kde.state asks again, a second (times the scale) after an empty answer or a failed command, up to 10 times. The daemon drops a query when it cannot take hold of the window manager within a second, and komorebic then prints an empty line and succeeds; komorebic itself gives the daemon a second to answer and fails when that is not enough. A daemon busy with the first windows does either on a machine that is loaded or slow, and a suite that polled the state died on JSONDecodeError. An answer that is not JSON still fails at once. --- CONTRIBUTING.md | 3 +- Cargo.lock | 170 +++++++++++++++++++ Cargo.toml | 5 +- README.md | 22 ++- deny.toml | 5 + docs/cli/completions.md | 14 ++ docs/cli/data-directory.md | 10 ++ docs/cli/log.md | 10 ++ docs/cli/monitor-information.md | 10 ++ docs/cli/query.md | 15 ++ docs/cli/retile.md | 10 ++ docs/cli/start.md | 14 ++ docs/cli/state.md | 10 ++ docs/cli/stop.md | 10 ++ docs/dev/ARCHITECTURE.md | 17 +- docs/dev/DESIGN.md | 7 + docs/dev/PLATFORM.md | 17 +- docs/dev/vm-tests.md | 9 +- docs/index.md | 94 +++++++++++ docs/usage/running-komorebi.md | 98 +++++++++++ flake.nix | 17 +- justfile | 5 + komorebi-client/src/lib.rs | 1 + komorebi/Cargo.toml | 1 + komorebi/src/lib.rs | 6 + komorebi/src/main.rs | 30 +++- komorebi/tests/no_kwin.rs | 15 +- komorebi/tests/socket.rs | 3 + komorebic/Cargo.toml | 21 +++ komorebic/src/main.rs | 239 +++++++++++++++++++++++++++ komorebic/tests/cli.rs | 212 ++++++++++++++++++++++++ nix/tests/vm/default.nix | 6 +- nix/tests/vm/lib/komorebi_vm/kde.py | 52 ++++++ nix/tests/vm/lib/tests/test_kde.py | 142 ++++++++++++++++ nix/tests/vm/nodes/headless.nix | 3 +- nix/tests/vm/suites/core-e2e/test.py | 56 ++++++- 36 files changed, 1320 insertions(+), 39 deletions(-) create mode 100644 docs/cli/completions.md create mode 100644 docs/cli/data-directory.md create mode 100644 docs/cli/log.md create mode 100644 docs/cli/monitor-information.md create mode 100644 docs/cli/query.md create mode 100644 docs/cli/retile.md create mode 100644 docs/cli/start.md create mode 100644 docs/cli/state.md create mode 100644 docs/cli/stop.md create mode 100644 docs/index.md create mode 100644 docs/usage/running-komorebi.md create mode 100644 komorebic/Cargo.toml create mode 100644 komorebic/src/main.rs create mode 100644 komorebic/tests/cli.rs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fcf1169b..584b9072 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,7 +87,8 @@ the flake and `github` for workflows. Every line of a message, the header included, is at most 80 columns, and the body says why the change is made. Documentation lands in the commit that changes the behavior it describes, not -in a later one. +in a later one. A change to a `komorebic` subcommand regenerates its page in +[`docs/cli`](docs/cli) with `just docgen`. ## Zero-Clause BSD diff --git a/Cargo.lock b/Cargo.lock index 1b67cc30..d269c192 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -219,8 +219,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", "serde", + "wasm-bindgen", "windows-link", ] @@ -247,6 +249,15 @@ dependencies = [ "terminal_size", ] +[[package]] +name = "clap_complete" +version = "4.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" +dependencies = [ + "clap", +] + [[package]] name = "clap_derive" version = "4.6.7" @@ -576,6 +587,15 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-tail" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73c8ee8694b2ad6d79aa976ad8572ca376c0450290041e6e3ae75147356b6ad2" +dependencies = [ + "memchr", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -974,6 +994,7 @@ dependencies = [ "strum", "tokio", "tracing", + "tracing-appender", "tracing-subscriber", "uuid", "version", @@ -1004,6 +1025,21 @@ dependencies = [ "tracing", ] +[[package]] +name = "komorebic" +version = "0.1.0" +dependencies = [ + "chrono", + "clap", + "clap_complete", + "color-eyre", + "fs-tail", + "komorebi-client", + "pastey", + "sysinfo", + "version", +] + [[package]] name = "konst" version = "0.2.20" @@ -1156,6 +1192,15 @@ dependencies = [ "libc", ] +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -1198,12 +1243,31 @@ dependencies = [ "objc2-encode", ] +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "objc2-encode" version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "object" version = "0.40.0" @@ -1761,6 +1825,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + [[package]] name = "syn" version = "2.0.119" @@ -1794,6 +1864,20 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "sysinfo" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ab6a2f8bfe508deb3c6406578252e491d299cbbf3bc0529ecc3313aee4a52f" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -1951,6 +2035,19 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror", + "time", + "tracing-subscriber", +] + [[package]] name = "tracing-attributes" version = "0.1.31" @@ -2172,6 +2269,49 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -2185,6 +2325,17 @@ dependencies = [ "windows-strings", ] +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -2213,6 +2364,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -2240,6 +2401,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "winnow" version = "1.0.4" diff --git a/Cargo.toml b/Cargo.toml index 46b0675d..fc6dfd52 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "2" -members = ["komorebi", "komorebi-client", "version"] +members = ["komorebi", "komorebi-client", "komorebic", "version"] [workspace.package] version = "0.1.0" @@ -13,6 +13,7 @@ komorebi-layouts = { git = "https://github.com/LGUG2Z/komorebi", rev = "f08aa555 "schemars", ] } +chrono = "0.4" clap = { version = "4", features = ["derive", "wrap_help"] } color-eyre = "0.6" crossbeam-channel = "0.5" @@ -23,7 +24,9 @@ schemars = "1.1" serde = { version = "1", features = ["derive"] } serde_json = { package = "serde_json_lenient", version = "0.2" } shadow-rs = "1" +sysinfo = "0.38" tracing = "0.1" +tracing-appender = "0.2" tracing-subscriber = { version = "0.3", features = ["env-filter"] } [workspace.metadata.crane] diff --git a/README.md b/README.md index 72eeade3..75687334 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,21 @@ While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in `$XDG_RUNTIME_DIR/komorebi` (the local data directory when there is no runtime directory): a message can ask for the state of the window manager, ask which monitor, workspace or container has the focus, retile every monitor, or stop -the daemon. [`komorebi-client`](komorebi-client) writes them. +the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +the command line, is how a person sends them. `komorebic start` runs the +`komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma +session: + +```sh +cargo build --locked +export PATH="$PWD/target/debug:$PATH" +komorebic start +komorebic state +komorebic stop +``` + +`komorebic start -- --fake-backend` tries the daemon and `komorebic` without a +compositor, against the in-memory desktop. `nix develop` provides the Rust toolchain that [`rust-toolchain.toml`](rust-toolchain.toml) selects, a nightly `rustfmt`, and the tools `just check` and the flake's checks @@ -52,6 +66,9 @@ without a checkout of the toolchain. (`state`). - [`komorebi-client`](komorebi-client): a library that sends messages to the daemon and reads its answers, and re-exports the types they are made of. +- [`komorebic`](komorebic): the command line. A subcommand that asks something + of the daemon is one message on its socket; `start`, `log`, `data-directory`, + `completions` and the hidden `docgen` work without the daemon. - [`version`](version): the version string every binary reports. The layouts, which turn a work area and a number of containers into a rectangle @@ -103,6 +120,9 @@ locked. A message that asks a question is answered on the same connection. ## Documentation +The user guide starts at [`docs/index.md`](docs/index.md), and +[`docs/cli`](docs/cli) has a page for every `komorebic` subcommand, which +`just docgen` writes from the subcommands' help. `cargo doc --workspace --no-deps --open` builds the API documentation. [`CONTRIBUTING.md`](CONTRIBUTING.md) says how to work on the code. [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md) describes the model, diff --git a/deny.toml b/deny.toml index 71131d7a..267bda37 100644 --- a/deny.toml +++ b/deny.toml @@ -44,6 +44,11 @@ crate = "komorebi-layouts" expression = "LicenseRef-Komorebi-2.0" license-files = [] +[[licenses.clarify]] +crate = "komorebic" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "version" expression = "LicenseRef-Komorebi-2.0" diff --git a/docs/cli/completions.md b/docs/cli/completions.md new file mode 100644 index 00000000..ed664143 --- /dev/null +++ b/docs/cli/completions.md @@ -0,0 +1,14 @@ +```text +Generate komorebic CLI completions for the target shell + +Usage: completions + +Arguments: + + [possible values: bash, elvish, fish, powershell, zsh] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/data-directory.md b/docs/cli/data-directory.md new file mode 100644 index 00000000..c1c9158e --- /dev/null +++ b/docs/cli/data-directory.md @@ -0,0 +1,10 @@ +```text +Show the path to komorebi's data directory, which has its socket + +Usage: data-directory + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/log.md b/docs/cli/log.md new file mode 100644 index 00000000..0b3fa97c --- /dev/null +++ b/docs/cli/log.md @@ -0,0 +1,10 @@ +```text +Tail komorebi's process logs (cancel with Ctrl-C) + +Usage: log + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/monitor-information.md b/docs/cli/monitor-information.md new file mode 100644 index 00000000..c50c6ac2 --- /dev/null +++ b/docs/cli/monitor-information.md @@ -0,0 +1,10 @@ +```text +Show information about connected monitors + +Usage: monitor-information + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/query.md b/docs/cli/query.md new file mode 100644 index 00000000..f2a6a955 --- /dev/null +++ b/docs/cli/query.md @@ -0,0 +1,15 @@ +```text +Query the current window manager state + +Usage: query + +Arguments: + + [possible values: focused-monitor-index, focused-workspace-index, focused-container-index, + focused-window-index, focused-workspace-layout, focused-container-kind, version] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/retile.md b/docs/cli/retile.md new file mode 100644 index 00000000..310d1cc1 --- /dev/null +++ b/docs/cli/retile.md @@ -0,0 +1,10 @@ +```text +Force the retiling of all managed windows + +Usage: retile + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/start.md b/docs/cli/start.md new file mode 100644 index 00000000..af684bd8 --- /dev/null +++ b/docs/cli/start.md @@ -0,0 +1,14 @@ +```text +Start komorebi as a background process + +Usage: start [-- ...] + +Arguments: + [KOMOREBI_ARGS]... + Arguments to pass to komorebi, after a `--`: `komorebic start -- --log-level debug` + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/state.md b/docs/cli/state.md new file mode 100644 index 00000000..c6ac520d --- /dev/null +++ b/docs/cli/state.md @@ -0,0 +1,10 @@ +```text +Show a JSON representation of the current window manager state + +Usage: state + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/stop.md b/docs/cli/stop.md new file mode 100644 index 00000000..889ec1ab --- /dev/null +++ b/docs/cli/stop.md @@ -0,0 +1,10 @@ +```text +Stop the komorebi process + +Usage: stop + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index c82ca934..28aa7885 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -223,6 +223,10 @@ status 0. `SIGINT` and `SIGTERM` do the same from `main.rs`, with the exit statu - [`state`](../../komorebi/src/state.rs): the [`State`] a `State` message is answered with. - [`komorebi-client`](../../komorebi-client/src/lib.rs): a library that writes messages on the socket and reads the answers, for programs that talk to the daemon. +- [`komorebic`](../../komorebic/src/main.rs): the command line. A subcommand that asks + something of the daemon is one message, sent with `komorebi-client`; `start` runs the + daemon, `log` follows its log file in [`LOG_DIR`], and the hidden `docgen` writes + `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, which binds the socket, loads and tiles the desktop, starts the threads that listen on the socket and handle events, and @@ -325,10 +329,10 @@ A window is shown, and ends up on a tile: ## One message, end to end -A client asks for the state of the window manager: +`komorebic state` asks for the state of the window manager: -1. [`send_query`] connects to `komorebi.sock` in [`DATA_DIR`], writes - `{"type":"State"}`, and shuts down its side of the connection for writing. +1. `komorebic` calls [`send_query`], which connects to `komorebi.sock` in [`DATA_DIR`], + writes `{"type":"State"}`, and shuts down its side of the connection for writing. 2. The thread that [`listen_for_commands`] started accepts the connection and starts a thread for it, which calls [`read_commands_uds`]. 3. `read_commands_uds` reads the line, parses it into [`SocketMessage`]`::State`, and locks @@ -339,7 +343,7 @@ A client asks for the state of the window manager: 5. The state is written to the connection as pretty-printed JSON, and the index of managed windows is rebuilt, as after every message. 6. There are no more lines, so `read_commands_uds` returns and the connection is closed. - `send_query` has read to the end, and returns the JSON. + `send_query` has read to the end, and returns the JSON, which `komorebic` prints. ## Where to look in the code @@ -358,6 +362,8 @@ A client asks for the state of the window manager: each message does, and the tests that send messages through a real socket. - [`komorebi-client/src/lib.rs`](../../komorebi-client/src/lib.rs): the client side of the socket. +- [`komorebic/src/main.rs`](../../komorebic/src/main.rs): the subcommands, and + [`komorebic/tests/cli.rs`](../../komorebic/tests/cli.rs), what each writes on the socket. - [`komorebi/src/kwin/mod.rs`](../../komorebi/src/kwin/mod.rs): the KWin backend, its D-Bus service and the held call. - [`komorebi/src/kwin/state.rs`](../../komorebi/src/kwin/state.rs): the table, with the @@ -369,7 +375,7 @@ A client asks for the state of the window manager: - [`nix/tests/vm/suites/kwin-events`](../../nix/tests/vm/suites/kwin-events/test.py): the events of a real KWin, through the daemon. - [`nix/tests/vm/suites/core-e2e`](../../nix/tests/vm/suites/core-e2e/test.py): the daemon - tiling a real KWin, checked against what KWin has. + tiling a real KWin, checked against what KWin has, and read and stopped with `komorebic`. - [`nix/tests/vm/suites/kwin-restart`](../../nix/tests/vm/suites/kwin-restart/test.py): KWin restarting under the daemon. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager @@ -411,6 +417,7 @@ A client asks for the state of the window manager: [`bridge.test.js`]: ../../komorebi/src/kwin/bridge.test.js [`fixtures`]: ../../komorebi/src/kwin/fixtures [`DATA_DIR`]: ../../komorebi/src/lib.rs +[`LOG_DIR`]: ../../komorebi/src/lib.rs [`SocketMessage`]: ../../komorebi/src/core/mod.rs [`StateQuery`]: ../../komorebi/src/core/mod.rs [`State`]: ../../komorebi/src/state.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 0049df8d..67ab1d07 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -164,3 +164,10 @@ an action is the job of another program, which runs a command that writes a mess socket. This is the architecture that bspwm made popular on Linux and yabai on macOS, and the one komorebi has on Windows and on macOS ([the design notes of komorebi for Mac](https://github.com/LGUG2Z/komorebi-for-mac/blob/master/docs/design.md)). + +## Why is `komorebic` a separate program? + +Because the daemon takes no input but its socket. `komorebic` turns a command line into one +message on the socket and, for a question, prints the answer. A key binding, a script and a +person at a terminal all drive komorebi the same way, by running `komorebic` (the design +notes of komorebi for Mac, linked above). diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index b775bc7d..e1870181 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -144,9 +144,11 @@ What komorebi calls: |---|---|---| | `$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 | +| `$XDG_DATA_HOME/komorebi/komorebi.log.YYYY-MM-DD` | the daemon's log, with colors, which `komorebic log` follows | a file a day (the UTC date), never removed by komorebi | +| `$XDG_DATA_HOME/komorebi/komorebi_plaintext.log.YYYY-MM-DD` | the same log without colors | as above | -Without `XDG_RUNTIME_DIR` the directory is `komorebi` in the local data directory instead -(see [`XDG_DATA_HOME`](#xdg_data_home)). +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)). ## Environment variables @@ -163,8 +165,10 @@ the `komorebi` directory in it, and binds its command socket there. ### `XDG_DATA_HOME` -Read only when `XDG_RUNTIME_DIR` is not set: the bridge and the socket then go to -`$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if `XDG_DATA_HOME` is not set either). +The logs are written to `$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if +`XDG_DATA_HOME` is not set), which the daemon makes before anything else: a home it cannot +write to stops it at once. When `XDG_RUNTIME_DIR` is not set, the bridge and the socket go +there too. ### `RUST_LOG` @@ -178,8 +182,9 @@ Whether an error carries a backtrace. komorebi sets it to `1` when it is not set ### `NO_COLOR` -When set to anything but the empty string, the log has no ANSI colors, which is what a log -written to a file wants. The VM tests set it. +When set to anything but the empty string, the log the daemon prints on its standard output +has no ANSI colors, which is what standard output redirected to a file wants. The VM tests +set it. The log files are not affected: one has colors and the other none. ## The bridge's environment diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index dd68907c..27c78e22 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -54,8 +54,8 @@ own Wayland socket), so a test can run several sessions side by side and none touches another. A virtual KWin has no real output, so it cannot draw: it can place windows and answer questions about them, but it cannot take a screenshot. A third unit, `komorebi@NAME`, runs the daemon in a session, built from the -commit under test and installed on the node; it is not bound to KWin's unit, so -a test can restart KWin under a running daemon. +commit under test and installed on the node with `komorebic`; it is not bound to +KWin's unit, so a test can restart KWin under a running daemon. KWin wants a DRM render node, which needs a GPU. The test driver gives every aarch64 guest one `virtio-gpu-pci`; on x86_64 the node adds it, unless `komorebi.vm.renderNode` is false. @@ -105,6 +105,11 @@ the run. started, and `script_loaded()` asks KWin whether it runs the bridge. `restart_kwin()` stops the session's KWin and starts a new one on the same bus, as when the compositor of a running session crashes, and waits for it. +- `komorebic(*args)` runs `komorebic` in the session and returns what it + printed, failing the test if it fails. `state()` is the daemon's state as + `komorebic state` prints it, `managed(workspace)` the number of windows the + daemon has on a workspace of the first monitor, and `focused_title(workspace)` + the title of the window it has focused there. - `daemon` reads the daemon's view of the desktop from that log, started with `--log-level debug`: `daemon.events(log)` lists the window events it handled, in order, `daemon.window_ids(log)` maps a window's title to the daemon's id diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..ef04d17f --- /dev/null +++ b/docs/index.md @@ -0,0 +1,94 @@ +# komorebi for KDE + +## Overview + +`komorebi` is a tiling window manager for KDE Plasma on Wayland. It decides where each window +goes, and KWin, the window manager of Plasma, moves and draws the windows. + +`komorebi` is a daemon that runs in the background, and it is controlled with a CLI, +`komorebic`. Every `komorebic` command that asks something of the daemon is a message on its +socket, so anything that can run a command can drive `komorebi`: a terminal, a script, or a +program that binds keys, which is how a key is given an action. + +`komorebi` aims to make _as few modifications as possible_ to the operating system and desktop +environment by default. Users are free to make such modifications in their own configuration +files for `komorebi`, but these will always remain opt-in and off-by-default. + +## How it fits together + +_komorebi_ only responds to the events KWin reports about windows and to the messages it +receives on a dedicated socket. _komorebic_ is a CLI that writes messages on _komorebi_'s +socket. _komorebi_ doesn't handle any keyboard or mouse inputs: a program that binds keys, +such as the custom shortcuts in Plasma's System Settings, runs _komorebic_ commands. + +```text + PROCESS SOCKET +key bindings --------> komorebic <------> komorebi +``` + +## Getting started + +[Running komorebi](usage/running-komorebi.md) explains how to get the two programs, start and +stop the daemon, ask it what it is doing and read its log. The [CLI reference](cli/start.md) +has a page for every `komorebic` command, generated from its help. + +## Community + +There is a [Discord server](https://discord.gg/mGkn66PHkx) available for +`komorebi`-related discussion, help, troubleshooting etc. + +There is a [YouTube +channel](https://www.youtube.com/channel/UCeai3-do-9O4MNy9_xjO6mg) where I post +`komorebi` development videos, feature previews and release overviews. Subscribing +to the channel (which is monetized as part of the YouTube Partner Program) and +watching videos is a really simple and passive way to contribute financially to +the development and maintenance of `komorebi`. + +There is an [Awesome List](https://github.com/LGUG2Z/awesome-komorebi) which +showcases the many awesome projects that exist in the `komorebi` ecosystem. + +## Licensing for Personal Use + +`komorebi` is licensed under the [Komorebi 2.0.0 license](https://github.com/LGUG2Z/komorebi-license), which is a fork +of the [PolyForm Strict 1.0.0 license](https://polyformproject.org/licenses/strict/1.0.0). On a high level this means +that you are free to do whatever you want with `komorebi` for personal use other than redistribution, or distribution of +new works (i.e. hard-forks) based on the software. + +Anyone is free to make their own fork of `komorebi` with changes intended either for personal use or for integration +back upstream via pull requests. + +The [Komorebi 2.0.0 License](https://github.com/LGUG2Z/komorebi-license) does not permit any kind of commercial use ( +i.e. using `komorebi` at work). + +## Sponsorship for Personal Use + +`komorebi` is a free and educational source project, and one that encourages you +to make charitable donations if you find the software to be useful and have the +financial means. + +I encourage you to make a charitable donation to the [Palestine Children's +Relief Fund](https://pcrf1.app.neoncrm.com/forms/gaza-recovery) or to contribute +to a [Gaza Funds campaign](https://gazafunds.com) before you consider sponsoring +me on GitHub. + +[GitHub Sponsors is enabled for this +project](https://github.com/sponsors/LGUG2Z). Sponsors can claim custom roles on +the Discord server, get shout-outs at the end of _komorebi_-related videos on +YouTube, and gain the ability to submit feature requests on the issue tracker. + +If you would like to tip or sponsor the project but are unable to use GitHub +Sponsors, you may also sponsor through [Ko-fi](https://ko-fi.com/lgug2z), or +make an anonymous Bitcoin donation to `bc1qv73wzspc77k46uty4vp85x8sdp24mphvm58f6q`. + +## Licensing for Commercial Use + +A dedicated Individual Commercial Use License is available for those who want to +use `komorebi` at work. + +The Individual Commercial Use License adds “Commercial Use” as a “Permitted Use” +for the licensed individual only, for the duration of a valid paid license +subscription only. All provisions and restrictions enumerated in the [Komorebi +License](https://github.com/LGUG2Z/komorebi-license) continue to apply. + +More information, pricing and purchase links for Individual Commercial Use +Licenses [can be found here](https://lgug2z.com/software/komorebi). diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md new file mode 100644 index 00000000..748254bd --- /dev/null +++ b/docs/usage/running-komorebi.md @@ -0,0 +1,98 @@ +# Running komorebi + +`komorebi` is the daemon that tiles your windows, and `komorebic` is the command line you +control it with. This page covers starting and stopping the daemon, asking it what it is +doing, and reading its log. + +## Getting the two programs + +On Linux, the flake's default package has both: in a checkout of the repository, +`nix build` leaves them in `result/bin`, and `nix profile install .` puts them on your +`PATH`. Without nix, build them with the Rust toolchain that `rust-toolchain.toml` +selects: + +```sh +cargo build --release --locked +export PATH="$PWD/target/release:$PATH" +``` + +## Starting and stopping + +[`komorebic start`](../cli/start.md) runs the `komorebi` on your `PATH` in the background, +and checks three seconds later that it is running. It tries three times. If `komorebi` has +not started by then, `komorebic start` runs it once more in the foreground and prints what +it wrote on its standard error, which explains why it did not start. When a `komorebi` is +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. + +Everything after a `--` is passed to `komorebi`. `--fake-backend` runs it against an +in-memory desktop with one monitor and no windows instead of KWin, which is a way to try the +daemon and `komorebic` without a compositor: + +```sh +komorebic start +komorebic start -- --log-level debug +komorebic start -- --fake-backend +``` + +[`komorebic stop`](../cli/stop.md) tells the daemon to stop. It asks KWin to unload its +script, removes its socket and exits. Stopping the process with `SIGINT` or `SIGTERM` does +the same. + +## Asking komorebi what it is doing + +The daemon answers questions on its socket, and these commands print the answers: + +- [`komorebic state`](../cli/state.md): every monitor, with its workspaces, their + containers and the windows in them, as JSON. +- [`komorebic monitor-information`](../cli/monitor-information.md): the id, the name and + the bounds of every monitor, as JSON. +- [`komorebic query`](../cli/query.md): one value, the answer to one question: the index of + the focused monitor, workspace, container or window, the layout of the focused workspace, + whether the focused container is a single window or a stack, or the version of the + daemon. + +```sh +komorebic query focused-workspace-index +komorebic state | jq '.monitors.elements[0].workspaces.elements[0].containers.elements | length' +``` + +[`komorebic retile`](../cli/retile.md) tiles the windows of every monitor again, which puts +a window that was moved by hand back on its tile. + +When the daemon is not running, these commands fail: there is no socket to write to. + +## The socket and the data directory + +The daemon listens on `komorebi.sock` in its data directory, `$XDG_RUNTIME_DIR/komorebi` +(the local data directory, `~/.local/share/komorebi`, when there is no runtime directory). +[`komorebic data-directory`](../cli/data-directory.md) prints the directory, if it exists. + +## The log + +The daemon logs to its standard output and to a file a day in `~/.local/share/komorebi` +(`$XDG_DATA_HOME/komorebi` when that is set): `komorebi.log.YYYY-MM-DD`, with colors, and +`komorebi_plaintext.log.YYYY-MM-DD`, without. The day is the UTC date. + +[`komorebic log`](../cli/log.md) follows the file of the current day, with colors, until +you press Ctrl-C. The `--log-level` of `komorebi` sets how much is logged: `error`, `warn`, +`info` (the default), `debug` or `trace`. + +## Shell completions + +[`komorebic completions`](../cli/completions.md) prints a completion script for bash, +elvish, fish, PowerShell or zsh: + +```sh +komorebic completions fish > ~/.config/fish/completions/komorebic.fish +komorebic completions bash > ~/.local/share/bash-completion/completions/komorebic +``` + +## Every command + +[`docs/cli`](../cli/start.md) has a page for every `komorebic` command, generated from its +help with `just docgen`. diff --git a/flake.nix b/flake.nix index 9694a5fc..e7f51b82 100644 --- a/flake.nix +++ b/flake.nix @@ -94,6 +94,7 @@ fullBuild ; komorebi = extractBinary "komorebi"; + komorebic = extractBinary "komorebic"; }; in flake-parts.lib.mkFlake { inherit inputs; } { @@ -122,8 +123,8 @@ pkgs = mkPkgs system; build = mkKomorebiPackages { inherit pkgs; }; isLinux = pkgs.stdenv.hostPlatform.isLinux; - # the daemon each guest runs, built for the guest's system - komorebiFor = guestSystem: self.packages.${guestSystem}.komorebi; + # the daemon and komorebic each guest runs, built for the guest's system + komorebiFor = guestSystem: self.packages.${guestSystem}.komorebi-full; # a Mac runs the guests under HVF, which is slower than KVM vm = import ./nix/tests/vm { hostPkgs = pkgs; @@ -236,7 +237,7 @@ }; packages = lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { - inherit (build) komorebi; + inherit (build) komorebi komorebic; komorebi-full = build.fullBuild; default = build.fullBuild; }; @@ -247,6 +248,11 @@ program = "${build.komorebi}/bin/komorebi"; meta.description = "The komorebi daemon"; }; + komorebic = { + type = "app"; + program = "${build.komorebic}/bin/komorebic"; + meta.description = "The command line interface of komorebi"; + }; default = config.apps.komorebi; }; @@ -290,7 +296,10 @@ flake = { overlays.default = final: _: { - inherit ((mkKomorebiPackages { pkgs = mkPkgs final.stdenv.hostPlatform.system; })) komorebi; + inherit ((mkKomorebiPackages { pkgs = mkPkgs final.stdenv.hostPlatform.system; })) + komorebi + komorebic + ; }; overlays.komorebi = self.overlays.default; }; diff --git a/justfile b/justfile index 5efb510f..3726a9ca 100644 --- a/justfile +++ b/justfile @@ -43,5 +43,10 @@ vm-all: just vm "$name" done +# write the help of every komorebic subcommand to docs/cli, one page each +docgen: + rm -f docs/cli/*.md + cargo run --package komorebic --locked -- docgen --output docs/cli + run target *args: cargo run --bin {{ target }} --locked -- {{ args }} diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index 5ac831fa..c249345e 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -50,6 +50,7 @@ //! way the daemon does, over an in-memory desktop. pub use komorebi::DATA_DIR; +pub use komorebi::LOG_DIR; pub use komorebi::container::Container; pub use komorebi::core::ApplicationIdentifier; pub use komorebi::core::Axis; diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index fb152296..674252c1 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -24,6 +24,7 @@ serde_with = { version = "3", features = ["schemars_1"] } strum = { version = "0.28", features = ["derive"] } tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] } tracing = { workspace = true } +tracing-appender = { workspace = true } tracing-subscriber = { workspace = true } zbus = { version = "5", default-features = false, features = ["tokio"] } futures-util = "0.3" diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 6a1b14a5..d0056428 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -58,6 +58,12 @@ lazy_static! { .expect("there is no local data directory") .join("komorebi") }); + /// Where the logs live: persistent, unlike [`struct@DATA_DIR`]. The daemon writes a file a day + /// here, `komorebi.log.YYYY-MM-DD`, and the same without colors in + /// `komorebi_plaintext.log.YYYY-MM-DD`. + pub static ref LOG_DIR: PathBuf = dirs::data_local_dir() + .expect("there is no local data directory") + .join("komorebi"); } /// The padding, in pixels, between the edge of a monitor's work area and the tiles of its diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 7ab2e5ec..920791a7 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -10,11 +10,15 @@ //! 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. use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; use komorebi::DATA_DIR; +use komorebi::LOG_DIR; use komorebi::backend; use komorebi::backend::fake::FakeBackend; use komorebi::process_command::listen_for_commands; @@ -24,9 +28,11 @@ use komorebi::window_manager_event_listener; use parking_lot::Mutex; use serde::Deserialize; use std::sync::Arc; +use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::EnvFilter; +use tracing_subscriber::layer::SubscriberExt; -fn setup(log_level: LogLevel) -> eyre::Result<()> { +fn setup(log_level: LogLevel) -> eyre::Result<(WorkerGuard, WorkerGuard)> { if std::env::var("RUST_LIB_BACKTRACE").is_err() { unsafe { std::env::set_var("RUST_LIB_BACKTRACE", "1"); @@ -50,10 +56,26 @@ fn setup(log_level: LogLevel) -> eyre::Result<()> { } } + std::fs::create_dir_all(&*LOG_DIR)?; + let appender = tracing_appender::rolling::daily(&*LOG_DIR, "komorebi_plaintext.log"); + let color_appender = tracing_appender::rolling::daily(&*LOG_DIR, "komorebi.log"); + let (non_blocking, guard) = tracing_appender::non_blocking(appender); + let (color_non_blocking, color_guard) = tracing_appender::non_blocking(color_appender); + tracing::subscriber::set_global_default( tracing_subscriber::fmt::Subscriber::builder() .with_env_filter(EnvFilter::from_default_env()) - .finish(), + .finish() + .with( + tracing_subscriber::fmt::Layer::default() + .with_writer(non_blocking) + .with_ansi(false), + ) + .with( + tracing_subscriber::fmt::Layer::default() + .with_writer(color_non_blocking) + .with_ansi(true), + ), )?; // https://github.com/tokio-rs/tracing/blob/master/examples/examples/panic_hook.rs @@ -75,7 +97,7 @@ fn setup(log_level: LogLevel) -> eyre::Result<()> { ); })); - Ok(()) + Ok((guard, color_guard)) } #[cfg(feature = "deadlock_detection")] @@ -129,7 +151,7 @@ struct Opts { fn main() -> eyre::Result<()> { let opts: Opts = Opts::parse(); - setup(opts.log_level)?; + let (_guard, _color_guard) = setup(opts.log_level)?; if !DATA_DIR.is_dir() { std::fs::create_dir_all(&*DATA_DIR)?; diff --git a/komorebi/tests/no_kwin.rs b/komorebi/tests/no_kwin.rs index 8c03143e..417c68a3 100644 --- a/komorebi/tests/no_kwin.rs +++ b/komorebi/tests/no_kwin.rs @@ -12,10 +12,11 @@ use std::time::Duration; /// A bus that is not there, so that a test never reaches the KWin of the session it runs in const NO_BUS: &str = "unix:path=/nonexistent/komorebi-test.bus"; -/// A runtime directory of the test's own, made empty: komorebi makes its data directory, and -/// binds its socket there with `--fake-backend`, before anything else, so the user's runtime -/// directory is kept out of it, and it is writable where the user's home is not (the nix -/// sandbox). /tmp: short enough for a unix socket path on macOS. +/// A runtime directory of the test's own, made empty, which is also its home: komorebi makes +/// its log directory in the home and its data directory in the runtime directory, and binds its +/// socket there with `--fake-backend`, before anything else, so the user's are kept out of it, +/// and it is writable where the user's home is not (the nix sandbox). /tmp: short enough for a +/// unix socket path on macOS. fn runtime(test: &str) -> String { let runtime = format!("/tmp/komorebi-no-kwin-{test}-{}", std::process::id()); let _ = std::fs::remove_dir_all(&runtime); @@ -29,6 +30,8 @@ fn without_a_session_bus_komorebi_exits_with_an_error_naming_it() { let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) .env("XDG_RUNTIME_DIR", &runtime) + .env("HOME", &runtime) + .env_remove("XDG_DATA_HOME") .output() .expect("komorebi runs"); let _ = std::fs::remove_dir_all(&runtime); @@ -53,6 +56,8 @@ fn without_kwin_komorebi_leaves_the_socket_it_finds_alone() { let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) .env("XDG_RUNTIME_DIR", &runtime) + .env("HOME", &runtime) + .env_remove("XDG_DATA_HOME") .output() .expect("komorebi runs"); @@ -71,6 +76,8 @@ fn with_the_fake_backend_komorebi_runs_without_a_session_bus() { .args(["--fake-backend", "--log-level", "error"]) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) .env("XDG_RUNTIME_DIR", &runtime) + .env("HOME", &runtime) + .env_remove("XDG_DATA_HOME") .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() diff --git a/komorebi/tests/socket.rs b/komorebi/tests/socket.rs index 43b0b6d1..42f4c6d5 100644 --- a/komorebi/tests/socket.rs +++ b/komorebi/tests/socket.rs @@ -56,7 +56,10 @@ fn the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to() { let mut daemon = Daemon( Command::new(env!("CARGO_BIN_EXE_komorebi")) .arg("--fake-backend") + // the logs go to the home directory, which may not be writable (the nix sandbox) .env("XDG_RUNTIME_DIR", &runtime) + .env("HOME", &runtime) + .env_remove("XDG_DATA_HOME") .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() diff --git a/komorebic/Cargo.toml b/komorebic/Cargo.toml new file mode 100644 index 00000000..f4c5d1e7 --- /dev/null +++ b/komorebic/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "komorebic" +version.workspace = true +description = "The command-line interface for Komorebi, a tiling window manager for KDE Plasma" +edition = "2024" + +[dependencies] +komorebi-client = { path = "../komorebi-client", default-features = false } +version = { path = "../version" } + +clap = { workspace = true } +clap_complete = "4" +chrono = { workspace = true } +color-eyre = { workspace = true } +fs-tail = "0.1" +pastey = { workspace = true } +sysinfo = { workspace = true } + +[features] +default = ["schemars"] +schemars = ["komorebi-client/default"] diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs new file mode 100644 index 00000000..5ef74b49 --- /dev/null +++ b/komorebic/src/main.rs @@ -0,0 +1,239 @@ +//! `komorebic`, the command line interface of komorebi for KDE Plasma. +//! +//! A subcommand that asks something of the daemon is one message on its socket: an order, such as +//! `stop` or `retile`, is written and `komorebic` exits; a question, such as `state` or `query`, +//! is written and the answer is printed. The messages are [`komorebi_client::SocketMessage`]s, +//! sent with [`komorebi_client::send_message`] and [`komorebi_client::send_query`]. +//! +//! The others work without the daemon: `start` runs `komorebi` in the background, `log` follows +//! its log, `data-directory` shows where its socket is, and `completions` prints a completion +//! script for a shell. The hidden `docgen` writes the help of every subcommand as Markdown, wrapped +//! at 100 columns whatever the width of the terminal, which is how `docs/cli` is made. + +use chrono::Utc; +use clap::CommandFactory; +use clap::Parser; +use color_eyre::eyre; +use fs_tail::TailedFile; +use komorebi_client::SocketMessage; +use komorebi_client::StateQuery; +use komorebi_client::send_message; +use komorebi_client::send_query; +use std::fs::File; +use std::io::BufRead; +use std::io::Write; +use std::path::PathBuf; +use std::process::Command; +use std::process::Stdio; +use std::time::Duration; +use sysinfo::ProcessesToUpdate; + +macro_rules! gen_enum_subcommand_args { + // SubCommand Pattern: Enum Type + ( $( $name:ident: $element:ty ),+ $(,)? ) => { + $( + pastey::paste! { + #[derive(clap::Parser)] + pub struct $name { + #[clap(value_enum)] + [<$element:snake>]: $element + } + } + )+ + }; +} + +gen_enum_subcommand_args! { + Query: StateQuery, +} + +#[derive(Parser)] +#[allow(clippy::struct_excessive_bools)] +struct Start { + /// Arguments to pass to komorebi, after a `--`: `komorebic start -- --log-level debug` + #[clap(last = true)] + komorebi_args: Vec, +} + +#[derive(Parser)] +struct Stop {} + +#[derive(Parser)] +struct Docgen { + /// Output directory for generated documentation files + #[clap(short, long)] + output: Option, +} + +#[derive(Parser)] +struct Completions { + #[clap(value_enum)] + shell: clap_complete::Shell, +} + +#[derive(Parser)] +#[clap(author, about, version = version::LONG_VERSION)] +struct Opts { + #[clap(subcommand)] + subcmd: SubCommand, +} + +#[derive(Parser)] +enum SubCommand { + #[clap(hide = true)] + Docgen(Docgen), + /// Generate komorebic CLI completions for the target shell + #[clap(arg_required_else_help = true)] + Completions(Completions), + /// Start komorebi as a background process + Start(Start), + /// Stop the komorebi process + Stop(Stop), + /// Show the path to komorebi's data directory, which has its socket + #[clap(alias = "datadir")] + DataDirectory, + /// Show a JSON representation of the current window manager state + State, + /// Show information about connected monitors + #[clap(alias = "monitor-info")] + MonitorInformation, + /// Query the current window manager state + #[clap(arg_required_else_help = true)] + Query(Query), + /// Tail komorebi's process logs (cancel with Ctrl-C) + Log, + /// Force the retiling of all managed windows + Retile, +} + +fn print_query(message: &SocketMessage) { + match send_query(message) { + Ok(response) => println!("{response}"), + Err(error) => panic!("{}", error), + } +} + +fn main() -> eyre::Result<()> { + let opts: Opts = Opts::parse(); + + match opts.subcmd { + SubCommand::Docgen(args) => { + let mut cli = Opts::command(); + let subcommands = cli.get_subcommands_mut(); + + let output_dir = args.output.unwrap_or_else(|| PathBuf::from("docs/cli")); + std::fs::create_dir_all(&output_dir)?; + + let ignore = [ + "docgen", + "splash", + "alt-focus-hack", + "identify-border-overflow-application", + "load-custom-layout", + "workspace-custom-layout", + "named-workspace-custom-layout", + "workspace-custom-layout-rule", + "named-workspace-custom-layout-rule", + "focus-follows-mouse", + "toggle-focus-follows-mouse", + "format-app-specific-configuration", + ]; + + for cmd in subcommands { + let name = cmd.get_name().to_string(); + if !ignore.contains(&name.as_str()) { + // the same pages whatever the width of the terminal docgen runs in + let help_text = cmd.clone().term_width(100).render_long_help().to_string(); + let outpath = output_dir.join(format!("{name}.md")); + let markdown = format!("```text\n{help_text}\n```\n"); + std::fs::write(&outpath, markdown)?; + println!("{}", outpath.display()); + } + } + } + SubCommand::Completions(args) => { + let mut cli = Opts::command(); + clap_complete::generate(args.shell, &mut cli, "komorebic", &mut std::io::stdout()); + } + SubCommand::Start(args) => { + let mut command = &mut Command::new("komorebi"); + + command = command + .args(&args.komorebi_args) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .stdin(Stdio::null()); + + let mut system = sysinfo::System::new_all(); + system.refresh_processes(ProcessesToUpdate::All, true); + + let mut attempts = 0; + let mut running = system + .processes_by_exact_name("komorebi".as_ref()) + .next() + .is_some(); + + while !running && attempts <= 2 { + command.spawn()?; + + print!("Waiting for komorebi to start... "); + std::io::stdout().flush()?; + std::thread::sleep(Duration::from_secs(3)); + + system.refresh_processes(ProcessesToUpdate::All, true); + + if system + .processes_by_exact_name("komorebi".as_ref()) + .next() + .is_some() + { + println!("Started!"); + running = true; + } else { + println!("komorebi did not start... Trying again"); + attempts += 1; + } + } + + if !running { + println!("\nRunning komorebi directly for detailed error output\n"); + if let Ok(output) = Command::new("komorebi").args(&args.komorebi_args).output() { + println!("{}", String::from_utf8(output.stderr)?); + } + } + } + SubCommand::Stop(_) => { + send_message(&SocketMessage::Stop)?; + } + SubCommand::DataDirectory => { + let dir = &*komorebi_client::DATA_DIR; + if dir.exists() { + println!("{}", dir.display()); + } + } + SubCommand::Log => { + let timestamp = Utc::now().format("%Y-%m-%d").to_string(); + let color_log = komorebi_client::LOG_DIR.join(format!("komorebi.log.{timestamp}")); + let file = TailedFile::new(File::open(color_log)?); + let locked = file.lock(); + #[allow(clippy::significant_drop_in_scrutinee, clippy::lines_filter_map_ok)] + for line in locked.lines().flatten() { + println!("{line}"); + } + } + SubCommand::Retile => { + send_message(&SocketMessage::Retile)?; + } + SubCommand::State => { + print_query(&SocketMessage::State); + } + SubCommand::Query(args) => { + print_query(&SocketMessage::Query(args.state_query)); + } + SubCommand::MonitorInformation => { + print_query(&SocketMessage::MonitorInformation); + } + } + + Ok(()) +} diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs new file mode 100644 index 00000000..ce285a94 --- /dev/null +++ b/komorebic/tests/cli.rs @@ -0,0 +1,212 @@ +//! `komorebic` as a person runs it, against a socket the test serves in place of the daemon: what +//! each subcommand writes on the socket, and what it prints. + +use std::io::Read; +use std::io::Write; +use std::os::unix::net::UnixListener; +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use std::process::Output; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; +use std::thread::JoinHandle; + +/// A runtime directory for one test, short enough for a unix socket path on macOS, with the +/// `komorebi` directory the daemon would make in it +struct Runtime(PathBuf); + +impl Runtime { + fn new() -> Self { + static NEXT: AtomicU32 = AtomicU32::new(0); + let dir = PathBuf::from(format!( + "/tmp/komorebic-test-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::SeqCst) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("komorebi")).unwrap(); + Self(dir) + } + + /// Listens on the daemon's socket, takes one connection, and answers what it reads on it with + /// `answer`. The thread returns what it read. + fn serve(&self, answer: &'static str) -> JoinHandle { + let listener = UnixListener::bind(self.0.join("komorebi").join("komorebi.sock")).unwrap(); + + std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut message = String::new(); + stream.read_to_string(&mut message).unwrap(); + stream.write_all(answer.as_bytes()).unwrap(); + message + }) + } + + fn komorebic(&self, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(args) + .env("XDG_RUNTIME_DIR", &self.0) + .output() + .unwrap() + } +} + +impl Drop for Runtime { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[test] +fn state_prints_the_answer_of_the_daemon() { + let runtime = Runtime::new(); + let daemon = runtime.serve(r#"{"monitors":{"elements":[],"focused":0}}"#); + + let output = runtime.komorebic(&["state"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!(daemon.join().unwrap(), r#"{"type":"State"}"#); + assert_eq!( + stdout(&output), + "{\"monitors\":{\"elements\":[],\"focused\":0}}\n" + ); +} + +#[test] +fn query_asks_the_question_it_is_given() { + let runtime = Runtime::new(); + let daemon = runtime.serve("1"); + + let output = runtime.komorebic(&["query", "focused-workspace-index"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!( + daemon.join().unwrap(), + r#"{"type":"Query","content":"FocusedWorkspaceIndex"}"# + ); + assert_eq!(stdout(&output), "1\n"); +} + +#[test] +fn monitor_information_prints_the_answer_of_the_daemon() { + let runtime = Runtime::new(); + let daemon = runtime.serve("[]"); + + let output = runtime.komorebic(&["monitor-info"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!(daemon.join().unwrap(), r#"{"type":"MonitorInformation"}"#); + assert_eq!(stdout(&output), "[]\n"); +} + +#[test] +fn stop_and_retile_send_their_message_and_print_nothing() { + for (subcommand, message) in [ + ("stop", r#"{"type":"Stop"}"#), + ("retile", r#"{"type":"Retile"}"#), + ] { + let runtime = Runtime::new(); + let daemon = runtime.serve(""); + + let output = runtime.komorebic(&[subcommand]); + + assert!(output.status.success(), "{subcommand}: {output:?}"); + assert_eq!(daemon.join().unwrap(), message, "{subcommand}"); + assert_eq!(stdout(&output), "", "{subcommand}"); + } +} + +#[test] +fn without_a_daemon_a_question_fails() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["state"]); + + assert!(!output.status.success(), "{output:?}"); + assert_eq!(stdout(&output), ""); +} + +#[test] +fn data_directory_shows_where_the_socket_is() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["data-directory"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!( + stdout(&output), + format!("{}\n", runtime.0.join("komorebi").display()) + ); +} + +#[test] +fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { + let runtime = Runtime::new(); + let docs = runtime.0.join("cli"); + + let output = runtime.komorebic(&["docgen", "--output", docs.to_str().unwrap()]); + + assert!(output.status.success(), "{output:?}"); + let mut pages = std::fs::read_dir(&docs) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect::>(); + pages.sort(); + assert_eq!( + pages, + [ + "completions.md", + "data-directory.md", + "log.md", + "monitor-information.md", + "query.md", + "retile.md", + "start.md", + "state.md", + "stop.md", + ] + ); + + let query = std::fs::read_to_string(Path::new(&docs).join("query.md")).unwrap(); + assert!(query.starts_with("```text\n"), "{query}"); + assert!(query.ends_with("\n```\n"), "{query}"); + assert!(query.contains("focused-workspace-index"), "{query}"); +} + +#[test] +fn docgen_writes_the_same_pages_whatever_the_width_of_the_terminal() { + let runtime = Runtime::new(); + // without a terminal, clap wraps the help at the width in COLUMNS + let query_page = |columns: &str| { + let docs = runtime.0.join(format!("cli-{columns}")); + let output = Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(["docgen", "--output", docs.to_str().unwrap()]) + .env("COLUMNS", columns) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + std::fs::read_to_string(docs.join("query.md")).unwrap() + }; + + let narrow = query_page("40"); + + assert_eq!(narrow, query_page("250")); + // the possible values of a query are wrapped at 100 columns + assert!(narrow.lines().any(|line| line.len() > 40), "{narrow}"); + assert!(narrow.lines().all(|line| line.len() <= 100), "{narrow}"); +} + +#[test] +fn completions_are_a_script_that_knows_the_subcommands() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["completions", "bash"]); + + assert!(output.status.success(), "{output:?}"); + assert!(stdout(&output).contains("monitor-information")); +} diff --git a/nix/tests/vm/default.nix b/nix/tests/vm/default.nix index b530d40d..245f72cb 100644 --- a/nix/tests/vm/default.nix +++ b/nix/tests/vm/default.nix @@ -3,9 +3,9 @@ # the flake. See docs/dev/vm-tests.md. # # `hostPkgs` is the pkgs of the machine that runs QEMU; the guests are always Linux. `komorebiFor` -# returns the komorebi package of a system, and the guests get the one of their own. `scale` says -# how much slower than KVM that machine is (1 for KVM, 1.5 for HVF on a Mac, 8 for TCG), and every -# wait in the suites is multiplied by it. +# returns the package of `komorebi` and `komorebic` for a system, and the guests get the one of +# their own. `scale` says how much slower than KVM that machine is (1 for KVM, 1.5 for HVF on a +# Mac, 8 for TCG), and every wait in the suites is multiplied by it. { hostPkgs, komorebiFor, diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index 86bf3d22..b7eae826 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -1,9 +1,11 @@ """A KWin session inside a test machine, and the tools to look at it.""" +import json import shlex import time from collections.abc import Callable from dataclasses import dataclass +from typing import Any from PIL import Image @@ -237,6 +239,53 @@ class Kde: """The daemon's log since it was last started, or the empty string before that.""" return self.machine.execute(f"cat {self.runtime}/komorebi-{self.name}.log")[1] + def komorebic(self, *args: str) -> str: + """Runs `komorebic` with `args` inside the session and returns what it printed. + + It fails the test unless `komorebic` succeeds, as it does when no daemon answers. + `komorebic` finds the daemon's socket in the user's runtime directory, which every session + of the user shares, so one daemon at a time can answer it. + """ + return self.sh(shlex.join(["komorebic", *args])) + + def state(self, attempts: int = 10) -> dict[str, Any]: + """The daemon's state, as `komorebic state` prints it. + + The daemon answers a query when it can take hold of the window manager within a second, + and answers nothing when it cannot, which is what a daemon busy with a window that has + just opened does on a machine that is loaded or slow: `komorebic` then prints an empty + line and succeeds. It also gives the daemon a second to answer, and fails when that is not + enough. The query is asked again, a second (times `scale`) after an empty answer or a + failure, up to `attempts` times, and fails the test if the daemon does not answer every + time. An answer that is not JSON and not empty fails at once. + """ + for attempt in range(attempts): + status, out = self.run(shlex.join(["komorebic", "state"])) + if status == 0 and out.strip(): + return json.loads(out) + if attempt + 1 < attempts: + time.sleep(self.scale) + raise AssertionError( + f"the daemon did not answer `komorebic state`, {attempts} times: {status} {out!r}" + ) + + def focused_title(self, workspace: int = 0) -> str: + """The title of the window the daemon has focused on a workspace of the first monitor. + + That is the focused window of the workspace's focused container, as the daemon's state + has it, or the empty string when the workspace has no container. + """ + containers = self._workspace(workspace)["containers"] + if not containers["elements"]: + return "" + windows = containers["elements"][containers["focused"]]["windows"] + return windows["elements"][windows["focused"]]["details"]["title"] + + def managed(self, workspace: int = 0) -> int: + """The number of windows the daemon has on a workspace of the first monitor.""" + containers = self._workspace(workspace)["containers"]["elements"] + return sum(len(container["windows"]["elements"]) for container in containers) + def monitor_bridge(self, path: str) -> None: """Starts recording the bridge's traffic on the session bus to `path`, in the background. @@ -337,6 +386,9 @@ class Kde: """The number of outputs KWin has enabled.""" return int(self.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'")) + def _workspace(self, workspace: int) -> dict[str, Any]: + return self.state()["monitors"]["elements"][0]["workspaces"]["elements"][workspace] + def _wrap(self, command: str, session: bool = True) -> str: env = self.env if session else f"XDG_RUNTIME_DIR={shlex.quote(self.runtime)}" return f"runuser -u {self.user} -- env {env} sh -c {shlex.quote(command)}" diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index 2675538a..9e246032 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -1,3 +1,4 @@ +import json import shlex import pytest @@ -265,3 +266,144 @@ def test_restart_kwin_reports_the_journal_when_kwin_does_not_come_back( with pytest.raises(AssertionError, match="the socket is taken"): Kde(machine, "main", scale=0.01).restart_kwin() + + +def test_komorebic_runs_inside_the_session_and_returns_what_it_printed( + machine: FakeMachine, +) -> None: + machine.reply("komorebic query", output="2\n") + + assert Kde(machine, "main").komorebic("query", "focused-workspace-index") == "2\n" + (command,) = machine.commands + assert inner(command) == "komorebic query focused-workspace-index" + assert "WAYLAND_DISPLAY=wayland-main" in command + assert "XDG_RUNTIME_DIR=/run/user/1000" in command + + +def test_komorebic_fails_the_test_when_no_daemon_answers(machine: FakeMachine) -> None: + machine.reply("komorebic", status=1, output="") + + with pytest.raises(AssertionError, match="komorebic state"): + Kde(machine, "main").komorebic("state") + + +def test_a_daemon_that_says_nothing_is_asked_again( + machine: FakeMachine, monkeypatch: pytest.MonkeyPatch +) -> None: + kde = Kde(machine, "main", scale=0.0) + answers = iter(["\n", "\n", a_state(workspace())]) + + def execute(command: str, /) -> tuple[int, str]: + machine.commands.append(command) + return 0, next(answers) + + monkeypatch.setattr(machine, "execute", execute) + + assert kde.state()["monitors"]["focused"] == 0 + assert len(machine.commands) == 3 + + +def test_a_daemon_that_always_says_nothing_fails_the_test_after_the_attempts( + machine: FakeMachine, +) -> None: + machine.reply("komorebic state", output="\n") + + with pytest.raises(AssertionError, match="did not answer"): + Kde(machine, "main", scale=0.0).state(attempts=3) + assert len(machine.commands) == 3 + + +def test_a_komorebic_that_gives_up_waiting_is_asked_again( + machine: FakeMachine, monkeypatch: pytest.MonkeyPatch +) -> None: + # `komorebic` waits a second for the daemon and panics (exit status 101) when it is not enough + answers = iter([(101, "thread 'main' panicked"), (0, a_state(workspace()))]) + + def execute(command: str, /) -> tuple[int, str]: + machine.commands.append(command) + return next(answers) + + monkeypatch.setattr(machine, "execute", execute) + + assert Kde(machine, "main", scale=0.0).state()["monitors"]["focused"] == 0 + assert len(machine.commands) == 2 + + +def test_an_answer_that_is_not_json_fails_at_once(machine: FakeMachine) -> None: + machine.reply("komorebic state", output="panic: Resource temporarily unavailable\n") + + with pytest.raises(ValueError): + Kde(machine, "main", scale=0.0).state() + assert len(machine.commands) == 1 + + +def window(title: str) -> dict[str, object]: + return {"id": 1, "details": {"title": title, "exe": "foot", "class": "foot", "path": ""}} + + +def container(*titles: str, focused: int = 0) -> dict[str, object]: + return { + "id": "c", + "locked": False, + "windows": {"elements": [window(t) for t in titles], "focused": focused}, + } + + +def workspace(*containers: dict[str, object], focused: int = 0) -> dict[str, object]: + return {"containers": {"elements": list(containers), "focused": focused}} + + +def a_state(*workspaces: dict[str, object]) -> str: + """What `komorebic state` prints for one monitor with these workspaces.""" + monitor = {"id": 1, "workspaces": {"elements": list(workspaces), "focused": 0}} + return json.dumps({"monitors": {"elements": [monitor], "focused": 0}}) + + +def test_the_state_is_what_komorebic_state_prints(machine: FakeMachine) -> None: + machine.reply("komorebic state", output=a_state(workspace())) + + state = Kde(machine, "main").state() + + assert state["monitors"]["elements"][0]["workspaces"]["focused"] == 0 + assert [inner(command) for command in machine.commands] == ["komorebic state"] + + +def test_managed_counts_the_windows_of_every_container_of_the_workspace( + machine: FakeMachine, +) -> None: + machine.reply( + "komorebic state", + output=a_state(workspace(container("a", "b"), container("c")), workspace(container("d"))), + ) + kde = Kde(machine, "main") + + assert kde.managed() == 3 + assert kde.managed(1) == 1 + + +def test_managed_is_zero_for_a_workspace_without_containers(machine: FakeMachine) -> None: + machine.reply("komorebic state", output=a_state(workspace())) + + assert Kde(machine, "main").managed() == 0 + + +def test_focused_title_is_the_focused_window_of_the_focused_container( + machine: FakeMachine, +) -> None: + machine.reply( + "komorebic state", + output=a_state( + workspace(container("a"), container("b", "c", focused=1), focused=1), + workspace(container("d")), + ), + ) + kde = Kde(machine, "main") + + assert kde.focused_title() == "c" + assert kde.focused_title(1) == "d" + + +def test_focused_title_is_empty_for_a_workspace_without_containers(machine: FakeMachine) -> None: + machine.reply("komorebic state", output=a_state(workspace())) + + assert Kde(machine, "main").focused_title() == "" diff --git a/nix/tests/vm/nodes/headless.nix b/nix/tests/vm/nodes/headless.nix index 638c6d15..bd0ccb22 100644 --- a/nix/tests/vm/nodes/headless.nix +++ b/nix/tests/vm/nodes/headless.nix @@ -2,7 +2,8 @@ # own user units, once for every session a test starts, each with its own private session bus and # Wayland socket (`session-bus@NAME`, `kwin-virtual@NAME`). A virtual KWin has no real output, so it # cannot draw: pixel and pointer tests use the session node instead. `komorebi@NAME` runs the daemon -# in a session; `komorebi` is the package, which the test framework passes in. +# in a session; `komorebi` is the package of the daemon and `komorebic`, which the test framework +# passes in. { config, lib, diff --git a/nix/tests/vm/suites/core-e2e/test.py b/nix/tests/vm/suites/core-e2e/test.py index e711fe49..231508b9 100644 --- a/nix/tests/vm/suites/core-e2e/test.py +++ b/nix/tests/vm/suites/core-e2e/test.py @@ -1,9 +1,12 @@ # komorebi tiles a real KWin. What only a real KWin can tell: that the commands the daemon queues # reach KWin through the held call and that KWin carries them out, so that each window is where # the daemon asked for it (`komorebi/tests/wm_events.rs` checks the window manager's side against -# the fake), and that the daemon and KWin agree on which window has the focus. A window manager -# that agrees with itself proves nothing, so what the daemon believes is read from its debug log -# and what KWin has through kdotool. +# the fake), that the daemon and KWin agree on which window has the focus, that `komorebic` reaches +# the daemon of a session and reads its state, and that `komorebic stop` gives KWin back what the +# daemon set up in it. A window manager that agrees with itself proves nothing, so what the daemon +# believes is read from its debug log and from `komorebic state`, and what KWin has through kdotool. +import json + from komorebi_vm import Checks, Kde, Rect, daemon W, H = 1920, 1080 @@ -53,6 +56,18 @@ def focus_agrees() -> bool: return daemon.window_ids(log).get(kde.title(active)) == focus_changes[-1] +def answering() -> bool: + """`komorebic monitor-information` is answered, with the session's one output.""" + status, out = kde.run("komorebic monitor-information") + return status == 0 and json.loads(out)[0]["size"]["right"] == W + + +def state_agrees() -> bool: + """The window komorebi's state has focused is the one KWin has.""" + active = kde.active() + return active != "" and kde.title(active) == kde.focused_title() + + def report(titles: list[str]) -> None: for title in titles: print(f" {title}: asked {asked(title)}, has {kde.rect(kde.wid(title))}") @@ -65,6 +80,7 @@ checks.check( kde.wait_for(lambda: "loaded the KWin bridge script" in daemon_log(), timeout=30), ) checks.check("KWin runs the script", kde.script_loaded()) +checks.check("the daemon is up and answering komorebic", kde.wait_for(answering, timeout=30)) print("== 2. three windows are tiled") titles = ["win1", "win2", "win3"] @@ -83,11 +99,14 @@ checks.check("win1 and win3 do not overlap", not rects[0].overlaps(rects[2])) checks.check("win2 and win3 do not overlap", not rects[1].overlaps(rects[2])) checks.check("the windows share the screen: none is full width", all(r.w < W - 20 for r in rects)) checks.check("KWin and the daemon agree on the focused window", kde.wait_for(focus_agrees)) +checks.check("komorebi manages the three windows", kde.wait_for(lambda: kde.managed() == 3)) +checks.check("komorebi's state focuses the window KWin does", kde.wait_for(state_agrees)) print("== 3. the focus moves by hand") kde.activate(kde.wid("win1")) checks.check("KWin focused win1", kde.wait_for(lambda: kde.title(kde.active()) == "win1")) checks.check("... and the daemon followed", kde.wait_for(focus_agrees)) +checks.check("... and its state says so", kde.wait_for(state_agrees)) print("== 4. minimize and restore") kde.minimize(kde.wid("win2")) @@ -130,13 +149,36 @@ checks.check( ), ) report(["win1", "win2"]) +checks.check("komorebi manages the two that are left", kde.wait_for(lambda: kde.managed() == 2)) checks.check("KWin carried out every command", "the bridge could not do" not in daemon_log()) -print("== 6. stop") -kde.stop_komorebi() -checks.check("the daemon exited", not kde.komorebi_running()) +print("== 6. KWin restarts under the daemon") +kde.restart_kwin() +checks.check( + "the daemon loaded its script into the new KWin", + kde.wait_for(lambda: daemon_log().count("loaded the KWin bridge script") == 2, timeout=30), +) +checks.check( + "komorebi let go of the windows of the old KWin", kde.wait_for(lambda: kde.managed() == 0) +) +kde.spawn("foot -T afterwards sleep 3000") +kde.wait_for(lambda: kde.wid("afterwards") != "", timeout=30) +checks.check("a window opened in the new KWin is managed", kde.wait_for(lambda: kde.managed() == 1)) +checks.check( + "... and tiled on its own", + kde.wait_for( + lambda: where_asked("afterwards") and kde.rect(kde.wid("afterwards")).w > W - 100, + timeout=20, + ), +) +report(["afterwards"]) + +print("== 7. komorebic stop") +kde.komorebic("stop") +checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running())) +checks.check("its socket is gone", kde.run(f"test -e {kde.runtime}/komorebi/komorebi.sock")[0] != 0) checks.check("the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded())) -checks.check("the windows stay", kde.wid("win1") != "" and kde.wid("win2") != "") +checks.check("the window stays", kde.wid("afterwards") != "") kde.stop() checks.finish()