diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f63caf46..fcf1169b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,12 +37,28 @@ provides the Rust toolchain, a nightly `rustfmt` and the tools the checks use. formatter is a nightly one. `just check` runs everything a change has to pass before it is pushed: the -formatting check, clippy with warnings denied, the tests, and rustdoc with -warnings denied. `just fmt` formats the Rust sources, and `nix fmt` every file +formatting check, clippy with warnings denied, the tests, rustdoc with warnings +denied, and the checks of the bridge. `just fmt` formats the Rust sources, and `nix fmt` every file type the repository has. `nix flake check` builds the same checks, plus `cargo deny`, as derivations; on Linux it also boots every VM test, which needs KVM. +## The bridge + +[`bridge.js`](komorebi/src/kwin/bridge.js), the script komorebi loads into +KWin, is JavaScript that KWin runs as it is: there is no package.json and no +build step. Its types are JSDoc comments, which `tsc` checks against +[`kwin-api.d.ts`](komorebi/src/kwin/kwin-api.d.ts), the part of KWin's +scripting API the bridge uses; something the bridge starts to use is declared +there first. Its tests, [`bridge.test.js`](komorebi/src/kwin/bridge.test.js), +run under `node --test` against a fake KWin. `just check-js` runs both, with the +`tsc` and `node` of the dev shell. + +The messages between the bridge and the daemon are in +[`komorebi/src/kwin/fixtures`](komorebi/src/kwin/fixtures), which the tests of +both sides read. A change to a message changes the fixture, the bridge and the +daemon in the same commit. + ## VM tests A change that needs a real KWin to be checked comes with a VM test, next to diff --git a/Cargo.lock b/Cargo.lock index b5a228de..8f57b407 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -85,6 +85,40 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -148,6 +182,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + [[package]] name = "cc" version = "1.10.0" @@ -285,6 +325,21 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + [[package]] name = "ctrlc" version = "3.5.2" @@ -370,6 +425,27 @@ dependencies = [ "serde_core", ] +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys", +] + [[package]] name = "dispatch2" version = "0.3.1" @@ -399,6 +475,33 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -415,6 +518,26 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "eyre" version = "0.6.14" @@ -426,12 +549,24 @@ dependencies = [ "once_cell", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -447,6 +582,25 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-task" version = "0.3.34" @@ -792,8 +946,11 @@ version = "0.1.0" dependencies = [ "clap", "color-eyre", + "crossbeam-channel", "ctrlc", + "dirs", "komorebi-layouts", + "lazy_static", "nanoid", "parking_lot", "pastey", @@ -802,9 +959,11 @@ dependencies = [ "serde_json_lenient", "serde_with", "strum", + "tokio", "tracing", "tracing-subscriber", "version", + "zbus", ] [[package]] @@ -861,6 +1020,15 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + [[package]] name = "libz-sys" version = "1.1.30" @@ -915,6 +1083,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -924,6 +1101,17 @@ dependencies = [ "adler2", ] +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + [[package]] name = "nanoid" version = "0.4.0" @@ -1014,12 +1202,34 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + [[package]] name = "owo-colors" version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -1036,8 +1246,10 @@ version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ + "backtrace", "cfg-if", "libc", + "petgraph", "redox_syscall", "smallvec", "windows-link", @@ -1055,6 +1267,16 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" +dependencies = [ + "fixedbitset", + "indexmap 2.14.2", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1106,6 +1328,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -1169,6 +1400,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror", +] + [[package]] name = "ref-cast" version = "1.0.27" @@ -1340,12 +1581,24 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e033097bf0d2b59a62b42c18ebbb797503839b26afdda2c4e1415cb6c813540" dependencies = [ + "indexmap 2.14.2", "itoa", "memchr", "ryu", "serde", ] +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "serde_with" version = "3.24.0" @@ -1420,6 +1673,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "slab" version = "0.4.12" @@ -1432,6 +1695,16 @@ version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -1498,6 +1771,19 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys", +] + [[package]] name = "terminal_size" version = "0.4.4" @@ -1585,6 +1871,52 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tracing", + "windows-sys", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + [[package]] name = "tracing" version = "0.1.44" @@ -1682,6 +2014,17 @@ dependencies = [ "tz-rs", ] +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys", +] + [[package]] name = "unicode-ident" version = "1.0.27" @@ -1724,6 +2067,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" @@ -1862,6 +2216,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + [[package]] name = "writeable" version = "0.6.4" @@ -1891,6 +2254,71 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tokio", + "tracing", + "uds_windows", + "uuid", + "windows-sys", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -1970,3 +2398,44 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml index 6bd3f573..c4bf2334 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,9 @@ komorebi-layouts = { git = "https://github.com/LGUG2Z/komorebi", rev = "f08aa555 clap = { version = "4", features = ["derive", "wrap_help"] } color-eyre = "0.6" +crossbeam-channel = "0.5" +dirs = "6" +lazy_static = "1" pastey = "0.2" schemars = "1.1" serde = { version = "1", features = ["derive"] } diff --git a/README.md b/README.md index 4b613c76..7f5cc72b 100644 --- a/README.md +++ b/README.md @@ -11,12 +11,19 @@ moving and the drawing. ```sh nix develop cargo run --bin komorebi --locked -- --version +cargo run --bin komorebi --locked -- --log-level debug cargo run --bin komorebi --locked -- --fake-backend ``` -`--fake-backend` runs the window manager against an in-memory desktop with one -monitor and no windows, and logs what it does until it is stopped with Ctrl-C. -Without a backend, `komorebi` exits with a usage error. +Inside a Plasma Wayland session, `komorebi` loads a script into KWin, reads the +monitors and the windows that are open, and logs every window that opens, +closes, takes the focus, is minimized or comes back, until it is stopped with +Ctrl-C. It reads the desktop and does not change it: every attempt to move +a window is logged as refused. It needs KWin 6.8 or newer; +[`docs/dev/PLATFORM.md`](docs/dev/PLATFORM.md) has what it expects of the +session. Outside a Plasma session it exits with an error that says what is +missing. `--fake-backend` runs the window manager against an in-memory desktop +with one monitor and no windows instead. `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 @@ -29,12 +36,13 @@ without a checkout of the toolchain. - [`komorebi`](komorebi): the daemon, and the library behind it. The library has the vocabulary the window manager is written in (`core`), the `Backend` trait through which it reaches a compositor and the in-memory desktop the tests use - (`backend`), the model of what it tiles (`monitor`, `workspace`, `container`, - `window`), the window manager that keeps the model (`window_manager`), loads - it from the backend (`desktop`) and changes it when the compositor reports an - event (`window_manager_event`, `process_event`), the `Ring` that holds - monitors, workspaces and containers, and the lists in which some elements are - locked in place. + (`backend`), the backend that reaches KWin through a script it runs (`kwin`), + the model of what it tiles (`monitor`, `workspace`, `container`, `window`), the + window manager that keeps the model (`window_manager`), loads it from the + backend (`desktop`) and changes it when the compositor reports an event + (`window_manager_event`, `window_manager_event_listener`, `process_event`), the + `Ring` that holds monitors, workspaces and containers, and the lists in which + some elements are locked in place. - [`version`](version): the version string every binary reports. The layouts, which turn a work area and a number of containers into a rectangle @@ -43,11 +51,12 @@ a git dependency at the revision `Cargo.toml` pins. ## Checks -`just check` runs the formatting check, clippy with warnings denied, the tests -and rustdoc with warnings denied, inside `nix develop`. `nix flake check` runs -the same checks as derivations, plus `cargo deny`, the TOML and Nix formatting, -and the tests under `cargo nextest`, on Linux and on an Apple silicon Mac. On -Linux it also boots every VM test, which needs KVM. A Mac +`just check` runs the formatting check, clippy with warnings denied, the tests, +rustdoc with warnings denied, and the type check and tests of the bridge (no +package.json: `tsc` and `node` come from the dev shell), inside `nix develop`. +`nix flake check` runs the same checks as derivations, plus `cargo deny`, the +TOML and Nix formatting, and the tests under `cargo nextest`, on Linux and on an +Apple silicon Mac. On Linux it also boots every VM test, which needs KVM. A Mac runs the tests against the fake desktop, since KWin only exists on Linux. `nix fmt` formats every file the checks look at. @@ -63,6 +72,13 @@ so the window manager logic runs against a real compositor and against an in-memory fake desktop alike. [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md) describes the trait and where each of its rules is enforced. +On KDE Plasma the backend is in two parts. A script that komorebi loads into +KWin, the bridge, reports what KWin sees over the session bus, and carries out +the commands it is given as the answer to a call it holds open. The daemon keeps +a table of the windows and monitors from those reports, answers the window +manager's questions from it, and turns each report into an event for the window +manager. + The window manager models the desktop as monitors, each with a ring of workspaces, each with a ring of containers, each with a ring of windows. A workspace's layout gives each of its containers a tile of the monitor's work @@ -77,8 +93,9 @@ tiles the workspace in front again. `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, -[`docs/dev/DESIGN.md`](docs/dev/DESIGN.md) says why it is built that way, and -[`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) how the VM tests work. +[`docs/dev/DESIGN.md`](docs/dev/DESIGN.md) says why it is built that way, +[`docs/dev/PLATFORM.md`](docs/dev/PLATFORM.md) what it needs from KDE Plasma, +and [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) how the VM tests work. ## License diff --git a/deny.toml b/deny.toml index 99171afc..8ce0cea6 100644 --- a/deny.toml +++ b/deny.toml @@ -13,10 +13,20 @@ feature-depth = 1 [advisories] ignore = [ { id = "RUSTSEC-2024-0449", reason = "unsafe-libyaml comes with serde_yaml, which komorebi-layouts reads Windows-only custom layouts with; nothing here calls it" }, + { id = "RUSTSEC-2026-0370", reason = "zvariant is maintained inside zbus from zbus 6; komorebi talks to KWin with zbus 5" }, + { id = "RUSTSEC-2026-0371", reason = "zbus_names is maintained inside zbus from zbus 6; komorebi talks to KWin with zbus 5" }, + { id = "RUSTSEC-2026-0372", reason = "zvariant_derive is maintained inside zbus from zbus 6; komorebi talks to KWin with zbus 5" }, ] [licenses] -allow = ["Apache-2.0", "MIT", "Unicode-3.0", "Zlib", "LicenseRef-Komorebi-2.0"] +allow = [ + "Apache-2.0", + "MIT", + "MPL-2.0", + "Unicode-3.0", + "Zlib", + "LicenseRef-Komorebi-2.0", +] confidence-threshold = 0.8 [[licenses.clarify]] diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 6eee4f58..b81921ac 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -6,9 +6,9 @@ compositor to put it there. Everything it needs from the compositor is behind on tested, without one. This page describes that trait, who implements and calls it, where each of its rules is -enforced, the model of the desktop the window manager tiles, and how an event about a -window becomes a tile. It grows with the code: each part of the daemon that is added has -its place here. +enforced, the model of the desktop the window manager tiles, the backend that reaches KWin, +and how an event about a window becomes a tile. It grows with the code: each part of the +daemon that is added has its place here. ## Vocabulary @@ -30,6 +30,12 @@ its place here. trait that talks to a compositor. - **Fake**: [`FakeBackend`](../../komorebi/src/backend/fake.rs), the in-memory backend the tests use. +- **Bridge**: the script komorebi loads into KWin ([`bridge.js`]). It reports what KWin + tells it and carries out what the daemon asks. +- **Table**: the KWin backend's model of the desktop ([`Table`]), which the bridge's events + keep up to date and the queries are answered from. +- **Held call**: the `Poll` call the bridge always has open, which the daemon answers when it + has commands for the bridge, or after 10 seconds with none. ## Design @@ -84,6 +90,52 @@ monitor, and every open window that is normal, alive and not minimized, on the f workspace of the monitor its middle is on. After that it changes only when an event comes in, and each event ends with the workspace in front tiled again. +## The KWin backend + +[`KWinBackend`] is the backend of a real Plasma session. KWin has no protocol that lets +another process read and set window geometry, so the backend is in two processes: + +- **The bridge**, [`bridge.js`], a script KWin runs inside itself. It subscribes to KWin's + signals and sends each as a JSON `Event` call over the session bus, and it carries out the + commands it gets as the answer to its held `Poll` call. When it starts it sends a snapshot + of the desktop. It holds no window manager logic. +- **The daemon's side**, [`kwin`], owns `org.komorebi.Bridge` on the session bus, with one + object for `Event` and one for `Poll`. `Event` calls are handled one at a time, in the order + they arrive, and never wait. A `Poll` call is held until there are commands, so that the + bridge gets them as soon as they are queued, without a timer and without a call from the + daemon into KWin. + +Every decision about what an event means is made in the daemon, by the table +([`kwin::state`]): an event goes in, the table is updated, and what follows comes out, a +window event for the window manager or the answer to a query. The table is pure (no D-Bus, +no threads), so the unit tests drive it with the JSON the bridge sends. + +The bridge is JavaScript, which no Rust build compiles, and KWin loads the file as it is, so +it is checked without a build step. `tsc` checks it as strict TypeScript through its JSDoc +comments, which type every message, against [`kwin-api.d.ts`], the part of KWin's scripting +API the bridge uses. [`bridge.test.js`] runs it with `node --test` against a fake of that API. +The two sides share the messages of a session in [`fixtures`]: the bridge's tests check that +it sends exactly those events, and answer it with those commands, and the Rust tests feed +the events to the table and check that the backend sends those commands. A change to a +message on one side fails a test on the other. + +The path of an event: a KWin signal, the bridge's handler, `Event(json)` on the session bus, +[`Table::handle`], a [`WindowManagerEvent`] on the channel of +[`window_manager_event_listener`], the thread that [`listen_for_events`] starts, and +[`WindowManager::process_event`]. The queries (`windows`, `window`, `foreground_window`, +`monitors`) are answered from the table. `cursor_pos` is the exception: only the bridge can +read the pointer, so it is asked through the held call, and given 250 ms to answer before +the table's last known position is returned. + +The KWin backend only reads the desktop: every command is an error, "the KWin backend only +reads the desktop", which the window manager logs. When komorebi stops, the backend asks KWin +to unload the bridge. + +[`connect`] makes the backend: it connects to the session bus, loads the bridge into KWin, +and returns once the snapshot has arrived, so that the window manager reads a full table when +it starts. [PLATFORM.md](PLATFORM.md) has the D-Bus names, the files and the environment +variables; [DESIGN.md](DESIGN.md#why-does-komorebi-run-a-script-inside-kwin) has the reasons. + ## The parts - [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the @@ -105,9 +157,15 @@ in, and each event ends with the workspace in front tiled again. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and [`process_event`](../../komorebi/src/process_event.rs): the events, and what the window manager does with each. -- [`main.rs`](../../komorebi/src/main.rs): the daemon. It installs the backend chosen on the - command line (`--fake-backend` is the only one), loads and tiles the desktop, and waits to - be stopped. +- [`window_manager_event_listener`](../../komorebi/src/window_manager_event_listener.rs): the + channel that carries events from the backend to the window manager, and + [`listen_for_events`], the thread that takes them off it. +- [`kwin`](../../komorebi/src/kwin/mod.rs): the KWin backend, its D-Bus service and the held + call; [`kwin::state`](../../komorebi/src/kwin/state.rs), the table; and + [`bridge.js`](../../komorebi/src/kwin/bridge.js), the bridge. +- [`main.rs`](../../komorebi/src/main.rs): the daemon. It connects to KWin, or installs the + fake with `--fake-backend`, loads and tiles the desktop, starts the thread that handles + events, and waits to be stopped. The handle is a process-wide singleton so that a window can be a small `Copy` value that carries only its id, and ask the backend for what it needs. A test replaces it for @@ -120,7 +178,8 @@ done, also if it panics. the fake. The window manager is its only caller, through [`backend`]. The contract: - Queries (`windows`, `window`, `foreground_window`, `cursor_pos`) answer from the - backend's own table and never wait for the compositor. `monitors` may fail. + backend's own table and never wait for the compositor, except the KWin backend's + `cursor_pos`, which waits up to 250 ms for the bridge. `monitors` may fail. - A command returns once the compositor has accepted it, not once the client has acted on it. The frame a window ends up with is what `window_rect` says afterwards, because a client may refuse a size. @@ -142,21 +201,36 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window` and `test_locked_containers_remove_window` | `containers_mut()` is the `VecDeque` itself | | A window komorebi does not manage is never moved | framework path: `handle_event` asks [`Window::should_manage`] before it acts on any event but a destroy | `dialogs_and_other_non_normal_windows_are_left_alone` | none | | A destroyed window leaves whichever workspace has it | framework path: the destroy is looked up in the index of managed windows, which is rebuilt at startup and before and after every event | `a_window_that_was_open_before_komorebi_started_is_removed_when_it_closes` | none | -| The daemon does not start without a backend | startup check: a usage error, exit code 2 | `without_a_backend_komorebi_exits_with_an_error_naming_the_flag` | none | -| Queries never block on the compositor | convention only | none | none | +| The daemon does not start without KWin, unless it is told to run against the fake | startup check: [`connect`] fails, and the daemon exits with the error, code 1 | `without_a_session_bus_komorebi_exits_with_an_error_naming_it` | `--fake-backend` | +| One komorebi per session | startup check: the session bus gives `org.komorebi.Bridge` to one connection | none | none | +| Events reach the window manager in the order KWin raised them | framework path: the `Event` interface is `spawn = false`, so the calls are handled inline, and one channel and one thread carry the events to the window manager | `vm-kwin-events` ("the Show came first") | none | +| No event names a window before the event that announces it | convention in the bridge, which announces a window it has not seen when it is activated; the table shows a window once | `a_new_window_raises_show_and_then_focus_in_that_order`, `announcing_the_same_window_twice_shows_it_once`, `vm-kwin-events` | none | +| A window's id names one window while the daemon runs | framework path: the table numbers each KWin window the first time it sees it, and never gives a number out twice | `ids_are_assigned_once_per_window_and_survive_a_new_snapshot`, `tombstones_are_dropped_after_a_while_and_their_ids_are_not_reused` | none | +| A backend never waits for the window manager | framework path: an event that does not fit in the channel (20 waiting) is dropped and logged | none | none | +| The KWin backend changes nothing on the desktop | runtime error: every command returns "the KWin backend only reads the desktop"; type checker: [`kwin-api.d.ts`] declares every property the bridge could set read-only | `vm-kwin-events` ("nothing was moved"), `tsc` | none | +| The bridge holds no window manager logic | convention, with every decision about an event in the table, which the `kwin::state` unit tests pin | the unit tests in `komorebi/src/kwin/state.rs` | none | +| What the bridge sends is what the table reads | type checker: the JSDoc types of the messages in [`bridge.js`]; tests: the events of [`fixtures`] are what the bridge's tests check it sends and what the table's tests feed it | `what the bridge sends for a session is what the daemon's tests read`, `the_bridges_events_for_a_session_are_the_window_events_komorebi_expects` | none | +| What the backend sends is what the bridge carries out | tests: the commands of [`fixtures`] are what the backend's tests check it sends and what the bridge's tests answer it with | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read` | none | +| Everything the bridge sends over D-Bus is one string | type checker: [`kwin-api.d.ts`] gives `callDBus` one string argument | `tsc`, `every call goes to the daemon's names, with one JSON string` | none | +| The bridge uses nothing a KWin script does not have | type checker: the library is ECMAScript 2016 alone, and KWin's API is what [`kwin-api.d.ts`] declares | `tsc` | a declaration KWin does not match: the VM tests run the bridge in KWin | +| Queries never block on the compositor | convention only | none | the KWin backend's `cursor_pos` waits up to 250 ms | | Only the backend module reaches the compositor | convention only | none | none | -The last two rows are rules nothing checks. A real backend that waits inside a query -breaks the first, and a module that talks to D-Bus directly breaks the second. +The rows enforced by convention are rules nothing checks. A real backend that waits inside a +query breaks one of them, a module that talks to D-Bus directly breaks another, and a bridge +that decides something in JavaScript breaks a third: the bridge's tests check what it sends, +not that it decides nothing. ## One event, end to end A window is shown, and ends up on a tile: -1. The event is a [`WindowManagerEvent`]`::Show` carrying the window and the compositor - signal it came from. The end-to-end tests build it and call - [`WindowManager::process_event`], which hands it to `handle_event` and logs how long - that took. +1. KWin raises `windowAdded`. The bridge sends an `added` event with what KWin says about + the window, and [`Table::handle`] gives the window an id, records it, and returns a + [`WindowManagerEvent`]`::Show` carrying the window and the compositor signal it came + from. The event goes on the channel, and the event thread calls + [`WindowManager::process_event`], which hands it to `handle_event` and logs how long that + took. The end-to-end tests build the event themselves and call `process_event`. 2. `handle_event` asks [`Window::should_manage`], which asks the backend's `window(id)` whether the window is alive and normal. If it is not, the event changes nothing. 3. The index of managed windows is rebuilt from the containers. If the workspace in front @@ -171,7 +245,8 @@ A window is shown, and ends up on a tile: 6. `Workspace::update` asks the layout for one tile per container, clamps each to the work area, and calls [`Window::set_position`] for each window, which is the backend's `set_rect`. The fake puts the window there at once; the frame a window ends up with is - what `window_rect` says afterwards. + what `window_rect` says afterwards. The KWin backend refuses, and the window stays where + KWin put it. 7. If the new container is the only one, the window is given the focus with the backend's `focus`, and the pointer follows it. 8. The index is rebuilt again, so the next event finds the window. @@ -188,7 +263,17 @@ A window is shown, and ends up on a tile: - [`komorebi/src/monitor.rs`](../../komorebi/src/monitor.rs): the work area, padding and offset a monitor gives the workspace it shows. - [`komorebi/src/process_event.rs`](../../komorebi/src/process_event.rs): what each event - does. + does, and the thread that handles them. +- [`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 + shapes of the bridge's events, and its tests. +- [`komorebi/src/kwin/bridge.js`](../../komorebi/src/kwin/bridge.js): the bridge, with the + types of its messages; [`kwin-api.d.ts`] and + [`tsconfig.json`](../../komorebi/src/kwin/tsconfig.json), what `tsc` checks it against; + [`bridge.test.js`], its tests; [`fixtures`], the messages both sides' tests read. +- [`nix/tests/vm/suites/kwin-events`](../../nix/tests/vm/suites/kwin-events/test.py): the + daemon against a real KWin. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager driven end to end against the fake. @@ -212,3 +297,15 @@ A window is shown, and ends up on a tile: [`WindowManager::process_event`]: ../../komorebi/src/process_event.rs [`WindowManager::update_focused_workspace`]: ../../komorebi/src/window_manager.rs [`WindowManagerEvent`]: ../../komorebi/src/window_manager_event.rs +[`window_manager_event_listener`]: ../../komorebi/src/window_manager_event_listener.rs +[`listen_for_events`]: ../../komorebi/src/process_event.rs +[`KWinBackend`]: ../../komorebi/src/kwin/mod.rs +[`connect`]: ../../komorebi/src/kwin/mod.rs +[`kwin`]: ../../komorebi/src/kwin/mod.rs +[`kwin::state`]: ../../komorebi/src/kwin/state.rs +[`Table`]: ../../komorebi/src/kwin/state.rs +[`Table::handle`]: ../../komorebi/src/kwin/state.rs +[`bridge.js`]: ../../komorebi/src/kwin/bridge.js +[`kwin-api.d.ts`]: ../../komorebi/src/kwin/kwin-api.d.ts +[`bridge.test.js`]: ../../komorebi/src/kwin/bridge.test.js +[`fixtures`]: ../../komorebi/src/kwin/fixtures diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 7b268893..b99fe405 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -58,3 +58,78 @@ it considers next and reports that as a focus change, which komorebi follows. If also focused a window of its own choosing, the two would fight over the focus. komorebi focuses the window of its focused container only when the compositor has left nothing focused. + +## Why does komorebi run a script inside KWin? + +KWin has no protocol that lets another process read and set window geometry. Its scripting +API has both, and a signal for each change komorebi follows: a window added, removed, +activated, minimized, moved or resized. So the part of the backend that sees and touches +windows is a script KWin runs, the bridge, and the daemon talks to it over the session bus. + +## Why does the bridge hold no logic? + +So that everything the backend decides can be tested without KWin. A script runs only inside +KWin: its own tests run it against a fake of KWin's API, which is only as right as the fake, +and a test of it against KWin needs a virtual machine. The bridge reports what KWin says, as +it says it, and carries out what it is told; what an event means (is this a window komorebi +manages, has it been announced already, which id does it have) is decided by the table in +`kwin::state`, which is plain Rust that takes the bridge's JSON and is unit-tested with it. + +## Why is the bridge type-checked and tested without a JavaScript build chain? + +I wanted safety, tests and typing around the bridge that do not need a JavaScript build +chain. KWin loads `bridge.js` as it is, so the checks read that file and produce nothing: + +- `tsc` checks it as strict TypeScript through its JSDoc comments (`checkJs`, `noEmit`), + against `kwin-api.d.ts`, a hand-written declaration of the part of KWin's scripting API the + bridge uses. KWin publishes no declarations, and the declarations are narrower than the API + where that catches a mistake: a property the bridge has no reason to set is read-only, and + `callDBus` takes one string. +- `bridge.test.js` runs under `node --test`, node's own test runner, and loads the bridge into + a `node:vm` context whose globals are a fake KWin. +- The messages of a session are JSON files that the bridge's tests and the Rust tests both + read, so neither side can change a message alone. + +`tsc` and `node` come from nixpkgs, through the dev shell and the flake's +`komorebi-bridge-js` check. There is no package.json, no npm dependency and no bundler. + +## Why do commands go to the bridge as the answer to a held call? + +Because it was the fastest channel measured, and it costs nothing while nothing happens. Four +ways for the daemon to get commands to a script in KWin were measured in October 2026, on +KWin 6.8.1 in a VM under HVF: twenty windows retiled in one batch, twenty times, timed from +the send until every window reported its new frame. + +| Channel | p50 / p95 / max | +|---|---| +| a held `Poll` call, answered when there are commands | 16 / 19 / 20 ms | +| the script polls on a 16 ms timer | 16 / 20 / 32 ms | +| the script polls on a 50 ms timer | 49 / 57 / 65 ms | +| a new script per batch (`loadScript`, `run`, `unloadScript`) | 17 / 18 / 20 ms | + +A timer is as fast only at about 60 D-Bus calls a second, forever. A new script per batch is +as fast, but 7 of its 17 ms (p50) are spent in the daemon's calls to KWin. A held call is +answered as soon as there is a batch, and an idle bridge makes one call every 10 seconds. +Rounds after idle gaps of 15 seconds to 10 minutes all completed, the slowest in 49 ms. + +The hold is 10 seconds because QtDBus fails a call after 25 seconds. A call that fails is +never answered (the callback of `callDBus` runs on success only), so the bridge has a +one-second watchdog that calls `Poll` again when the last call is older than the hold plus 3 +seconds, which is also how it finds a daemon that has restarted. + +## Why are events and the held call on two D-Bus objects? + +Because events must arrive in order and a held call waits. zbus handles each method call in a +task of its own by default, and two pairs of events were seen swapped. The `Event` interface +is therefore `spawn = false`: zbus handles its calls inline, one after the other, in the +order they arrive. The price is that a handler that waits holds up every call after it, so +`Event` never waits, and `Poll`, which waits by design, is a separate object with the default +spawning. + +## Why does everything cross D-Bus as a JSON string? + +Because a script cannot choose the D-Bus type of what it sends. `callDBus` sends a JavaScript +number as a 32-bit integer, and a call whose arguments do not match the method's signature +fails with no error the script can see. One string argument always matches, and the daemon +parses it. The declaration of `callDBus` the bridge is type-checked against takes one string, +so `tsc` refuses anything else. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md new file mode 100644 index 00000000..c3dbbd69 --- /dev/null +++ b/docs/dev/PLATFORM.md @@ -0,0 +1,200 @@ +# Platform + +komorebi for KDE runs in a KDE Plasma session, as a client of KWin. Most of the details on +this page are also written down next to the code that depends on them; this page +centralizes them: which KWin it needs, how it finds it, what it creates in the session and +leaves behind, every environment variable it reads, and what happens when something is +missing. + +Facts that change with KWin and Plasma releases are dated. Unless a fact says otherwise, it +was measured with KWin 6.8.1, Plasma 6.8.1 and Qt 6.12.0 from nixpkgs `d3b13ad` +(2026-10-24), in NixOS virtual machines under QEMU on an Apple silicon Mac (HVF). + +## Vocabulary + +- **Session**: one user's Plasma login: KWin, the Plasma shell, and a D-Bus session bus they + share. +- **Session bus**: the D-Bus bus of the session. komorebi and KWin talk over it. +- **KWin**: the compositor and window manager of Plasma, `kwin_wayland`. +- **Script**: a JavaScript program that KWin runs inside itself, through its scripting API. + komorebi's is the **bridge**, [`bridge.js`](../../komorebi/src/kwin/bridge.js). +- **Output**: KWin's name for a monitor. +- **Headless KWin**: `kwin_wayland --virtual`, a KWin with virtual outputs and no display, + which the VM tests run ([vm-tests.md](vm-tests.md)). + +## What komorebi needs + +### KWin 6.8 or newer + +KWin 6.8 is the oldest KWin komorebi supports. The bridge reads the work area of each output +for the virtual desktop that output shows (`workspace.currentDesktopForScreen`), which is part +of the per-output virtual desktops KWin 6.8 introduced. At time of writing (2026-10-27) KWin +6.8.1 is the only version komorebi has been run against; 6.7 and older have not been tried. + +### Wayland + +komorebi runs in a Plasma Wayland session. There is no X11 session of Plasma 6.8 to run it in. +Programs that run on XWayland inside the Wayland session are windows like any other; KWin +reports their X11 class (`XTerm`) where a Wayland client has its app id (`foot`, +`org.kde.konsole`). + +### The session bus + +komorebi finds KWin on the session bus, and nowhere else. It needs to own the name +`org.komorebi.Bridge` there, and KWin has to own `org.kde.KWin`. See +[`DBUS_SESSION_BUS_ADDRESS`](#dbus_session_bus_address) for how the bus is found. + +## Environments + +The same questions, for each place the daemon can be started: + +1. How it finds KWin. +2. What it does there. +3. What it leaves behind. + +### A Plasma session + +#### How komorebi finds KWin + +Through the session bus. When the daemon is started from the session (a terminal, an +autostart entry, a user unit of the session), the bus is already in its environment. + +#### What komorebi does + +It connects to the session bus as `org.komorebi.Bridge`, writes the bridge to +`$XDG_RUNTIME_DIR/komorebi/bridge.js`, and asks KWin to load it under the name +`komorebi-bridge`, replacing a script of that name left by an earlier run. The script reports +the windows and outputs it finds, and from then on every window that opens, closes, takes the +focus, is minimized or brought back, moves or changes size. The daemon waits up to 10 seconds +for the first report and does not start without it. + +The KWin backend only reads the desktop. Every command the window manager gives it (move, +focus, raise, minimize, close a window, move the pointer) fails with "the KWin backend only +reads the desktop", which the window manager logs. + +#### What komorebi leaves behind + +When it is stopped with `SIGINT` or `SIGTERM` it asks KWin to unload the script. The file +`bridge.js` stays in the runtime directory, which is removed at logout. A daemon that is +killed leaves the script running in KWin, reporting to nobody, until the next start replaces +it or the session ends. + +### A headless KWin + +`kwin_wayland --virtual` behaves like the KWin of a session for everything komorebi does: +the VM tests run the daemon against one, on a private session bus of its own. It cannot draw +(see [Rendering](#rendering-in-virtual-machines-and-over-rdp)), so nothing that depends on +pixels can be tested against it. + +### No KWin + +Anywhere else (a session that is not Plasma, a Linux console, a Mac), the daemon exits with an +error that names what is missing: + +- "could not connect to the session bus as org.komorebi.Bridge": there is no session bus at + the address the environment gives, or another komorebi owns the name. +- "KWin is not on the session bus": the bus is there and KWin is not. +- "KWin loaded the bridge script but it never reported in": KWin is there, and the script did + not run. KWin logs a script's errors to the journal (`journalctl --user -t kwin_wayland`). + +`komorebi --fake-backend` runs the window manager against an in-memory desktop instead, which +works anywhere, for development and testing. + +## D-Bus + +What komorebi owns, on the session bus: + +| Name | Object | Interface | Member | Called by | +|---|---|---|---|---| +| `org.komorebi.Bridge` | `/org/komorebi/Bridge` | `org.komorebi.Bridge` | `Event(s)` | the bridge, for every event | +| `org.komorebi.Bridge` | `/org/komorebi/Bridge/Poll` | `org.komorebi.Bridge.Poll` | `Poll(s) -> s` | the bridge, for commands | + +Both take a JSON string. `Poll` is held: the daemon answers it when it has commands for the +bridge, or with an empty list after 10 seconds, and the bridge then calls it again. + +What komorebi calls: + +| Name | Object | Interface | Member | When | +|---|---|---|---|---| +| `org.kde.KWin` | `/Scripting` | `org.kde.kwin.Scripting` | `unloadScript(s)`, `loadScript(ss) -> i` | at start; `unloadScript` again at exit | +| `org.kde.KWin` | `/Scripting/Script` | `org.kde.kwin.Script` | `run()` | at start | + +## Files and directories + +| Path | What | Lifetime | +|---|---|---| +| `$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 | + +Without `XDG_RUNTIME_DIR` the directory is `komorebi` in the local data directory instead +(see [`XDG_DATA_HOME`](#xdg_data_home)). + +## 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). + +### `XDG_RUNTIME_DIR` + +The runtime directory of the user, normally `/run/user/`: komorebi writes the bridge to +the `komorebi` directory in it. + +### `XDG_DATA_HOME` + +Read only when `XDG_RUNTIME_DIR` is not set: the bridge is then written to +`$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if `XDG_DATA_HOME` is not set either). + +### `RUST_LOG` + +Which log lines the daemon prints, in the syntax of `tracing-subscriber`'s `EnvFilter` +(`komorebi=debug`, `komorebi::kwin=trace`). If it is not set, `--log-level` sets it to +`komorebi=`; `--log-level` defaults to `info`. + +### `RUST_LIB_BACKTRACE` + +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. + +## The bridge's environment + +What the KWin scripting API offers a script, and what it does not, at time of writing +(2026-10-27). The bridge is written around these, and +[`kwin-api.d.ts`](../../komorebi/src/kwin/kwin-api.d.ts) declares the part of the API it +uses, which `tsc` checks it against with ECMAScript 2016's library and nothing else. Node and +TypeScript are needed only for those checks: in the session the bridge needs KWin alone. + +- `callDBus` sends a JavaScript number as a 32-bit integer, and a call whose arguments do not + match the method's signature fails without a word. The bridge sends every argument as a + JSON string. +- The callback of `callDBus` is called on success only. A call that fails (the daemon has + exited) is never answered, so the bridge re-issues `Poll` from a one-second `QTimer` when + the last one is older than the hold time plus 3 seconds. +- There is a `QTimer`, but no `setTimeout`, and no `Qt` global: a rectangle is assigned as a + plain `{x, y, width, height}` object. +- KWin activates a new window before it announces it (`windowActivated` comes before + `windowAdded`). The bridge announces a window it has not seen when it is activated, so that + no event names a window before the event that announces it. +- A script's `print()` goes to KWin's log, which shows it only when the `kwin_scripting` + logging category is enabled (`QT_LOGGING_RULES="kwin_scripting.debug=true"`, as the VM + tests do). + +## Rendering in virtual machines and over RDP + +At time of writing (2026-10-27): + +- A headless KWin cannot render. Mesa's software rasterizer needs `CREATE_DUMB` on the + primary DRM node and the virtual backend offers only the render node, so KWin reports that + compositing is active while every frame fails, and screenshots are black. KWin does not start at all with no DRM + device. The VM nodes give the guest a `virtio-gpu` device for that reason. +- In a QEMU guest everything is drawn in software (llvmpipe on the guest's CPUs): the + nixpkgs QEMU has only the 2D `virtio-gpu`. KWin then refuses to load animating effects + unless `KWIN_EFFECTS_FORCE_ANIMATIONS=1` is in its environment, which the VM nodes set. +- KRDP 6.8.1, Plasma's RDP server, does not start without a TLS certificate and key, although + its `--help` says it generates one; it logs the error and keeps running with nothing + listening. `xrdp` is not an option, since there is no X11 session to start. diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index 12b584c5..df220bad 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -52,6 +52,9 @@ D-Bus session bus) and `kwin-virtual@NAME` (`kwin_wayland --virtual` with its 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. 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. @@ -92,6 +95,15 @@ the run. - `Kde.session(machine, scale=)` attaches to the session node's own Plasma session once its desktop is up, and `shot(name)` returns a screenshot as a Pillow image, keeping `NAME.png` in the output directory. +- `activate`, `minimize` and `close` act on a window through `kdotool`, as the + user would. +- `start_komorebi(*args)` starts the daemon in the session, `stop_komorebi()` + stops it with `SIGTERM`, `komorebi_log()` returns its log since it was last + started, and `script_loaded()` asks KWin whether it runs the bridge. +- `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, and `daemon.window_ids(log)` maps a window's title to the daemon's id + for it. Poll for what the test needs with `wait_for`. A fixed sleep is too long on KVM and too short on TCG. @@ -133,7 +145,9 @@ The script prints where the artifacts (screenshots, logs) are, under ## Writing a test 1. Create `nix/tests/vm/suites/NAME/default.nix` and `test.py`. Start from - [`suites/kwin`](../../nix/tests/vm/suites/kwin). + [`suites/kwin`](../../nix/tests/vm/suites/kwin), or from + [`suites/kwin-events`](../../nix/tests/vm/suites/kwin-events) for a test that + runs the daemon. 2. Pick the tier. `fast` suites are the pull request gate and should take minutes. `slow` suites run on `master` and every night. 3. Run it: `just vm NAME`. @@ -150,4 +164,5 @@ Add `git add -N` for new files first: a flake only sees files git knows about. build `driverInteractive` instead of `driver`, run it, and call `start_all()` and `machine.shell_interact()` at its prompt. In the guest, KWin's own log is `journalctl --user -u kwin-virtual@NAME` as the test user, and a KWin script's -`print()` goes to the same journal. +`print()` goes to the same journal. The daemon's log is +`/run/user/1000/komorebi-NAME.log`. diff --git a/flake.nix b/flake.nix index 09f742a8..9694a5fc 100644 --- a/flake.nix +++ b/flake.nix @@ -40,7 +40,16 @@ pkgs.rust-bin.nightly.latest.minimal.override { extensions = [ "rustfmt" ]; } ); - src = craneLib.cleanCargoSource ./.; + src = pkgs.lib.cleanSourceWith { + src = ./.; + filter = + path: type: + (craneLib.filterCargoSources path type) + # the script komorebi loads into KWin, which the daemon includes + || (pkgs.lib.hasSuffix ".js" path) + # the messages the tests of the bridge and of the daemon share + || (pkgs.lib.hasSuffix ".json" path); + }; commonArgs = { inherit src; @@ -113,9 +122,12 @@ 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; # a Mac runs the guests under HVF, which is slower than KVM vm = import ./nix/tests/vm { hostPkgs = pkgs; + inherit komorebiFor; scale = if isLinux then 1 else 1.5; }; nightlyRustfmt = pkgs.rust-bin.nightly.latest.rustfmt; @@ -176,6 +188,27 @@ build.individualCrateArgs // { doCheck = true; } ); + # The bridge is not Rust: tsc checks its types from its JSDoc comments, and node runs + # its tests against a fake KWin. No package.json and no build step. + komorebi-bridge-js = + pkgs.runCommand "komorebi-bridge-js" + { + nativeBuildInputs = [ + pkgs.nodejs + pkgs.typescript + ]; + src = lib.fileset.toSource { + root = ./komorebi/src/kwin; + fileset = lib.fileset.fileFilter (file: !file.hasExt "rs") ./komorebi/src/kwin; + }; + } + '' + cd $src + tsc -p tsconfig.json + node --test bridge.test.js + touch $out + ''; + vm-lib = vm.lib; } # The VM tests need QEMU with KVM, so only Linux checks them. A Mac runs the same tests @@ -197,6 +230,7 @@ vmTcg = (import ./nix/tests/vm { hostPkgs = pkgs; + inherit komorebiFor; scale = 8; }).suites; }; @@ -233,6 +267,10 @@ pkgs.just pkgs.ripgrep + # the bridge's type check and tests (`just check-js`) + pkgs.nodejs + pkgs.typescript + # the VM test library pkgs.ruff pkgs.ty diff --git a/justfile b/justfile index 2120a566..5efb510f 100644 --- a/justfile +++ b/justfile @@ -5,12 +5,18 @@ fmt: cargo fmt # everything a change has to pass before it is pushed -check: lint +check: lint check-js cargo fmt --check cargo clippy --workspace --all-targets --locked -- -D warnings cargo test --workspace --locked RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --locked +# the KWin bridge, which is JavaScript: its types, checked by tsc from its JSDoc comments, and its +# tests, which node runs against a fake KWin (no package.json, no build step) +check-js: + cd komorebi/src/kwin && tsc -p tsconfig.json + node --test komorebi/src/kwin/bridge.test.js + # the macros the codebase has agreed not to use lint: test -z "$(rg 'eyre!' --type rust .)" || (echo "eyre! macro not allowed"; false) diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index ff229a13..f2ebecb6 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -10,20 +10,24 @@ version = { path = "../version" } clap = { workspace = true } color-eyre = { workspace = true } +crossbeam-channel = { workspace = true } ctrlc = { version = "3", features = ["termination"] } +dirs = { workspace = true } +lazy_static = { workspace = true } nanoid = "0.4" parking_lot = "0.12" pastey = { workspace = true } schemars = { workspace = true, optional = true } serde = { workspace = true } +serde_json = { workspace = true, features = ["preserve_order"] } 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-subscriber = { workspace = true } - -[dev-dependencies] -serde_json = { workspace = true } +zbus = { version = "5", default-features = false, features = ["tokio"] } [features] default = ["schemars"] +deadlock_detection = ["parking_lot/deadlock_detection"] schemars = ["dep:schemars"] diff --git a/komorebi/src/desktop.rs b/komorebi/src/desktop.rs index e3bd966f..a7af3f01 100644 --- a/komorebi/src/desktop.rs +++ b/komorebi/src/desktop.rs @@ -19,7 +19,8 @@ //! let fake = Arc::new(FakeBackend::with_one_monitor()); //! fake.open_window(1, "foot", "foot", "a terminal"); //! -//! let mut wm = WindowManager::new()?; +//! let (_sender, events) = crossbeam_channel::bounded(1); +//! let mut wm = WindowManager::new(events)?; //! with_backend(fake, || { //! load_monitor_information(&mut wm)?; //! load_workspace_information(&mut wm) @@ -103,7 +104,8 @@ pub fn latest_monitor_information() -> eyre::Result> { /// use komorebi::window_manager::WindowManager; /// /// let fake = Arc::new(FakeBackend::with_one_monitor()); -/// let mut wm = WindowManager::new()?; +/// let (_sender, events) = crossbeam_channel::bounded(1); +/// let mut wm = WindowManager::new(events)?; /// /// with_backend(fake, || { /// load_monitor_information(&mut wm)?; @@ -159,7 +161,8 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { /// fake.open_window(2, "foot", "foot", "a dialog"); /// fake.set_normal(2, false); /// -/// let mut wm = WindowManager::new()?; +/// let (_sender, events) = crossbeam_channel::bounded(1); +/// let mut wm = WindowManager::new(events)?; /// with_backend(fake, || { /// load_monitor_information(&mut wm)?; /// load_workspace_information(&mut wm) diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js new file mode 100644 index 00000000..4d88e548 --- /dev/null +++ b/komorebi/src/kwin/bridge.js @@ -0,0 +1,319 @@ +// @ts-check +// komorebi's KWin bridge. +// +// A dumb adapter: it reports what KWin tells it and does what komorebi asks, and holds no window +// manager logic. The daemon prepends `var CFG = {...};` (the D-Bus names and the poll hold time). +// +// Everything crosses D-Bus as a JSON string. `callDBus` types a JS number as int32 and a mismatch +// with the declared signature is a silent error, and its callback only fires on success, so the +// inbound command loop below is guarded by a watchdog (see the end of the file). +// +// KWin runs this file as it is: there is no build step. `tsc -p tsconfig.json` checks it as strict +// TypeScript through its JSDoc comments, against the part of KWin's API declared in +// kwin-api.d.ts, and `node --test bridge.test.js` runs it against a fake KWin (`just check-js` +// does both). The messages typed below are what `kwin::state` reads and `kwin::KWinBackend` +// sends; the tests of both sides read the same messages from fixtures/. + +// ---- the messages -------------------------------------------------------------------------- + +/** @typedef {{ x: number, y: number }} Point */ +/** @typedef {{ x: number, y: number, w: number, h: number }} Rect */ + +/** + * A window as KWin describes it. `id` is KWin's UUID for the window, `normal` says whether it is + * a window of an application (`isApplicationWindow`), and `desktops` are the ids of its virtual + * desktops. + * + * @typedef {{ + * id: string, pid: number, class: string, name: string, desktopFile: string, caption: string, + * normal: boolean, minimized: boolean, fullscreen: boolean, maximized: boolean, geo: Rect, + * minSize: { w: number, h: number }, desktops: string[] + * }} WindowInfo + */ + +/** + * An output. `area` is the part of it windows may cover (not the panels) on the virtual desktop + * it shows. + * + * @typedef {{ + * name: string, manufacturer: string, model: string, serial: string, geo: Rect, + * scale: number, area: Rect + * }} Screen + */ + +/** + * What the bridge sends, as the one argument of `Event`. `emit` adds `seq` to each, which counts + * them from 1. `snapshot` is everything on the desktop, sent once, when the script starts; an + * `activated` with no `id` means no window has the focus; `cursor` answers a cursor query, and + * `failed` gives back the commands of a batch that could not be carried out. + * + * @typedef {{ + * type: "snapshot", windows: WindowInfo[], screens: Screen[], active: string | null, + * cursor: Point + * }} Snapshot + * @typedef {WindowInfo & { type: "added" }} Added + * @typedef {{ type: "removed", id: string }} Removed + * @typedef {{ type: "activated", id: string | null }} Activated + * @typedef {{ type: "minimized", id: string, v: boolean }} Minimized + * @typedef {{ type: "geometry", id: string, geo: Rect }} Geometry + * @typedef {{ type: "cursor", token: number, x: number, y: number }} CursorAnswer + * @typedef {{ type: "failed", batch: number, cmds: Command[] }} Failed + * @typedef {Snapshot | Added | Removed | Activated | Minimized | Geometry | CursorAnswer | Failed} BridgeEvent + */ + +/** + * What the daemon sends: the answer to `Poll` is a list of batches, each a list of commands. The + * only command is the cursor query, which `token` numbers so that its answer can be matched. + * + * @typedef {{ op: "cursor", token: number }} CursorQuery + * @typedef {CursorQuery} Command + * @typedef {{ batch: number, cmds: Command[] }} Batch + */ + +// ---- reporting ------------------------------------------------------------------------------- + +var SVC = CFG.service, PATH = CFG.path, IFACE = CFG.iface; +var POLL_PATH = CFG.poll_path, POLL_IFACE = CFG.poll_iface; +var seq = 0; +/** @type {Record} */ +var known = {}; + +/** + * @template {BridgeEvent["type"]} T + * @param {T} type + * @param {Omit, "type">} body + */ +function emit(type, body) { + /** @type {Record} */ + var ev = body || {}; + ev.type = type; + ev.seq = ++seq; + callDBus(SVC, PATH, IFACE, "Event", JSON.stringify(ev)); +} + +/** + * @param {QRectF} g + * @returns {Rect} + */ +function rect(g) { + return { x: Math.round(g.x), y: Math.round(g.y), w: Math.round(g.width), h: Math.round(g.height) }; +} + +/** @param {KWinWindow} w */ +function wid(w) { + return String(w.internalId); +} + +/** @param {KWinWindow} w */ +function desktopIds(w) { + var ds = []; + for (var i = 0; i < w.desktops.length; i++) { + ds.push(String(w.desktops[i].id)); + } + return ds; +} + +// A window of an application, as opposed to a dialog, a panel, a popup, or something the compositor +// shows for itself: the lock screen is a normal window by KWin's reckoning, but it is on every +// desktop, in no task list, no pager and no switcher, and belongs to KWin. komorebi tiling it would +// move everything else about while the screen is locked. +/** @param {KWinWindow} w */ +function isApplicationWindow(w) { + if (!w.normalWindow) { + return false; + } + if (w.skipTaskbar && w.skipPager && w.skipSwitcher) { + return false; + } + return String(w.resourceClass) !== "kwin_wayland"; +} + +// maximized both ways (KWin's MaximizeFull); a window maximized in one direction only is not "maximized" +/** @param {KWinWindow} w */ +function isMaximized(w) { + return w.maximizeMode === 3; +} + +/** + * @param {KWinWindow} w + * @returns {WindowInfo} + */ +function describe(w) { + return { + id: wid(w), + pid: w.pid, + class: String(w.resourceClass), + name: String(w.resourceName), + desktopFile: String(w.desktopFileName), + caption: String(w.caption), + normal: isApplicationWindow(w), + minimized: !!w.minimized, + fullscreen: !!w.fullScreen, + maximized: isMaximized(w), + geo: rect(w.frameGeometry), + minSize: { w: Math.round(w.minSize.width), h: Math.round(w.minSize.height) }, + desktops: desktopIds(w) + }; +} + +/** @param {unknown} v */ +function str(v) { + return v === undefined || v === null ? "" : String(v); +} + +/** @returns {Screen[]} */ +function screens() { + var out = []; + for (var i = 0; i < workspace.screens.length; i++) { + var s = workspace.screens[i]; + out.push({ + name: String(s.name), + manufacturer: str(s.manufacturer), + model: str(s.model), + serial: str(s.serialNumber), + geo: rect(s.geometry), + scale: s.devicePixelRatio, + area: rect(workspace.clientArea(KWin.PlacementArea, s, workspace.currentDesktopForScreen(s))) + }); + } + return out; +} + +/** @returns {Point} */ +function cursor() { + var p = workspace.cursorPos; + return { x: Math.round(p.x), y: Math.round(p.y) }; +} + +// ---- hooks --------------------------------------------------------------------------------- + +/** + * @param {KWinWindow} w + * @param {boolean} announce + */ +function track(w, announce) { + var id = wid(w); + if (known[id]) { + return; + } + known[id] = w; + if (announce) { + emit("added", describe(w)); + } + w.frameGeometryChanged.connect(function (old) { + emit("geometry", { id: id, geo: rect(w.frameGeometry) }); + }); + w.minimizedChanged.connect(function () { + emit("minimized", { id: id, v: !!w.minimized }); + }); +} + +workspace.windowAdded.connect(function (w) { + track(w, true); +}); +workspace.windowRemoved.connect(function (w) { + var id = wid(w); + delete known[id]; + emit("removed", { id: id }); +}); +/** @type {string | null} */ +var lastActive = null; + +/** @param {KWinWindow | null} w */ +function announceActive(w) { + // kwin emits windowActivated for a new window *before* windowAdded; keep the invariant that no + // event mentions a window before its `added` + if (w) { + track(w, true); + } + lastActive = w ? wid(w) : null; + emit("activated", { id: lastActive }); +} + +workspace.windowActivated.connect(announceActive); + +var existing = workspace.windowList(); +for (var i = 0; i < existing.length; i++) { + track(existing[i], false); +} + +lastActive = workspace.activeWindow ? wid(workspace.activeWindow) : null; + +emit("snapshot", { + windows: workspace.windowList().map(describe), + screens: screens(), + active: workspace.activeWindow ? wid(workspace.activeWindow) : null, + cursor: cursor() +}); + +// ---- commands from the daemon ---------------------------------------------------------------- + +/** + * @param {Command} c + * @returns {boolean} false if the command could not be carried out + */ +function applyOne(c) { + if (c.op === "cursor") { + // a query: the answer comes back as an event + var p = cursor(); + emit("cursor", { token: c.token, x: p.x, y: p.y }); + return true; + } + return false; +} + +/** @param {Batch} batch */ +function applyBatch(batch) { + var failed = []; + for (var i = 0; i < batch.cmds.length; i++) { + try { + if (!applyOne(batch.cmds[i])) { + failed.push(batch.cmds[i]); + } + } catch (e) { + print("komorebi bridge: " + e + " in " + JSON.stringify(batch.cmds[i])); + failed.push(batch.cmds[i]); + } + } + if (failed.length > 0) { + emit("failed", { batch: batch.batch, cmds: failed }); + } +} + +// The daemon holds a Poll call open and answers it when it has commands, or after `hold_ms` with an +// empty batch. `callDBus` calls the callback only on success, so if the call fails (the daemon is +// gone, or it restarted) nothing would ever re-issue it; the watchdog does. Generations drop the +// reply of a call that has been superseded. +var gen = 0; +var lastIssue = 0; + +function pull() { + var g = ++gen; + lastIssue = Date.now(); + callDBus(SVC, POLL_PATH, POLL_IFACE, "Poll", JSON.stringify({ hold_ms: CFG.hold_ms }), function (reply) { + if (g !== gen) { + return; + } + try { + /** @type {Batch[]} */ + var batches = JSON.parse(reply); + for (var i = 0; i < batches.length; i++) { + applyBatch(batches[i]); + } + } catch (e) { + print("komorebi bridge: bad poll reply: " + e); + } + pull(); + }); +} + +pull(); + +var watchdog = new QTimer(); +watchdog.interval = 1000; +watchdog.timeout.connect(function () { + if (Date.now() - lastIssue > CFG.hold_ms + 3000) { + pull(); + } +}); +watchdog.start(); diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js new file mode 100644 index 00000000..fbec1d93 --- /dev/null +++ b/komorebi/src/kwin/bridge.test.js @@ -0,0 +1,389 @@ +// Tests of bridge.js, run by `node --test` (node's own test runner: no package.json and no +// dependencies). Each test loads the script as the daemon has KWin load it, with `var CFG = {...};` +// in front, into a `node:vm` context of its own whose globals are a fake of the part of KWin's API +// that kwin-api.d.ts declares: a `workspace` whose signals are tiny emitters, windows that are +// plain objects, a `callDBus` that records the script's calls, and a `QTimer` that a test fires. +// The fake does what KWin does as far as the bridge can tell (setting a property raises its +// signal, KWin activates a new window before it announces it); whether KWin really behaves so is +// what the VM tests check. +// +// The first test plays a session and compares what the bridge sends with fixtures/events.json, +// which the tests of `kwin::state` feed to the table; the commands it answers the bridge's `Poll` +// with are fixtures/commands.json, which the tests of `kwin` expect the backend to send. A change +// to what one side sends or reads fails a test on the other side. + +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const test = require("node:test"); +const vm = require("node:vm"); + +const SOURCE = fs.readFileSync(path.join(__dirname, "bridge.js"), "utf8"); + +function fixture(name) { + return JSON.parse(fs.readFileSync(path.join(__dirname, "fixtures", name), "utf8")); +} + +// what `kwin::load_script` prepends +const CFG = { + service: "org.komorebi.Bridge", + path: "/org/komorebi/Bridge", + iface: "org.komorebi.Bridge", + poll_path: "/org/komorebi/Bridge/Poll", + poll_iface: "org.komorebi.Bridge.Poll", + hold_ms: 10000, +}; + +class Signal { + constructor() { + this.slots = []; + } + + connect(slot) { + this.slots.push(slot); + } + + emit(...args) { + for (const slot of this.slots) { + slot(...args); + } + } +} + +function geometry(x, y, width, height) { + return { x, y, width, height }; +} + +// A window. `id` becomes its `internalId`, which is a QUuid in KWin: an object, not a string. +// Setting `minimized` or `frameGeometry` raises the signal KWin raises. +function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100), ...rest }) { + const w = { + internalId: { toString: () => id }, + pid: 0, + resourceClass: "", + resourceName: "", + desktopFileName: "", + caption: "", + normalWindow: true, + skipTaskbar: false, + skipPager: false, + skipSwitcher: false, + fullScreen: false, + maximizeMode: 0, + minSize: { width: 0, height: 0 }, + desktops: [], + frameGeometryChanged: new Signal(), + minimizedChanged: new Signal(), + ...rest, + }; + let state = { minimized, frameGeometry }; + Object.defineProperties(w, { + minimized: { + get: () => state.minimized, + set: (v) => { + state.minimized = v; + w.minimizedChanged.emit(); + }, + }, + frameGeometry: { + get: () => state.frameGeometry, + set: (g) => { + const old = state.frameGeometry; + state.frameGeometry = geometry(g.x, g.y, g.width, g.height); + w.frameGeometryChanged.emit(old); + }, + }, + }); + return w; +} + +// one output, with a panel along its bottom edge +const DP1 = { + name: "DP-1", + manufacturer: "ACME", + model: "M1", + serialNumber: "S1", + geometry: geometry(0, 0, 1920, 1080), + devicePixelRatio: 1, + // not KWin's: what the fake's `clientArea` answers for it + placementArea: geometry(0, 0, 1920, 1050), +}; + +// A KWin with `windows` open, `active` focused and the pointer at `cursor`, running the bridge. +function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y: 0 } } = {}) { + const calls = []; + const printed = []; + const timers = []; + const clock = { now: 1000 }; + const open = windows.slice(); + let activeWindow = active; + + const workspace = { + screens, + cursorPos: cursor, + windowList: () => open.slice(), + clientArea: (option, output, desktop) => { + assert.equal(option, 7, "the placement area"); + assert.equal(desktop.id, `desktop of ${output.name}`); + return output.placementArea; + }, + currentDesktopForScreen: (output) => ({ id: `desktop of ${output.name}` }), + windowAdded: new Signal(), + windowRemoved: new Signal(), + windowActivated: new Signal(), + }; + Object.defineProperty(workspace, "activeWindow", { + get: () => activeWindow, + set: (w) => { + activeWindow = w; + workspace.windowActivated.emit(w); + }, + }); + + class QTimer { + constructor() { + this.interval = 0; + this.timeout = new Signal(); + this.running = false; + timers.push(this); + } + + start() { + this.running = true; + } + } + + const context = vm.createContext({ + workspace, + KWin: { PlacementArea: 7 }, + callDBus: (service, path, iface, method, arg, callback) => { + calls.push({ service, path, iface, method, arg, callback }); + }, + print: (...values) => printed.push(values.join(" ")), + QTimer, + Date: { now: () => clock.now }, + }); + vm.runInContext(`var CFG = ${JSON.stringify(CFG)};\n${SOURCE}`, context, { + filename: "bridge.js", + }); + + const k = { + workspace, + calls, + printed, + timers, + clock, + // what the bridge has sent with `Event`, oldest first + events: () => calls.filter((c) => c.method === "Event").map((c) => JSON.parse(c.arg)), + polls: () => calls.filter((c) => c.method === "Poll"), + // the daemon answers the bridge's last `Poll` with `text` + reply: (text) => calls.filter((c) => c.method === "Poll").at(-1).callback(text), + // a window opens: KWin activates it before it announces it, unless it is not to be focused + open: (w, { focus = true } = {}) => { + open.push(w); + if (focus) { + workspace.activeWindow = w; + } + workspace.windowAdded.emit(w); + }, + close: (w) => { + open.splice(open.indexOf(w), 1); + if (activeWindow === w) { + activeWindow = null; + } + workspace.windowRemoved.emit(w); + }, + // the daemon answers the bridge's last `Poll` with these batches + answer: (batches) => k.reply(JSON.stringify(batches)), + }; + return k; +} + +test("what the bridge sends for a session is what the daemon's tests read", () => { + const [events, commands] = [fixture("events.json"), fixture("commands.json")]; + const editor = window({ + id: "{0e5a1c3b-0000-4000-8000-00000000000a}", + pid: 4242, + resourceClass: "org.kde.kate", + resourceName: "kate", + desktopFileName: "org.kde.kate", + caption: "notes.txt — Kate", + frameGeometry: geometry(0, 0, 1920, 1050), + minSize: { width: 300, height: 200 }, + desktops: [{ id: "desktop-1" }], + }); + const k = kwin({ windows: [editor], active: editor, cursor: { x: 480.6, y: 525.2 } }); + + const terminal = window({ + id: "{7f3d9e21-0000-4000-8000-00000000000b}", + pid: 4343, + resourceClass: "foot", + resourceName: "foot", + desktopFileName: "foot", + caption: "a terminal", + frameGeometry: geometry(480, 270, 960, 540), + minSize: { width: 21, height: 34.5 }, + desktops: [{ id: "desktop-1" }], + }); + k.open(terminal); + const dialog = window({ + id: "{c4b8a2f0-0000-4000-8000-00000000000c}", + pid: 4242, + resourceClass: "org.kde.kate", + resourceName: "kate", + desktopFileName: "org.kde.kate", + caption: "Save As — Kate", + normalWindow: false, + frameGeometry: geometry(660, 290, 600, 500), + desktops: [{ id: "desktop-1" }], + }); + k.open(dialog, { focus: false }); + terminal.minimized = true; + terminal.minimized = false; + // the client took the frame it was given to whole cells of its font + terminal.frameGeometry = geometry(480.4, 270, 956, 532); + + const [cursorQuery] = commands; + assert.equal(k.events().at(-1).seq, cursorQuery.after_seq); + k.workspace.cursorPos = { x: 1200, y: 700.5 }; + k.answer([cursorQuery.batch]); + + k.close(terminal); + + assert.deepStrictEqual(k.events(), events); +}); + +test("a window KWin activates before announcing it is announced first, and once", () => { + const k = kwin(); + const w = window({ id: "{w}" }); + + k.open(w); + + assert.deepStrictEqual( + k.events().map((e) => [e.type, e.id]), + [ + ["snapshot", undefined], + ["added", "{w}"], + ["activated", "{w}"], + ], + ); +}); + +test("no window having the focus is an activation with no id", () => { + const w = window({ id: "{w}" }); + const k = kwin({ windows: [w], active: w }); + + k.workspace.activeWindow = null; + + assert.deepStrictEqual(k.events().at(-1), { type: "activated", id: null, seq: 2 }); +}); + +test("dialogs, the lock screen and windows nobody can switch to are not application windows", () => { + const windows = [ + window({ id: "{app}" }), + window({ id: "{dialog}", normalWindow: false }), + window({ id: "{lock}", resourceClass: "kwin_wayland" }), + window({ id: "{hidden}", skipTaskbar: true, skipPager: true, skipSwitcher: true }), + window({ id: "{no-taskbar}", skipTaskbar: true }), + ]; + const k = kwin({ windows }); + + const [snapshot] = k.events(); + + assert.deepStrictEqual( + snapshot.windows.map((w) => [w.id, w.normal]), + [ + ["{app}", true], + ["{dialog}", false], + ["{lock}", false], + ["{hidden}", false], + ["{no-taskbar}", true], + ], + ); +}); + +test("a window maximized one way only is not maximized", () => { + const windows = [0, 1, 2, 3].map((mode) => window({ id: `{${mode}}`, maximizeMode: mode })); + const k = kwin({ windows }); + + const [snapshot] = k.events(); + + assert.deepStrictEqual( + snapshot.windows.map((w) => w.maximized), + [false, false, false, true], + ); +}); + +test("every call goes to the daemon's names, with one JSON string", () => { + const k = kwin(); + k.answer([]); + + assert.deepStrictEqual( + k.calls.map((c) => [c.service, c.path, c.iface, c.method, typeof c.arg]), + [ + [CFG.service, CFG.path, CFG.iface, "Event", "string"], + [CFG.service, CFG.poll_path, CFG.poll_iface, "Poll", "string"], + [CFG.service, CFG.poll_path, CFG.poll_iface, "Poll", "string"], + ], + ); + assert.deepStrictEqual(JSON.parse(k.polls()[0].arg), { hold_ms: CFG.hold_ms }); +}); + +test("the bridge always has a Poll open: one when it starts, and another after each answer", () => { + const k = kwin(); + assert.equal(k.polls().length, 1); + + k.answer([]); + k.answer([{ batch: 1, cmds: [{ op: "cursor", token: 1 }] }]); + + assert.equal(k.polls().length, 3); +}); + +test("the watchdog calls Poll again when the last call is older than the hold and 3 seconds", () => { + const k = kwin(); + const [watchdog] = k.timers; + assert.equal(watchdog.interval, 1000); + assert.ok(watchdog.running); + + k.clock.now += CFG.hold_ms + 3000; + watchdog.timeout.emit(); + assert.equal(k.polls().length, 1, "not older yet"); + + k.clock.now += 1; + watchdog.timeout.emit(); + assert.equal(k.polls().length, 2); +}); + +test("the answer to a Poll that the watchdog replaced is dropped", () => { + const k = kwin(); + const [stale] = k.polls(); + k.clock.now += CFG.hold_ms + 3001; + k.timers[0].timeout.emit(); + + stale.callback(JSON.stringify([{ batch: 1, cmds: [{ op: "cursor", token: 1 }] }])); + + assert.equal(k.events().length, 1, "only the snapshot"); + assert.equal(k.polls().length, 2, "and no third Poll"); +}); + +test("an answer that is not JSON is printed, and the bridge polls again", () => { + const k = kwin(); + + k.reply("not json"); + + assert.match(k.printed[0], /^komorebi bridge: bad poll reply: SyntaxError/); + assert.equal(k.polls().length, 2); +}); + +test("a command the bridge does not know is given back as failed", () => { + const k = kwin(); + + k.answer([{ batch: 4, cmds: [{ op: "cursor", token: 9 }, { op: "teleport" }] }]); + + assert.deepStrictEqual(k.events().slice(1), [ + { type: "cursor", token: 9, x: 0, y: 0, seq: 2 }, + { type: "failed", batch: 4, cmds: [{ op: "teleport" }], seq: 3 }, + ]); +}); diff --git a/komorebi/src/kwin/fixtures/commands.json b/komorebi/src/kwin/fixtures/commands.json new file mode 100644 index 00000000..b32c21cd --- /dev/null +++ b/komorebi/src/kwin/fixtures/commands.json @@ -0,0 +1,3 @@ +[ + {"after_seq": 7, "batch": {"batch": 1, "cmds": [{"op": "cursor", "token": 1}]}} +] diff --git a/komorebi/src/kwin/fixtures/events.json b/komorebi/src/kwin/fixtures/events.json new file mode 100644 index 00000000..411c0b76 --- /dev/null +++ b/komorebi/src/kwin/fixtures/events.json @@ -0,0 +1,46 @@ +[ + { + "type": "snapshot", "seq": 1, + "windows": [ + { + "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "pid": 4242, + "class": "org.kde.kate", "name": "kate", "desktopFile": "org.kde.kate", + "caption": "notes.txt — Kate", "normal": true, "minimized": false, + "fullscreen": false, "maximized": false, + "geo": {"x": 0, "y": 0, "w": 1920, "h": 1050}, "minSize": {"w": 300, "h": 200}, + "desktops": ["desktop-1"] + } + ], + "screens": [ + { + "name": "DP-1", "manufacturer": "ACME", "model": "M1", "serial": "S1", + "geo": {"x": 0, "y": 0, "w": 1920, "h": 1080}, "scale": 1, + "area": {"x": 0, "y": 0, "w": 1920, "h": 1050} + } + ], + "active": "{0e5a1c3b-0000-4000-8000-00000000000a}", "cursor": {"x": 481, "y": 525} + }, + { + "type": "added", "seq": 2, "id": "{7f3d9e21-0000-4000-8000-00000000000b}", "pid": 4343, + "class": "foot", "name": "foot", "desktopFile": "foot", "caption": "a terminal", + "normal": true, "minimized": false, "fullscreen": false, "maximized": false, + "geo": {"x": 480, "y": 270, "w": 960, "h": 540}, "minSize": {"w": 21, "h": 35}, + "desktops": ["desktop-1"] + }, + {"type": "activated", "seq": 3, "id": "{7f3d9e21-0000-4000-8000-00000000000b}"}, + { + "type": "added", "seq": 4, "id": "{c4b8a2f0-0000-4000-8000-00000000000c}", "pid": 4242, + "class": "org.kde.kate", "name": "kate", "desktopFile": "org.kde.kate", + "caption": "Save As — Kate", "normal": false, "minimized": false, "fullscreen": false, + "maximized": false, "geo": {"x": 660, "y": 290, "w": 600, "h": 500}, + "minSize": {"w": 0, "h": 0}, "desktops": ["desktop-1"] + }, + {"type": "minimized", "seq": 5, "id": "{7f3d9e21-0000-4000-8000-00000000000b}", "v": true}, + {"type": "minimized", "seq": 6, "id": "{7f3d9e21-0000-4000-8000-00000000000b}", "v": false}, + { + "type": "geometry", "seq": 7, "id": "{7f3d9e21-0000-4000-8000-00000000000b}", + "geo": {"x": 480, "y": 270, "w": 956, "h": 532} + }, + {"type": "cursor", "seq": 8, "token": 1, "x": 1200, "y": 701}, + {"type": "removed", "seq": 9, "id": "{7f3d9e21-0000-4000-8000-00000000000b}"} +] diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts new file mode 100644 index 00000000..d177a4c6 --- /dev/null +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -0,0 +1,125 @@ +// The part of KWin's scripting API that bridge.js uses, declared for `tsc` (tsconfig.json). KWin +// publishes no declarations; these are written from its scripting documentation +// (https://develop.kde.org/docs/plasma/kwin/api/) and from what a script is given in KWin 6.8. +// Something the bridge starts to use is declared here first. +// +// They are narrower than KWin's API on purpose: a property the bridge has no business setting is +// read-only, and `callDBus` takes one string argument, because a JavaScript number goes over D-Bus +// as a 32-bit integer and a call that does not match the method's signature fails without a word. + +/** What the daemon prepends to the script (`kwin::load_script`): its D-Bus names and how long it + * holds a `Poll` call. */ +declare const CFG: { + readonly service: string; + readonly path: string; + readonly iface: string; + readonly poll_path: string; + readonly poll_iface: string; + readonly hold_ms: number; +}; + +/** A Qt signal. A script connects a function to it, which is called with the signal's arguments. */ +interface Signal { + connect(slot: (...args: Args) => void): void; +} + +interface QPointF { + readonly x: number; + readonly y: number; +} + +interface QSizeF { + readonly width: number; + readonly height: number; +} + +interface QRectF { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +/** A `QUuid`, which is not a string: `String()` gives its text, `{...}` with the braces. */ +interface QUuid { + readonly __quuid: never; +} + +interface VirtualDesktop { + readonly id: string; +} + +/** An output (`KWin::Output`). */ +interface Output { + readonly name: string; + readonly manufacturer: string; + readonly model: string; + readonly serialNumber: string; + readonly geometry: QRectF; + readonly devicePixelRatio: number; +} + +/** A window (`KWin::Window`). */ +interface KWinWindow { + readonly internalId: QUuid; + readonly pid: number; + readonly resourceClass: string; + readonly resourceName: string; + readonly desktopFileName: string; + readonly caption: string; + readonly normalWindow: boolean; + readonly skipTaskbar: boolean; + readonly skipPager: boolean; + readonly skipSwitcher: boolean; + readonly minimized: boolean; + readonly fullScreen: boolean; + /** `KWin::MaximizeMode`: 0 restored, 1 vertically, 2 horizontally, 3 both ways. */ + readonly maximizeMode: number; + readonly frameGeometry: QRectF; + readonly minSize: QSizeF; + readonly desktops: VirtualDesktop[]; + readonly frameGeometryChanged: Signal<[oldGeometry: QRectF]>; + readonly minimizedChanged: Signal; +} + +/** The global `workspace` (`KWin::ScriptingWorkspace`). */ +interface Workspace { + readonly screens: Output[]; + readonly activeWindow: KWinWindow | null; + readonly cursorPos: QPointF; + windowList(): KWinWindow[]; + clientArea(option: number, output: Output, desktop: VirtualDesktop): QRectF; + currentDesktopForScreen(output: Output): VirtualDesktop; + readonly windowAdded: Signal<[window: KWinWindow]>; + readonly windowRemoved: Signal<[window: KWinWindow]>; + /** `null` when no window has the focus. */ + readonly windowActivated: Signal<[window: KWinWindow | null]>; +} + +declare const workspace: Workspace; + +/** KWin's enums. */ +declare const KWin: { + /** The `KWin::ClientAreaOption` of the area windows are placed in. */ + readonly PlacementArea: number; +}; + +/** Calls a D-Bus method. `callback` is called with the reply when the call succeeds, and not at + * all when it fails. */ +declare function callDBus( + service: string, + path: string, + iface: string, + method: string, + arg: string, + callback?: (reply: string) => void, +): void; + +/** Writes to KWin's log, under the `kwin_scripting` category. */ +declare function print(...values: unknown[]): void; + +declare class QTimer { + interval: number; + readonly timeout: Signal; + start(): void; +} diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs new file mode 100644 index 00000000..9a26b732 --- /dev/null +++ b/komorebi/src/kwin/mod.rs @@ -0,0 +1,549 @@ +//! The KWin backend: [`KWinBackend`], made by [`connect`]. +//! +//! KWin has no protocol that lets another process read and set window geometry, so komorebi runs a +//! small script inside KWin (`bridge.js`) and talks to it over D-Bus: +//! +//! ```text +//! komorebi (this process) KWin +//! ----------------------- ---- +//! owns org.komorebi.Bridge <--- Event(json) ------- script reports what it sees +//! (window added, focus, minimize, ...) +//! answers Poll(json) late ---- batch of commands -> script carries them out +//! ``` +//! +//! Events are delivered in order on an interface that handles calls inline; commands go out as the +//! answer to a `Poll` call the script makes on a separate object, and that the daemon holds open +//! until it has something to send, so waiting for work never blocks an event. +//! +//! All of the decisions about what an event means are made in [`state`], which is pure and tested +//! without a compositor. This module is the plumbing around it: the D-Bus service, the held call, +//! and loading the script into KWin. +//! +//! The script is type-checked by `tsc` from its JSDoc comments and tested with `node --test` +//! against a fake KWin (`just check-js`). Its tests and the tests of this module and of [`state`] +//! read the same messages, in `fixtures/`, so that what one side sends is what the other reads. +//! +//! The backend reads the desktop: it answers every query from the [`state::Table`], and turns +//! what KWin reports into the window events of [`crate::window_manager_event`]. It does not change +//! the desktop: every command of [`Backend`] is an error. +//! +//! `docs/dev/PLATFORM.md` has the D-Bus names, the files and the environment variables involved, +//! and `docs/dev/DESIGN.md` the reasons for this design. + +#![deny(missing_docs)] + +pub mod state; + +use crate::DATA_DIR; +use crate::backend::Backend; +use crate::backend::MonitorInfo; +use crate::backend::WindowInfo; +use crate::core::Rect; +use crate::window_manager_event_listener; +use color_eyre::eyre; +use color_eyre::eyre::OptionExt; +use parking_lot::Condvar; +use parking_lot::Mutex; +use serde_json::Value; +use serde_json::json; +use state::Output; +use state::Table; +use std::collections::HashMap; +use std::collections::VecDeque; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; +use std::time::Duration; +use std::time::Instant; +use tokio::runtime::Handle; +use tokio::sync::Notify; +use zbus::Connection; +use zbus::interface; +use zbus::proxy::Proxy; + +const SERVICE: &str = "org.komorebi.Bridge"; +const PATH: &str = "/org/komorebi/Bridge"; +const POLL_PATH: &str = "/org/komorebi/Bridge/Poll"; +const IFACE: &str = "org.komorebi.Bridge"; +const POLL_IFACE: &str = "org.komorebi.Bridge.Poll"; +const SCRIPT_NAME: &str = "komorebi-bridge"; +const BRIDGE_JS: &str = include_str!("bridge.js"); + +/// How long a `Poll` is held open when there is nothing to send. Below QtDBus's 25 second call +/// timeout, which would otherwise fail the call. +const HOLD_MS: u64 = 10_000; + +/// Commands that arrive within this long of each other go out as one batch +const COALESCE: Duration = Duration::from_millis(1); + +/// The state the D-Bus objects, the backend and the thread that runs the connection share +struct Shared { + table: Mutex, + /// commands for the script, oldest first + queue: Mutex>, + wake: Notify, + batch: AtomicU64, + /// set once the script has reported its first snapshot + ready: (Mutex, Condvar), + cursor_waiters: Mutex>>, + next_token: AtomicU64, + handle: Handle, + /// false once the thread that runs the runtime has ended: the runtime is then being shut down, + /// and blocking on it panics + alive: AtomicBool, + connection: Mutex>, +} + +impl Shared { + /// Run something on the runtime and wait for it, unless the runtime is gone: once its thread + /// has ended, tokio panics rather than run it + fn block_on(&self, future: F) -> eyre::Result { + if !self.alive.load(Ordering::SeqCst) { + eyre::bail!("KWin is gone"); + } + Ok(self.handle.block_on(future)) + } + + fn push(&self, command: Value) { + self.queue.lock().push_back(command); + self.wake.notify_one(); + } + + /// Route what the table decided to where it goes + fn dispatch(&self, outputs: Vec) { + for output in outputs { + match output { + Output::Event(event) => window_manager_event_listener::send_notification(event), + Output::Cursor { token, x, y } => { + if let Some(waiter) = self.cursor_waiters.lock().remove(&token) { + let _ = waiter.send((x, y)); + } + } + } + } + } + + fn mark_ready(&self) { + *self.ready.0.lock() = true; + self.ready.1.notify_all(); + } + + async fn connection(&self) -> eyre::Result { + self.connection + .lock() + .clone() + .ok_or_eyre("not connected to the session bus") + } +} + +/// script -> daemon. `spawn = false` makes zbus handle these inline and in the order received (the +/// default, a task per call, was seen to reorder events); the price is that a handler that waits +/// blocks every later call on the connection, so these never wait. +struct Events { + shared: Arc, +} + +#[interface(name = "org.komorebi.Bridge", spawn = false)] +impl Events { + async fn event(&self, json: String) { + let value: Value = match serde_json::from_str(&json) { + Ok(value) => value, + Err(error) => { + tracing::error!("bad event from the bridge ({error}): {json}"); + return; + } + }; + + let is_snapshot = value["type"] == "snapshot"; + let outputs = self.shared.table.lock().handle(&value, Instant::now()); + self.shared.dispatch(outputs); + + if is_snapshot { + self.shared.mark_ready(); + } + } +} + +/// daemon -> script, on its own object so that the held call is spawned and cannot block `Events` +struct Poll { + shared: Arc, +} + +#[interface(name = "org.komorebi.Bridge.Poll")] +impl Poll { + /// `args` is JSON `{"hold_ms": n}`. Returns a JSON array of command batches: as soon as there + /// are commands, or empty once `hold_ms` has passed. + async fn poll(&self, args: String) -> String { + let hold_ms = serde_json::from_str::(&args) + .ok() + .and_then(|v| v["hold_ms"].as_u64()) + .unwrap_or(HOLD_MS); + + let deadline = tokio::time::Instant::now() + Duration::from_millis(hold_ms); + + loop { + if !self.shared.queue.lock().is_empty() { + // let a burst finish arriving, so that a retile is one batch and not twenty + tokio::time::sleep(COALESCE).await; + let cmds: Vec = self.shared.queue.lock().drain(..).collect(); + let batch = self.shared.batch.fetch_add(1, Ordering::Relaxed) + 1; + return json!([{ "batch": batch, "cmds": cmds }]).to_string(); + } + + if tokio::time::timeout_at(deadline, self.shared.wake.notified()) + .await + .is_err() + { + return "[]".to_string(); + } + } + } +} + +/// The desktop of a running KWin, read through the script komorebi loads into it. +/// +/// The queries are answered from a [`state::Table`] that the script's events keep up to date, so +/// they do not wait for KWin, except [`Backend::cursor_pos`]: only the script can read the pointer, +/// so it is asked, and given 250 ms to answer. +/// +/// The backend only reads the desktop. Every command ([`Backend::set_rect`], +/// [`Backend::focus`] and the rest) returns an error and changes nothing. +/// +/// It is made by [`connect`]. +pub struct KWinBackend { + shared: Arc, +} + +/// Connects to the session bus, loads the script into KWin, and waits for it to report what is on +/// the desktop. Returns once that first report has arrived, so that the window manager can read +/// the desktop straight away. +/// +/// The connection is served by a thread of its own (`kwin-bridge-main`), which runs until the +/// daemon exits. +/// +/// # Errors +/// +/// - The session bus cannot be reached (`DBUS_SESSION_BUS_ADDRESS` is not set, or names a bus +/// that is not there), or `org.komorebi.Bridge` is already owned on it: another komorebi is +/// running in the session. +/// - KWin is not on the session bus, or refuses the script. +/// - The script was loaded but did not report the desktop within 10 seconds. KWin logs a script's +/// errors to the journal (`journalctl --user -t kwin_wayland`). +/// - The script cannot be written to [`struct@DATA_DIR`]. +/// +/// # Example +/// +/// This is how the daemon installs the backend. The VM test `vm-kwin-events` +/// (`nix/tests/vm/suites/kwin-events`) starts the daemon against a real KWin; the example needs +/// one, so it is only compiled here. +/// +/// ```rust,no_run +/// use komorebi::backend; +/// use komorebi::kwin; +/// +/// let kwin_backend = kwin::connect()?; +/// backend::set_backend(kwin_backend); +/// # Ok::<(), color_eyre::eyre::Report>(()) +/// ``` +pub fn connect() -> eyre::Result> { + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_name("kwin-bridge") + .enable_all() + .build()?; + + let shared = Arc::new(Shared { + table: Mutex::new(Table::new()), + queue: Mutex::new(VecDeque::new()), + wake: Notify::new(), + batch: AtomicU64::new(0), + ready: (Mutex::new(false), Condvar::new()), + cursor_waiters: Mutex::new(HashMap::new()), + next_token: AtomicU64::new(1), + handle: runtime.handle().clone(), + alive: AtomicBool::new(true), + connection: Mutex::new(None), + }); + + let (started_tx, started_rx) = std::sync::mpsc::channel::>(); + let thread_shared = shared.clone(); + + std::thread::Builder::new() + .name("kwin-bridge-main".into()) + .spawn(move || { + let alive = thread_shared.clone(); + runtime.block_on(async move { + match start(thread_shared.clone()).await { + Ok(()) => { + let _ = started_tx.send(Ok(())); + // the connection is served by this runtime for as long as the daemon runs + std::future::pending::<()>().await; + } + Err(error) => { + let _ = started_tx.send(Err(error)); + } + } + }); + // the runtime goes when this thread does + alive.alive.store(false, Ordering::SeqCst); + })?; + + started_rx + .recv() + .map_err(|_| eyre::Report::msg("the bridge thread exited before starting"))??; + + // the script reports the desktop as soon as it runs + { + let (lock, condvar) = &shared.ready; + let mut ready = lock.lock(); + if !*ready { + condvar.wait_for(&mut ready, Duration::from_secs(10)); + } + if !*ready { + eyre::bail!( + "KWin loaded the bridge script but it never reported in; \ + check `journalctl --user -t kwin_wayland` for script errors" + ); + } + } + + Ok(Arc::new(KWinBackend { shared })) +} + +async fn start(shared: Arc) -> eyre::Result<()> { + let connection = zbus::connection::Builder::session()? + .name(SERVICE)? + .serve_at( + PATH, + Events { + shared: shared.clone(), + }, + )? + .serve_at( + POLL_PATH, + Poll { + shared: shared.clone(), + }, + )? + .build() + .await + .map_err(|error| { + eyre::Report::msg(format!( + "could not connect to the session bus as {SERVICE} \ + (is another komorebi running, and is DBUS_SESSION_BUS_ADDRESS set?): {error}" + )) + })?; + + *shared.connection.lock() = Some(connection.clone()); + load_script(&connection).await +} + +/// Write the bridge to disk, where KWin can read it, and have KWin run it +async fn load_script(connection: &Connection) -> eyre::Result<()> { + let cfg = json!({ + "service": SERVICE, + "path": PATH, + "iface": IFACE, + "poll_path": POLL_PATH, + "poll_iface": POLL_IFACE, + "hold_ms": HOLD_MS, + }); + + std::fs::create_dir_all(&*DATA_DIR)?; + let path = DATA_DIR.join("bridge.js"); + std::fs::write(&path, format!("var CFG = {cfg};\n{BRIDGE_JS}"))?; + + let scripting = Proxy::new( + connection, + "org.kde.KWin", + "/Scripting", + "org.kde.kwin.Scripting", + ) + .await + .map_err(|e| eyre::Report::msg(format!("KWin is not on the session bus: {e}")))?; + + // a script from an earlier run (komorebi crashed, or was restarted) is replaced + let _: bool = scripting.call("unloadScript", &(SCRIPT_NAME,)).await?; + + let path = path.to_string_lossy().to_string(); + let id: i32 = scripting + .call("loadScript", &(path.as_str(), SCRIPT_NAME)) + .await?; + + let script = Proxy::new( + connection, + "org.kde.KWin", + format!("/Scripting/Script{id}"), + "org.kde.kwin.Script", + ) + .await?; + script.call_method("run", &()).await?; + + tracing::info!("loaded the KWin bridge script (script id {id})"); + Ok(()) +} + +/// The error of every command: the backend reads the desktop and changes nothing +fn read_only() -> eyre::Result { + eyre::bail!("the KWin backend only reads the desktop") +} + +impl Backend for KWinBackend { + fn windows(&self) -> Vec { + self.shared.table.lock().windows() + } + + fn window(&self, id: u32) -> Option { + self.shared.table.lock().window(id) + } + + fn foreground_window(&self) -> Option { + self.shared.table.lock().foreground() + } + + fn monitors(&self) -> eyre::Result> { + let monitors = self.shared.table.lock().monitors(); + if monitors.is_empty() { + eyre::bail!("KWin reported no outputs"); + } + Ok(monitors) + } + + fn cursor_pos(&self) -> Option<(i32, i32)> { + // The script is the only thing that can read the pointer, so ask it, and fall back to where + // it was last seen if it does not answer in time + let token = self.shared.next_token.fetch_add(1, Ordering::Relaxed); + let (sender, receiver) = std::sync::mpsc::channel(); + self.shared.cursor_waiters.lock().insert(token, sender); + self.shared.push(json!({ "op": "cursor", "token": token })); + + let answer = receiver.recv_timeout(Duration::from_millis(250)).ok(); + self.shared.cursor_waiters.lock().remove(&token); + + answer.or_else(|| self.shared.table.lock().cursor()) + } + + fn set_rect(&self, _id: u32, _rect: &Rect) -> eyre::Result<()> { + read_only() + } + + fn focus(&self, _id: u32, _mouse_follows_focus: bool) -> eyre::Result<()> { + read_only() + } + + fn raise(&self, _id: u32) -> eyre::Result<()> { + read_only() + } + + fn minimize(&self, _id: u32) -> eyre::Result<()> { + read_only() + } + + fn unminimize(&self, _id: u32) -> eyre::Result<()> { + read_only() + } + + fn close(&self, _id: u32) -> eyre::Result<()> { + read_only() + } + + fn center_cursor_in(&self, _rect: &Rect) -> eyre::Result<()> { + read_only() + } + + fn shutdown(&self) { + // the script goes with komorebi: KWin would otherwise keep running it, reporting to nobody + let shared = self.shared.clone(); + + let _ = self.shared.block_on(async move { + if let Ok(connection) = shared.connection().await + && let Ok(scripting) = Proxy::new( + &connection, + "org.kde.KWin", + "/Scripting", + "org.kde.kwin.Scripting", + ) + .await + { + let _: Result = scripting.call("unloadScript", &(SCRIPT_NAME,)).await; + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A backend connected to nothing: the table, the queue and the `Poll` object, on a runtime of + /// the test's own + fn offline() -> (tokio::runtime::Runtime, KWinBackend) { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + + let shared = Arc::new(Shared { + table: Mutex::new(Table::new()), + queue: Mutex::new(VecDeque::new()), + wake: Notify::new(), + batch: AtomicU64::new(0), + ready: (Mutex::new(false), Condvar::new()), + cursor_waiters: Mutex::new(HashMap::new()), + next_token: AtomicU64::new(1), + handle: runtime.handle().clone(), + alive: AtomicBool::new(true), + connection: Mutex::new(None), + }); + + (runtime, KWinBackend { shared }) + } + + /// The answer the bridge's next `Poll` gets + fn next_poll(runtime: &tokio::runtime::Runtime, backend: &KWinBackend) -> Value { + let poll = Poll { + shared: backend.shared.clone(), + }; + let reply = runtime.block_on(poll.poll(json!({ "hold_ms": 0 }).to_string())); + serde_json::from_str(&reply).unwrap() + } + + /// The commands of a session as the backend sends them: `bridge.test.js` answers the bridge's + /// `Poll` with each batch once the bridge has sent the events up to its `after_seq` + #[test] + fn the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it() { + let (runtime, backend) = offline(); + let events: Vec = + serde_json::from_str(include_str!("fixtures/events.json")).unwrap(); + let commands: Vec = + serde_json::from_str(include_str!("fixtures/commands.json")).unwrap(); + + // what the window manager asks of the backend, batch by batch + let asks: [fn(&KWinBackend); 1] = [|backend| { + // nothing answers the query here, so the pointer is where the snapshot had it + assert_eq!(backend.cursor_pos(), Some((481, 525))); + }]; + assert_eq!(asks.len(), commands.len()); + + let mut handled = 0; + for (command, ask) in commands.iter().zip(asks) { + // the table, as the events the bridge had sent by then left it + let after = command["after_seq"].as_u64().unwrap() as usize; + for event in &events[handled..after] { + backend.shared.table.lock().handle(event, Instant::now()); + } + handled = after; + + ask(&backend); + assert_eq!(next_poll(&runtime, &backend), json!([command["batch"]])); + } + } + + #[test] + fn a_poll_with_nothing_to_send_is_answered_with_nothing_once_its_hold_is_over() { + let (runtime, backend) = offline(); + + assert_eq!(next_poll(&runtime, &backend), json!([])); + } +} diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs new file mode 100644 index 00000000..4c40b559 --- /dev/null +++ b/komorebi/src/kwin/state.rs @@ -0,0 +1,833 @@ +//! The daemon's model of the compositor: the windows and monitors KWin reports, kept up to date by +//! the events the script in KWin sends, and the window events the window manager gets from them. +//! +//! This is pure: JSON in, [`Output`]s out, no D-Bus and no threads, so everything the bridge +//! decides can be tested without a compositor. The script (`bridge.js`) holds no logic: it reports +//! what KWin tells it, and every decision about what a report means is made here. The events are +//! JSON objects with a `type`, described on [`Table::handle`]. +//! +//! # Example +//! +//! The script's first report is a snapshot of the desktop. A window that opens after it is an +//! `added` event, which the window manager gets as a [`WindowManagerEvent::Show`]: +//! +//! ```rust +//! use std::time::Instant; +//! +//! use komorebi::kwin::state::{Output, Table}; +//! use komorebi::window_manager_event::WindowManagerEvent; +//! use serde_json::json; +//! +//! let mut table = Table::new(); +//! let now = Instant::now(); +//! +//! table.handle( +//! &json!({ +//! "type": "snapshot", +//! "windows": [], +//! "screens": [{ +//! "name": "DP-1", "manufacturer": "ACME", "model": "M1", "serial": "S1", +//! "geo": { "x": 0, "y": 0, "w": 1920, "h": 1080 }, +//! "area": { "x": 0, "y": 0, "w": 1920, "h": 1050 }, +//! }], +//! "active": null, +//! "cursor": { "x": 960, "y": 540 }, +//! }), +//! now, +//! ); +//! +//! let out = table.handle( +//! &json!({ +//! "type": "added", "id": "{6b9c}", "pid": 0, "class": "foot", +//! "caption": "a terminal", "normal": true, "minimized": false, +//! "geo": { "x": 0, "y": 0, "w": 800, "h": 600 }, +//! }), +//! now, +//! ); +//! +//! // KWin names the window by a UUID; komorebi gives it a number of its own +//! assert!(matches!(&out[..], [Output::Event(WindowManagerEvent::Show(_, window))] if window.id == 1)); +//! assert_eq!(table.windows()[0].title, "a terminal"); +//! assert_eq!(table.monitors()[0].work_area.bottom, 1050); +//! ``` + +use crate::backend::MonitorInfo; +use crate::backend::WindowInfo; +use crate::core::Rect; +use crate::window::Window; +use crate::window_manager_event::KWinNotification; +use crate::window_manager_event::SystemNotification; +use crate::window_manager_event::WindowManagerEvent; +use serde_json::Value; +use std::collections::HashMap; +use std::time::Duration; +use std::time::Instant; + +/// How long a closed window can still be asked about, so that the `Destroy` event that names it +/// can be logged and serialized +const TOMBSTONE: Duration = Duration::from_secs(60); + +struct Entry { + uuid: String, + info: WindowInfo, + /// What KWin says: a normal window, as opposed to a dialog, splash, panel, popup... + kwin_normal: bool, + closed_at: Option, +} + +/// The work a handled event leaves for the rest of the daemon. +#[derive(Debug)] +pub enum Output { + /// A window event for the window manager. + Event(WindowManagerEvent), + /// The answer to a cursor query. + Cursor { + /// The query this answers, as the daemon numbered it. + token: u64, + /// Where the pointer is, across. + x: i32, + /// Where the pointer is, down. + y: i32, + }, +} + +/// The windows and monitors of the desktop, as the script last reported them. +/// +/// A window is known by the UUID KWin gives it, and the table gives it a `u32` the first time it +/// sees it ([`WindowInfo::id`]), which is how every other part of komorebi names it. An id is never +/// given to another window, also after the window has closed. A closed window stays in the table, +/// with [`WindowInfo::alive`] false, for a minute, so that the event that names it can still be +/// logged. +#[derive(Default)] +pub struct Table { + next_id: u32, + by_uuid: HashMap, + windows: HashMap, + monitors: Vec, + foreground: Option, + cursor: Option<(i32, i32)>, +} + +fn rect(v: &Value) -> Rect { + let n = |k: &str| v[k].as_i64().unwrap_or(0) as i32; + Rect { + left: n("x"), + top: n("y"), + right: n("w"), + bottom: n("h"), + } +} + +/// FNV-1a: a monitor's id has to be the same on every run, so no `RandomState` +fn stable_id(s: &str) -> u32 { + let mut hash: u32 = 0x811c_9dc5; + for b in s.bytes() { + hash ^= u32::from(b); + hash = hash.wrapping_mul(0x0100_0193); + } + hash +} + +fn monitor(v: &Value) -> MonitorInfo { + let name = v["name"].as_str().unwrap_or_default().to_string(); + let serial = v["serial"].as_str().unwrap_or_default(); + + // an output's name follows the port it is plugged into; its serial follows the monitor + let serial_number_id = if serial.is_empty() { + name.clone() + } else { + format!( + "{}-{}-{serial}", + v["manufacturer"].as_str().unwrap_or_default(), + v["model"].as_str().unwrap_or_default() + ) + }; + + MonitorInfo { + id: stable_id(&serial_number_id), + name, + serial_number_id, + size: rect(&v["geo"]), + work_area: rect(&v["area"]), + } +} + +fn kwin(n: KWinNotification) -> SystemNotification { + SystemNotification::KWin(n) +} + +impl Table { + /// Returns an empty table. The first window it sees gets the id 1. + pub fn new() -> Self { + Self { + next_id: 1, + ..Self::default() + } + } + + // ---- queries --------------------------------------------------------------------------- + + /// Returns what is known about the window, or `None` if the table has never seen it or it + /// closed more than a minute ago. + pub fn window(&self, id: u32) -> Option { + self.windows.get(&id).map(|e| e.info.clone()) + } + + /// Returns the windows komorebi may manage that are open right now, ordered by id. + pub fn windows(&self) -> Vec { + let mut windows: Vec<_> = self + .windows + .values() + .filter(|e| e.info.alive && self.manageable(e)) + .map(|e| e.info.clone()) + .collect(); + windows.sort_by_key(|w| w.id); + windows + } + + /// Returns the monitors, in the order KWin lists its outputs. + pub fn monitors(&self) -> Vec { + self.monitors.clone() + } + + /// Returns the id of the window KWin last reported active, if it is still open. + pub fn foreground(&self) -> Option { + self.foreground + .filter(|id| self.windows.get(id).is_some_and(|e| e.info.alive)) + } + + /// Returns where the pointer was the last time the script said. + pub fn cursor(&self) -> Option<(i32, i32)> { + self.cursor + } + + /// Whether komorebi should have anything to do with this window: a normal window, as opposed + /// to a dialog, a panel, a popup. + fn manageable(&self, entry: &Entry) -> bool { + entry.kwin_normal + } + + // ---- events ---------------------------------------------------------------------------- + + fn id_for(&mut self, uuid: &str) -> u32 { + if let Some(id) = self.by_uuid.get(uuid) { + return *id; + } + let id = self.next_id.max(1); + self.next_id = id + 1; + self.by_uuid.insert(uuid.to_string(), id); + id + } + + fn entry_from(&mut self, w: &Value) -> (u32, Entry) { + let uuid = w["id"].as_str().unwrap_or_default().to_string(); + let id = self.id_for(&uuid); + let class = w["class"].as_str().unwrap_or_default().to_string(); + let pid = w["pid"].as_i64().unwrap_or_default() as i32; + let (exe, path) = process(pid, &class); + + let info = WindowInfo { + id, + pid, + title: w["caption"].as_str().unwrap_or_default().to_string(), + class, + exe, + path, + rect: rect(&w["geo"]), + minimized: w["minimized"].as_bool().unwrap_or(false), + normal: false, + alive: true, + }; + + let entry = Entry { + uuid, + info, + kwin_normal: w["normal"].as_bool().unwrap_or(false), + closed_at: None, + }; + + (id, entry) + } + + /// `WindowInfo::normal` is "may be managed", which is kept in step after every change rather + /// than recomputed by the consumer + fn sync_normal(&mut self, id: u32) { + let manageable = self.windows.get(&id).is_some_and(|e| self.manageable(e)); + if let Some(entry) = self.windows.get_mut(&id) { + entry.info.normal = manageable; + } + } + + fn prune(&mut self, now: Instant) { + let expired: Vec = self + .windows + .iter() + .filter(|(_, e)| { + e.closed_at + .is_some_and(|t| now.duration_since(t) > TOMBSTONE) + }) + .map(|(id, _)| *id) + .collect(); + + for id in expired { + if let Some(entry) = self.windows.remove(&id) { + self.by_uuid.remove(&entry.uuid); + } + } + } + + /// Updates the table with one event from the script, and returns what the rest of the daemon + /// has to do about it. `now` is when the event arrived; a closed window is forgotten a minute + /// after it closed. + /// + /// The event's `type` is one of: + /// + /// - `snapshot`: everything on the desktop (`windows`, `screens`, `active`, `cursor`), sent + /// once, when the script starts. It fills the table and raises no event: the window manager + /// reads the desktop from the table when it starts. + /// - `added`, `removed`: a window opened or closed. For a window komorebi may manage, they are + /// a [`WindowManagerEvent::Show`] and a [`WindowManagerEvent::Destroy`]. + /// - `activated`: KWin gave a window the focus ([`WindowManagerEvent::FocusChange`]), or, + /// with no `id`, took it away from every window. + /// - `minimized`: a window was minimized or brought back ([`WindowManagerEvent::Minimize`], + /// [`WindowManagerEvent::Restore`]). + /// - `geometry`: a window's frame changed. It raises no event. + /// - `cursor`: the answer to a cursor query ([`Output::Cursor`]). + /// - `failed`: commands the script could not carry out. They are logged. + /// + /// Anything else is logged at debug level and ignored. A dialog, a panel or a popup is in the + /// table, and can have the focus, but it raises no window event. + pub fn handle(&mut self, event: &Value, now: Instant) -> Vec { + self.prune(now); + + match event["type"].as_str() { + Some("snapshot") => self.on_snapshot(event), + Some("added") => self.on_added(event), + Some("removed") => self.on_removed(event, now), + Some("activated") => self.on_activated(event), + Some("minimized") => self.on_minimized(event), + Some("geometry") => { + if let Some(entry) = self.entry_mut(event) { + entry.info.rect = rect(&event["geo"]); + } + vec![] + } + Some("cursor") => { + let (x, y) = ( + event["x"].as_i64().unwrap_or(0) as i32, + event["y"].as_i64().unwrap_or(0) as i32, + ); + self.cursor = Some((x, y)); + vec![Output::Cursor { + token: event["token"].as_u64().unwrap_or(0), + x, + y, + }] + } + Some("failed") => { + tracing::warn!("the bridge could not do: {}", event["cmds"]); + vec![] + } + other => { + tracing::debug!("ignoring unknown bridge event {other:?}"); + vec![] + } + } + } + + fn entry_mut(&mut self, event: &Value) -> Option<&mut Entry> { + let uuid = event["id"].as_str()?; + let id = *self.by_uuid.get(uuid)?; + self.windows.get_mut(&id) + } + + fn id_of(&self, event: &Value) -> Option { + self.by_uuid.get(event["id"].as_str()?).copied() + } + + fn on_snapshot(&mut self, event: &Value) -> Vec { + // rebuild the windows, keeping the ids of those we already knew + let old = std::mem::take(&mut self.windows); + for w in event["windows"].as_array().cloned().unwrap_or_default() { + let (id, entry) = self.entry_from(&w); + self.windows.insert(id, entry); + self.sync_normal(id); + } + // closed windows still within their grace period + for (id, entry) in old { + if entry.closed_at.is_some() { + self.windows.entry(id).or_insert(entry); + } + } + + self.foreground = event["active"] + .as_str() + .and_then(|u| self.by_uuid.get(u)) + .copied(); + + if let (Some(x), Some(y)) = (event["cursor"]["x"].as_i64(), event["cursor"]["y"].as_i64()) { + self.cursor = Some((x as i32, y as i32)); + } + + self.set_monitors(&event["screens"]); + vec![] + } + + fn set_monitors(&mut self, screens: &Value) { + self.monitors = screens + .as_array() + .map(|a| a.iter().map(monitor).collect()) + .unwrap_or_default(); + } + + fn on_added(&mut self, event: &Value) -> Vec { + let (id, entry) = self.entry_from(event); + if self.windows.get(&id).is_some_and(|e| e.info.alive) { + // already announced (the script announces on activation as well as on creation) + return vec![]; + } + + self.windows.insert(id, entry); + self.sync_normal(id); + + if self.windows[&id].info.normal { + vec![Output::Event(WindowManagerEvent::Show( + kwin(KWinNotification::WindowAdded), + Window::from(id), + ))] + } else { + vec![] + } + } + + fn on_removed(&mut self, event: &Value, now: Instant) -> Vec { + let Some(id) = self.id_of(event) else { + return vec![]; + }; + + let manageable = self.windows.get(&id).is_some_and(|e| e.info.normal); + + if let Some(entry) = self.windows.get_mut(&id) { + entry.info.alive = false; + entry.info.normal = false; + entry.closed_at = Some(now); + } + + if self.foreground == Some(id) { + self.foreground = None; + } + + if manageable { + vec![Output::Event(WindowManagerEvent::Destroy( + kwin(KWinNotification::WindowRemoved), + Window::from(id), + ))] + } else { + vec![] + } + } + + fn on_activated(&mut self, event: &Value) -> Vec { + let Some(uuid) = event["id"].as_str() else { + self.foreground = None; + return vec![]; + }; + + let Some(id) = self.by_uuid.get(uuid).copied() else { + return vec![]; + }; + + self.foreground = Some(id); + tracing::debug!( + "KWin activated window {id} ({})", + self.windows.get(&id).map_or("?", |e| e.info.title.as_str()) + ); + + if self.windows.get(&id).is_some_and(|e| e.info.normal) { + vec![Output::Event(WindowManagerEvent::FocusChange( + kwin(KWinNotification::WindowActivated), + Window::from(id), + ))] + } else { + vec![] + } + } + + fn on_minimized(&mut self, event: &Value) -> Vec { + let minimized = event["v"].as_bool().unwrap_or(false); + let Some(id) = self.id_of(event) else { + return vec![]; + }; + + let Some(entry) = self.windows.get_mut(&id) else { + return vec![]; + }; + entry.info.minimized = minimized; + + if !entry.info.normal { + return vec![]; + } + + let window = Window::from(id); + vec![Output::Event(if minimized { + WindowManagerEvent::Minimize(kwin(KWinNotification::WindowMinimized), window) + } else { + WindowManagerEvent::Restore(kwin(KWinNotification::WindowRestored), window) + })] + } +} + +/// The executable of a process, by name and by path. +/// +/// Rules match on these (`Exe` is the basename, `Path` the full path), as they do on Windows. +/// `/proc//exe` is a symlink to the executable; for a window whose process cannot be read +/// (another user's, a sandbox) the class is the best identity there is. +fn process(pid: i32, class: &str) -> (String, String) { + #[cfg(target_os = "linux")] + if pid > 0 + && let Ok(path) = std::fs::read_link(format!("/proc/{pid}/exe")) + { + let exe = path + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_default(); + + return (exe, path.to_string_lossy().to_string()); + } + + let _ = pid; + (class.to_string(), String::new()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn win(id: &str, desktops: &[&str]) -> Value { + json!({ + "id": id, "pid": 0, "class": "foot", "caption": "terminal", "normal": true, + "minimized": false, "fullscreen": false, + "geo": { "x": 10, "y": 20, "w": 800, "h": 600 }, + "desktops": desktops, + }) + } + + fn snapshot(windows: Vec) -> Value { + json!({ + "type": "snapshot", + "windows": windows, + "screens": [{ + "name": "DP-1", "manufacturer": "ACME", "model": "M1", "serial": "S1", + "geo": { "x": 0, "y": 0, "w": 1920, "h": 1080 }, + "area": { "x": 0, "y": 0, "w": 1920, "h": 1050 }, + }], + "active": null, + "cursor": { "x": 5, "y": 6 }, + }) + } + + fn table(windows: Vec) -> Table { + let mut t = Table::new(); + t.handle(&snapshot(windows), Instant::now()); + t + } + + fn events(out: &[Output]) -> Vec { + out.iter() + .filter_map(|o| match o { + Output::Event(e) => Some(format!("{e} {}", e.window_id().unwrap_or(0))), + _ => None, + }) + .collect() + } + + /// The events of a session as the bridge sends them: `bridge.test.js` plays the session + /// against a fake KWin and checks that the bridge sends exactly these + #[test] + fn the_bridges_events_for_a_session_are_the_window_events_komorebi_expects() { + let session: Vec = + serde_json::from_str(include_str!("fixtures/events.json")).unwrap(); + let mut t = Table::new(); + let now = Instant::now(); + + let mut trace = vec![]; + for event in &session { + let out = t.handle(event, now); + let mut said = events(&out); + for output in &out { + if let Output::Cursor { token, x, y } = output { + said.push(format!("Cursor {token} at {x},{y}")); + } + } + trace.push(format!( + "{} -> {}", + event["type"].as_str().unwrap(), + said.join(", ") + )); + + if event["type"] == "added" && event["caption"] == "a terminal" { + let w = t.window(2).unwrap(); + assert_eq!( + (w.pid, w.class.as_str(), w.title.as_str()), + (4343, "foot", "a terminal") + ); + assert_eq!( + w.rect, + Rect { + left: 480, + top: 270, + right: 960, + bottom: 540 + } + ); + assert!(w.normal && !w.minimized); + } + } + + assert_eq!( + trace, + [ + "snapshot -> ", + "added -> Show 2", + "activated -> FocusChange 2", + "added -> ", + "minimized -> Minimize 2", + "minimized -> Restore 2", + "geometry -> ", + "cursor -> Cursor 1 at 1200,701", + "removed -> Destroy 2", + ] + ); + + // the editor of the snapshot is left, and its dialog, which komorebi does not manage + let windows = t.windows(); + assert_eq!(windows.len(), 1); + assert_eq!(windows[0].title, "notes.txt — Kate"); + assert_eq!(t.window(3).map(|w| w.normal), Some(false)); + assert_eq!(t.window(2).unwrap().rect.bottom, 532, "the geometry event"); + assert_eq!(t.foreground(), None, "the terminal had the focus"); + assert_eq!(t.cursor(), Some((1200, 701))); + + let monitor = &t.monitors()[0]; + assert_eq!( + (monitor.name.as_str(), monitor.serial_number_id.as_str()), + ("DP-1", "ACME-M1-S1") + ); + assert_eq!( + monitor.work_area, + Rect { + left: 0, + top: 0, + right: 1920, + bottom: 1050 + } + ); + } + + #[test] + fn the_snapshot_fills_the_table_without_raising_events() { + let mut t = Table::new(); + let out = t.handle( + &snapshot(vec![win("a", &["d1"]), win("b", &["d1"])]), + Instant::now(), + ); + + assert!(events(&out).is_empty()); + let windows = t.windows(); + assert_eq!(windows.len(), 2); + assert_eq!( + windows[0].rect, + Rect { + left: 10, + top: 20, + right: 800, + bottom: 600 + } + ); + assert_eq!(t.cursor(), Some((5, 6))); + } + + #[test] + fn monitors_get_a_stable_identity_from_the_serial_not_the_port() { + let t = table(vec![]); + let m = &t.monitors()[0]; + assert_eq!(m.serial_number_id, "ACME-M1-S1"); + assert_eq!(m.id, stable_id("ACME-M1-S1")); + assert_eq!(m.work_area.bottom, 1050); + + let mut t2 = Table::new(); + let mut s = snapshot(vec![]); + s["screens"][0]["name"] = json!("HDMI-A-2"); + t2.handle(&s, Instant::now()); + assert_eq!( + t2.monitors()[0].id, + m.id, + "same monitor on another port keeps its id" + ); + } + + #[test] + fn a_monitor_without_a_serial_is_identified_by_its_name() { + let mut t = Table::new(); + let mut s = snapshot(vec![]); + s["screens"][0]["serial"] = json!(""); + t.handle(&s, Instant::now()); + assert_eq!(t.monitors()[0].serial_number_id, "DP-1"); + } + + #[test] + fn ids_are_assigned_once_per_window_and_survive_a_new_snapshot() { + let mut t = table(vec![win("a", &["d1"]), win("b", &["d1"])]); + let before: Vec = t.windows().iter().map(|w| w.id).collect(); + + t.handle( + &snapshot(vec![ + win("b", &["d1"]), + win("a", &["d1"]), + win("c", &["d1"]), + ]), + Instant::now(), + ); + let after: Vec = t.windows().iter().map(|w| w.id).collect(); + + assert_eq!(&after[..2], &before[..]); + assert_eq!(after.len(), 3); + } + + #[test] + fn a_new_window_raises_show_and_then_focus_in_that_order() { + let mut t = table(vec![]); + let now = Instant::now(); + + let shown = t.handle( + &json!({ "type": "added", "id": "w1", "pid": 0, "class": "foot", + "caption": "x", "normal": true, "geo": {"x":0,"y":0,"w":1,"h":1}, "desktops": ["d1"] }), + now, + ); + let focused = t.handle(&json!({ "type": "activated", "id": "w1" }), now); + + assert_eq!(events(&shown), vec!["Show 1"]); + assert_eq!(events(&focused), vec!["FocusChange 1"]); + assert_eq!(t.foreground(), Some(1)); + } + + #[test] + fn announcing_the_same_window_twice_shows_it_once() { + let mut t = table(vec![]); + let added = json!({ "type": "added", "id": "w1", "pid": 0, "class": "foot", "caption": "x", + "normal": true, "geo": {"x":0,"y":0,"w":1,"h":1}, "desktops": ["d1"] }); + + assert_eq!(events(&t.handle(&added, Instant::now())).len(), 1); + assert!(events(&t.handle(&added, Instant::now())).is_empty()); + } + + #[test] + fn dialogs_panels_and_popups_raise_nothing() { + let mut t = table(vec![]); + let now = Instant::now(); + let mut dialog = win("dlg", &["d1"]); + dialog["type"] = json!("added"); + dialog["normal"] = json!(false); + + assert!(t.handle(&dialog, now).is_empty()); + assert!( + t.handle(&json!({ "type": "activated", "id": "dlg" }), now) + .is_empty() + ); + assert!(t.windows().is_empty()); + // ... though they are still known, and still have a foreground + assert_eq!(t.foreground(), Some(1)); + } + + #[test] + fn a_closed_window_raises_destroy_and_can_still_be_asked_about() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + t.handle(&json!({ "type": "activated", "id": "a" }), now); + + let out = t.handle(&json!({ "type": "removed", "id": "a" }), now); + assert_eq!(events(&out), vec!["Destroy 1"]); + assert_eq!(t.foreground(), None); + + let info = t.window(1).expect("a tombstone is kept"); + assert!(!info.alive); + assert_eq!(info.title, "terminal"); + assert!(t.windows().is_empty()); + } + + #[test] + fn tombstones_are_dropped_after_a_while_and_their_ids_are_not_reused() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + t.handle(&json!({ "type": "removed", "id": "a" }), now); + + t.handle( + &json!({ "type": "geometry", "id": "nobody", "geo": {"x":0,"y":0,"w":0,"h":0} }), + now + Duration::from_secs(61), + ); + assert!(t.window(1).is_none()); + + let out = t.handle( + &json!({ "type": "added", "id": "b", "pid": 0, "class": "foot", "caption": "x", + "normal": true, "geo": {"x":0,"y":0,"w":1,"h":1}, "desktops": ["d1"] }), + now, + ); + assert_eq!(events(&out), vec!["Show 2"]); + } + + #[test] + fn minimize_and_restore_map_to_their_events() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + + assert_eq!( + events(&t.handle(&json!({ "type": "minimized", "id": "a", "v": true }), now)), + vec!["Minimize 1"] + ); + assert!(t.window(1).unwrap().minimized); + assert_eq!( + events(&t.handle(&json!({ "type": "minimized", "id": "a", "v": false }), now)), + vec!["Restore 1"] + ); + } + + #[test] + fn geometry_updates_the_rect_silently() { + let mut t = table(vec![win("a", &["d1"])]); + let out = t.handle( + &json!({ "type": "geometry", "id": "a", "geo": {"x":1,"y":2,"w":3,"h":4} }), + Instant::now(), + ); + + assert!(out.is_empty()); + assert_eq!( + t.window(1).unwrap().rect, + Rect { + left: 1, + top: 2, + right: 3, + bottom: 4 + } + ); + } + + #[test] + fn a_cursor_query_answer_is_passed_on_and_remembered() { + let mut t = table(vec![]); + let out = t.handle( + &json!({ "type": "cursor", "token": 7, "x": 300, "y": 400 }), + Instant::now(), + ); + + assert!(matches!( + &out[..], + [Output::Cursor { + token: 7, + x: 300, + y: 400 + }] + )); + assert_eq!(t.cursor(), Some((300, 400))); + } +} diff --git a/komorebi/src/kwin/tsconfig.json b/komorebi/src/kwin/tsconfig.json new file mode 100644 index 00000000..29d8a9c4 --- /dev/null +++ b/komorebi/src/kwin/tsconfig.json @@ -0,0 +1,22 @@ +{ + // Checks bridge.js as KWin runs it, as strict TypeScript through its JSDoc comments, against + // the declarations of KWin's API in kwin-api.d.ts. Nothing is emitted. `lib` is ECMAScript + // 2016, the edition Qt's JavaScript engine implements, and nothing else, so the globals of a + // browser or of node (`setTimeout`, `console`) are errors. Beyond `strict`: an unused local, a + // function that does not return on every path, a switch case that falls through and code that + // cannot be reached are errors too. + "compilerOptions": { + "target": "es2016", + "lib": ["es2016"], + "types": [], + "allowJs": true, + "checkJs": true, + "noEmit": true, + "strict": true, + "noUnusedLocals": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "allowUnreachableCode": false + }, + "files": ["bridge.js", "kwin-api.d.ts"] +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 6d9a7be6..ac675ddd 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -8,9 +8,14 @@ //! //! The [`window_manager::WindowManager`] keeps that model. It is loaded from what the backend //! reports ([`desktop`]) and changed by what the compositor reports about windows -//! ([`window_manager_event`], [`process_event`]). +//! ([`window_manager_event`], [`process_event`]), which reaches it through +//! [`window_manager_event_listener`]. +//! +//! On KDE Plasma the backend is [`kwin::KWinBackend`], which talks to a script it loads into KWin. use color_eyre::eyre; +use lazy_static::lazy_static; +use std::path::PathBuf; use std::sync::atomic::AtomicI32; #[macro_use] @@ -20,18 +25,35 @@ pub mod backend; pub mod container; pub mod core; pub mod desktop; +pub mod kwin; pub mod lockable_sequence; pub mod monitor; pub mod process_event; pub mod window; pub mod window_manager; pub mod window_manager_event; +pub mod window_manager_event_listener; pub mod workspace; /// The error the window manager returns when it talks to the desktop: a report, since every /// failure comes from the one backend. pub type LibraryError = eyre::Report; +lazy_static! { + /// Where komorebi keeps the files it needs while it runs, such as the script it loads into + /// KWin: `$XDG_RUNTIME_DIR/komorebi`, which is per-user, on tmpfs and removed at logout. + /// Without a runtime directory (a bare ssh session, or the tests on a Mac) it falls back to the + /// local data directory. + pub static ref DATA_DIR: PathBuf = std::env::var_os("XDG_RUNTIME_DIR") + .filter(|dir| !dir.is_empty()) + .map(|dir| PathBuf::from(dir).join("komorebi")) + .unwrap_or_else(|| { + 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 /// workspaces, for a monitor that sets none of its own. The default for this is 5. pub static DEFAULT_WORKSPACE_PADDING: AtomicI32 = AtomicI32::new(5); diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 39eb1c3f..fe9d0065 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -3,19 +3,22 @@ //! The daemon owns the layout of every window and asks the compositor, through a backend, to //! put each one where the layout says. //! -//! The backend is chosen on the command line. `--fake-backend` is an in-memory desktop with one -//! monitor and no windows, for development and testing. Without a backend the daemon exits with -//! a usage error. With one, it loads the monitors and the windows that are open, tiles them, and -//! runs until it is stopped with `SIGINT` or `SIGTERM`. +//! The backend is KWin's ([`komorebi::kwin`]): the daemon connects to the session bus, loads its +//! script into KWin and waits for the script to report the desktop. `--fake-backend` replaces it +//! with an in-memory desktop with one monitor and no windows, for development and testing. The +//! daemon then loads the monitors and the windows that are open, tiles them, handles the events +//! the backend reports on a thread of their own, and runs until it is stopped with `SIGINT` or +//! `SIGTERM`. -use clap::CommandFactory; use clap::Parser; use clap::ValueEnum; -use clap::error::ErrorKind; use color_eyre::eyre; use komorebi::backend; use komorebi::backend::fake::FakeBackend; +use komorebi::process_event::listen_for_events; use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event_listener; +use parking_lot::Mutex; use serde::Deserialize; use std::sync::Arc; use tracing_subscriber::EnvFilter; @@ -72,6 +75,31 @@ fn setup(log_level: LogLevel) -> eyre::Result<()> { Ok(()) } +#[cfg(feature = "deadlock_detection")] +#[tracing::instrument] +fn detect_deadlocks() { + // Create a background thread which checks for deadlocks every 10s + std::thread::spawn(move || { + loop { + tracing::info!("running deadlock detector"); + std::thread::sleep(std::time::Duration::from_secs(5)); + let deadlocks = parking_lot::deadlock::check_deadlock(); + if deadlocks.is_empty() { + continue; + } + + tracing::error!("{} deadlocks detected", deadlocks.len()); + for (i, threads) in deadlocks.iter().enumerate() { + tracing::error!("deadlock #{}", i); + for t in threads { + tracing::error!("thread id: {:#?}", t.thread_id()); + tracing::error!("{:#?}", t.backtrace()); + } + } + } + }); +} + #[derive(Default, Deserialize, ValueEnum, Clone)] #[serde(rename_all = "snake_case")] enum LogLevel { @@ -90,9 +118,9 @@ struct Opts { /// Level of log output verbosity #[clap(long, value_enum, default_value_t=LogLevel::Info)] log_level: LogLevel, - /// Run against an in-memory desktop with one monitor and no windows, for development and - /// testing. Windows and monitors are not real. - #[clap(long)] + /// Run against an in-memory desktop instead of KWin, for development and testing. Windows + /// and monitors are not real. + #[clap(long, hide = true)] fake_backend: bool, } @@ -104,17 +132,21 @@ fn main() -> eyre::Result<()> { tracing::warn!("running against an in-memory desktop; nothing here is a real window"); backend::set_backend(Arc::new(FakeBackend::with_one_monitor())); } else { - Opts::command() - .error( - ErrorKind::MissingRequiredArgument, - "a backend has to be chosen: pass --fake-backend to run against an in-memory desktop", - ) - .exit(); + tracing::info!("connecting to KWin"); + backend::set_backend(komorebi::kwin::connect()?); } - let mut wm = WindowManager::new()?; - wm.init()?; - wm.retile_all()?; + #[cfg(feature = "deadlock_detection")] + detect_deadlocks(); + + let wm = Arc::new(Mutex::new(WindowManager::new( + window_manager_event_listener::event_rx(), + )?)); + + wm.lock().init()?; + wm.lock().retile_all()?; + + listen_for_events(wm.clone()); let (quit_sender, quit_receiver) = std::sync::mpsc::channel(); ctrlc::set_handler(move || { @@ -122,7 +154,7 @@ fn main() -> eyre::Result<()> { }) .expect("could not set ctrl-c handler"); - // this thread only waits to be told to stop + // everything runs on its own threads; this one only waits to be told to stop let _ = quit_receiver.recv(); tracing::info!("stop signal received"); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index d14e3059..8f051fd3 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -12,14 +12,48 @@ //! - **Minimize**: a window the user minimized leaves its workspace and the rest are tiled //! again; **Restore** brings it back in a container of its own. //! +//! The daemon hands events to the window manager on a thread of their own, +//! [`listen_for_events`], one at a time and in the order the backend raised them. +//! //! [`Window::should_manage`]: crate::window::Window::should_manage use crate::backend::backend; use crate::window_manager::WindowManager; use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; +use parking_lot::Mutex; +use std::sync::Arc; use tracing::instrument; +/// Starts the thread that takes each event from the window manager's channel +/// ([`WindowManager::incoming_events`]) and handles it with [`WindowManager::process_event`]. +/// +/// An event that fails is logged and the next one is taken: one event the window manager could +/// not act on does not stop the ones after it. +#[tracing::instrument] +pub fn listen_for_events(wm: Arc>) { + let receiver = wm.lock().incoming_events.clone(); + + std::thread::spawn(move || { + tracing::info!("listening"); + loop { + if let Ok(event) = receiver.recv() { + let mut guard = wm.lock(); + match guard.process_event(event) { + Ok(()) => {} + Err(error) => { + if cfg!(debug_assertions) { + tracing::error!("{:?}", error) + } else { + tracing::error!("{}", error) + } + } + } + } + } + }); +} + /// After a managed window is destroyed KWin activates whatever it considers next. Only when there /// is nothing to activate does komorebi step in and focus its own selection; otherwise the /// `FocusChange` for the successor does the reconciling and the two do not fight. diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 8b9fc80f..6898a75d 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -13,9 +13,11 @@ use crate::desktop; use crate::monitor::Monitor; use crate::ring::Ring; use crate::window::Window; +use crate::window_manager_event::WindowManagerEvent; use crate::workspace::Workspace; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use crossbeam_channel::Receiver; use std::collections::HashMap; #[derive(Debug)] @@ -23,6 +25,9 @@ pub struct WindowManager { pub monitors: Ring, pub mouse_follows_focus: bool, pub work_area_offset: Option, + /// The events the backend has reported and the window manager has yet to handle, from + /// [`crate::window_manager_event_listener`] + pub incoming_events: Receiver, pub minimized_windows: HashMap, /// Maps each known window id to the (monitor, workspace) index pair managing it pub known_window_ids: HashMap, @@ -31,13 +36,14 @@ pub struct WindowManager { impl_ring_elements!(WindowManager, Monitor); impl WindowManager { - /// Returns a window manager with no monitors: [`WindowManager::init`] loads them from the - /// backend - pub fn new() -> eyre::Result { + /// Returns a window manager with no monitors, which handles the events that arrive on + /// `incoming`: [`WindowManager::init`] loads the monitors from the backend + pub fn new(incoming: Receiver) -> eyre::Result { Ok(Self { monitors: Ring::default(), mouse_follows_focus: true, work_area_offset: None, + incoming_events: incoming, minimized_windows: HashMap::new(), known_window_ids: Default::default(), }) @@ -202,8 +208,10 @@ mod tests { use std::sync::Arc; fn setup_window_manager() -> WindowManager { + let (_sender, receiver) = crossbeam_channel::bounded(1); + // Create a new WindowManager instance - let wm = WindowManager::new(); + let wm = WindowManager::new(receiver); // Window Manager should be created successfully assert!(wm.is_ok()); diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index 2abd946f..15e6a6f2 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -18,7 +18,7 @@ pub enum SystemNotification { KWin(KWinNotification), } -/// The signals of the KWin script API an event comes from +/// The KWin script signals the bridge listens to #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, PartialEq, Eq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum KWinNotification { diff --git a/komorebi/src/window_manager_event_listener.rs b/komorebi/src/window_manager_event_listener.rs new file mode 100644 index 00000000..d72f9530 --- /dev/null +++ b/komorebi/src/window_manager_event_listener.rs @@ -0,0 +1,35 @@ +//! The channel that carries [`WindowManagerEvent`]s from the backend to the window manager. +//! +//! The backend raises events on its own threads, as the compositor reports them, and calls +//! [`send_notification`]. The window manager takes them, one at a time and in order, on the thread +//! [`listen_for_events`](crate::process_event::listen_for_events) starts, from the receiver it was +//! made with ([`event_rx`]). The channel is bounded: an event that does not fit is dropped and +//! logged, so a backend never waits for the window manager. + +use crate::window_manager_event::WindowManagerEvent; +use crossbeam_channel::Receiver; +use crossbeam_channel::Sender; +use std::sync::OnceLock; + +static CHANNEL: OnceLock<(Sender, Receiver)> = + OnceLock::new(); + +fn channel() -> &'static (Sender, Receiver) { + CHANNEL.get_or_init(|| crossbeam_channel::bounded(20)) +} + +fn event_tx() -> Sender { + channel().0.clone() +} + +/// Returns the receiving end of the channel, for the window manager. +pub fn event_rx() -> Receiver { + channel().1.clone() +} + +/// Queues an event for the window manager, or drops it with a warning if 20 are already waiting. +pub fn send_notification(notification: WindowManagerEvent) { + if event_tx().try_send(notification).is_err() { + tracing::warn!("channel is full; dropping notification") + } +} diff --git a/komorebi/tests/no_backend.rs b/komorebi/tests/no_backend.rs deleted file mode 100644 index 438541e6..00000000 --- a/komorebi/tests/no_backend.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! `komorebi` refuses to start without a backend, and says how to choose one. - -use std::process::Command; - -#[test] -fn without_a_backend_komorebi_exits_with_an_error_naming_the_flag() { - let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) - .output() - .expect("komorebi runs"); - - // the exit code of a usage error - assert_eq!(output.status.code(), Some(2)); - - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("a backend has to be chosen: pass --fake-backend"), - "{stderr}" - ); -} diff --git a/komorebi/tests/no_kwin.rs b/komorebi/tests/no_kwin.rs new file mode 100644 index 00000000..eea65d3f --- /dev/null +++ b/komorebi/tests/no_kwin.rs @@ -0,0 +1,43 @@ +//! `komorebi` connects to KWin unless it is told to run against the in-memory desktop, and says +//! what went wrong when it cannot. + +use std::process::Command; +use std::process::Stdio; +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"; + +#[test] +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) + .output() + .expect("komorebi runs"); + + assert_eq!(output.status.code(), Some(1)); + + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("could not connect to the session bus as org.komorebi.Bridge"), + "{stderr}" + ); +} + +#[test] +fn with_the_fake_backend_komorebi_runs_without_a_session_bus() { + let mut daemon = Command::new(env!("CARGO_BIN_EXE_komorebi")) + .args(["--fake-backend", "--log-level", "error"]) + .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("komorebi runs"); + + std::thread::sleep(Duration::from_millis(1500)); + let exited = daemon.try_wait().expect("komorebi can be waited for"); + + daemon.kill().expect("komorebi can be stopped"); + daemon.wait().expect("komorebi can be waited for"); + assert!(exited.is_none(), "komorebi exited: {exited:?}"); +} diff --git a/komorebi/tests/wm_events.rs b/komorebi/tests/wm_events.rs index c982346f..34f79af9 100644 --- a/komorebi/tests/wm_events.rs +++ b/komorebi/tests/wm_events.rs @@ -56,9 +56,10 @@ fn desktop() -> (Arc, WindowManager) { fn desktop_on(fake: FakeBackend) -> (Arc, WindowManager) { let fake = Arc::new(fake); + let (_sender, receiver) = crossbeam_channel::bounded(1); let wm = with_backend(fake.clone(), || { - let mut wm = WindowManager::new().unwrap(); + let mut wm = WindowManager::new(receiver).unwrap(); wm.init().unwrap(); wm }); diff --git a/nix/tests/vm/default.nix b/nix/tests/vm/default.nix index 66fc2b82..99e4a62c 100644 --- a/nix/tests/vm/default.nix +++ b/nix/tests/vm/default.nix @@ -2,16 +2,21 @@ # (Linux) and `legacyPackages..vm.` (everywhere), so a new suite needs no edit to # the flake. See docs/dev/vm-tests.md. # -# `hostPkgs` is the pkgs of the machine that runs QEMU; the guests are always Linux. `scale` says +# `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. { hostPkgs, + komorebiFor, scale ? 1, }: let inherit (hostPkgs) lib; + # a Linux guest of the host's architecture, which is what the test driver boots + guestSystem = "${hostPkgs.stdenv.hostPlatform.parsed.cpu.name}-linux"; + # the library the suites import, built for the python of the test driver komorebiVm = ps: @@ -75,6 +80,9 @@ let globalTimeout = builtins.ceil (suite.timeoutMinutes * 60 * scale); passthru.tier = suite.tier; + # the nodes take the daemon as an argument, `komorebi` + node.specialArgs.komorebi = komorebiFor guestSystem; + nodes.machine = { imports = [ (./nodes + "/${suite.kind}.nix") ]; }; diff --git a/nix/tests/vm/lib/komorebi_vm/__init__.py b/nix/tests/vm/lib/komorebi_vm/__init__.py index 6b771634..d6f4722e 100644 --- a/nix/tests/vm/lib/komorebi_vm/__init__.py +++ b/nix/tests/vm/lib/komorebi_vm/__init__.py @@ -4,15 +4,19 @@ A suite imports what it needs from here: * [`Checks`](komorebi_vm.checks.Checks) counts checks and fails at the end. * [`Kde`](komorebi_vm.kde.Kde) is a KWin session inside a test machine, with - the tools to look at it (`kdotool`, `busctl`, `kscreen-doctor`, screenshots). + the tools to look at it (`kdotool`, `busctl`, `kscreen-doctor`, screenshots) + and the komorebi daemon that runs in it. +* [`daemon`](komorebi_vm.daemon) reads what the daemon logs about the events it + handles. The library depends on the small [`Machine`](komorebi_vm.machine.Machine) protocol, not on the test driver, so `nix/tests/vm/lib/tests` can run it against a fake machine (the `vm-lib` check does). """ +from komorebi_vm import daemon from komorebi_vm.checks import Checks from komorebi_vm.kde import Kde, Rect from komorebi_vm.machine import Machine -__all__ = ["Checks", "Kde", "Machine", "Rect"] +__all__ = ["Checks", "Kde", "Machine", "Rect", "daemon"] diff --git a/nix/tests/vm/lib/komorebi_vm/daemon.py b/nix/tests/vm/lib/komorebi_vm/daemon.py new file mode 100644 index 00000000..035f3027 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/daemon.py @@ -0,0 +1,38 @@ +"""What the komorebi daemon logs about the events it handles. + +A test reads the daemon's view of the desktop from its log +([`Kde.komorebi_log`](komorebi_vm.kde.Kde.komorebi_log)), started with +`--log-level debug`: every event it handles is an info line, and every focus +change KWin reports names the window by the daemon's id and its title. +""" + +import re +from dataclasses import dataclass + +_EVENT = re.compile(r"processing event: (\w+) for window (\d+) with notification (\w+)") +_ACTIVATED = re.compile(r"KWin activated window (\d+) \((.*)\)$", re.MULTILINE) + + +@dataclass(frozen=True) +class Event: + """A window event the daemon handled.""" + + kind: str + """The event (`Show`, `Destroy`, `FocusChange`, `Minimize`, `Restore`).""" + window: int + """The daemon's id for the window.""" + notification: str + """The KWin signal it came from (`WindowAdded`, ...).""" + + +def events(log: str) -> list[Event]: + """Returns the window events the daemon handled, in the order it handled them.""" + return [Event(kind, int(window), signal) for kind, window, signal in _EVENT.findall(log)] + + +def window_ids(log: str) -> dict[str, int]: + """Returns the daemon's id for each window KWin has given the focus, by title. + + A title that two windows had is the later one's. + """ + return {title: int(window) for window, title in _ACTIVATED.findall(log)} diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index 9c2c9fb5..ea70c92f 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -178,6 +178,38 @@ class Kde: "stop", f"kwin-virtual@{self.name}.service", f"session-bus@{self.name}.service" ) + def start_komorebi(self, *args: str) -> None: + """Starts the daemon in this session, with `args`, as the user unit `komorebi@NAME`. + + The unit runs the `komorebi` the node has, against this session's bus and KWin, and + writes its log to a file that [`Kde.komorebi_log`][] reads, emptied on every start. + """ + words = shlex.quote(" ".join(args)) + self.as_user(f"echo KOMOREBI_ARGS={words} > {self.runtime}/komorebi-{self.name}.env") + self.systemctl("start", f"komorebi@{self.name}.service") + + def stop_komorebi(self) -> None: + """Stops the daemon with `SIGTERM`, as a logout does, and waits for it to exit.""" + self.systemctl("stop", f"komorebi@{self.name}.service") + + def komorebi_running(self) -> bool: + """Returns true if and only if the daemon of this session is running.""" + unit = f"komorebi@{self.name}.service" + command = self._wrap(f"systemctl --user is-active --quiet {unit}", session=False) + return self.machine.execute(command)[0] == 0 + + def komorebi_log(self) -> str: + """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 script_loaded(self, name: str = "komorebi-bridge") -> bool: + """Returns true if and only if KWin runs a script loaded under `name`.""" + status, out = self.run( + "busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting" + f" isScriptLoaded s {shlex.quote(name)}" + ) + return status == 0 and out.strip() == "b true" + def wait_for( self, predicate: Callable[[], bool], @@ -228,6 +260,18 @@ class Kde: lines = self.run("kdotool getactivewindow")[1].strip().splitlines() return lines[-1] if lines else "" + def activate(self, wid: str) -> None: + """Asks KWin to give the window the focus, as a click on it would.""" + self.sh(f"kdotool windowactivate {shlex.quote(wid)}") + + def minimize(self, wid: str) -> None: + """Asks KWin to minimize the window, as its title bar button would.""" + self.sh(f"kdotool windowminimize {shlex.quote(wid)}") + + def close(self, wid: str) -> None: + """Asks KWin to close the window, as its title bar button would.""" + self.sh(f"kdotool windowclose {shlex.quote(wid)}") + def shot(self, name: str) -> Image.Image: """Takes a screenshot of the machine's display and returns it, as RGB. diff --git a/nix/tests/vm/lib/tests/test_daemon.py b/nix/tests/vm/lib/tests/test_daemon.py new file mode 100644 index 00000000..9b915e99 --- /dev/null +++ b/nix/tests/vm/lib/tests/test_daemon.py @@ -0,0 +1,28 @@ +from komorebi_vm import daemon +from komorebi_vm.daemon import Event + +LOG = """\ +2026-10-27T12:00:00.000001Z INFO komorebi::kwin: loaded the KWin bridge script (script id 0) +2026-10-27T12:00:01.000001Z DEBUG komorebi::kwin::state: KWin activated window 2 (alpha) +2026-10-27T12:00:01.000002Z INFO handle_event: komorebi::process_event: processing event: \ +Show for window 2 with notification WindowAdded +2026-10-27T12:00:01.000003Z INFO handle_event: komorebi::process_event: processing event: \ +FocusChange for window 2 with notification WindowActivated +2026-10-27T12:00:02.000001Z DEBUG komorebi::kwin::state: KWin activated window 1 (a (b) c) +""" + + +def test_events_are_read_in_the_order_they_were_handled() -> None: + assert daemon.events(LOG) == [ + Event("Show", 2, "WindowAdded"), + Event("FocusChange", 2, "WindowActivated"), + ] + + +def test_window_ids_are_found_by_title_also_one_with_parentheses() -> None: + assert daemon.window_ids(LOG) == {"alpha": 2, "a (b) c": 1} + + +def test_an_empty_log_has_nothing_in_it() -> None: + assert daemon.events("") == [] + assert daemon.window_ids("") == {} diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index bf149f6a..0794f1a8 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -135,3 +135,54 @@ def test_shot_returns_the_screenshot_as_rgb(machine: FakeMachine) -> None: assert image.size == (4, 4) assert image.getpixel((0, 0)) == (10, 20, 30) assert (machine.out_dir / "desktop.png").exists() + + +def test_start_komorebi_writes_the_arguments_and_starts_the_unit(machine: FakeMachine) -> None: + Kde(machine, "main").start_komorebi("--log-level", "debug") + + scripts = [inner(command) for command in machine.commands if " sh -c " in command] + assert "echo KOMOREBI_ARGS='--log-level debug' > /run/user/1000/komorebi-main.env" in scripts + assert "systemctl --user start komorebi@main.service" in scripts + + +def test_the_log_is_the_file_of_the_session_and_empty_before_a_start( + machine: FakeMachine, +) -> None: + machine.reply("cat /run/user/1000/komorebi-main.log", output="a line\n") + assert Kde(machine, "main").komorebi_log() == "a line\n" + + machine.replies.clear() + machine.reply("cat /run/user/1000/komorebi-main.log", status=1, output="") + assert Kde(machine, "main").komorebi_log() == "" + + +def test_komorebi_running_asks_the_user_manager(machine: FakeMachine) -> None: + machine.reply("is-active --quiet komorebi@main.service", status=3) + assert not Kde(machine, "main").komorebi_running() + + machine.replies.clear() + assert Kde(machine, "main").komorebi_running() + + +def test_script_loaded_reads_the_answer_of_kwin(machine: FakeMachine) -> None: + machine.reply("isScriptLoaded s komorebi-bridge", output="b true\n") + assert Kde(machine, "main").script_loaded() + + machine.replies.clear() + machine.reply("isScriptLoaded s komorebi-bridge", output="b false\n") + assert not Kde(machine, "main").script_loaded() + + +def test_window_actions_go_through_kdotool_inside_the_session(machine: FakeMachine) -> None: + kde = Kde(machine, "main") + + kde.activate("{a}") + kde.minimize("{a}") + kde.close("{a}") + + assert [inner(command) for command in machine.commands] == [ + "kdotool windowactivate '{a}'", + "kdotool windowminimize '{a}'", + "kdotool windowclose '{a}'", + ] + assert all("WAYLAND_DISPLAY=wayland-main" in command for command in machine.commands) diff --git a/nix/tests/vm/nodes/headless.nix b/nix/tests/vm/nodes/headless.nix index 04655b61..ad6f8ec0 100644 --- a/nix/tests/vm/nodes/headless.nix +++ b/nix/tests/vm/nodes/headless.nix @@ -1,11 +1,13 @@ # A machine with Plasma installed and no login: `kwin_wayland --virtual` runs as the test user's # 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. +# 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. { config, lib, pkgs, + komorebi, ... }: { @@ -37,6 +39,7 @@ kdotool kdePackages.libkscreen kdePackages.qttools + komorebi ]; systemd.user.services = { @@ -63,5 +66,30 @@ ExecStart = "${pkgs.kdePackages.kwin}/bin/kwin_wayland --virtual --socket wayland-%i --no-lockscreen --no-global-shortcuts $KWIN_ARGS"; }; }; + + # Not bound to KWin's unit: a test restarts KWin under a running daemon + "komorebi@" = { + description = "komorebi in the test session %i"; + requires = [ "session-bus@%i.service" ]; + after = [ + "session-bus@%i.service" + "kwin-virtual@%i.service" + ]; + environment = { + DBUS_SESSION_BUS_ADDRESS = "unix:path=%t/session-%i.bus"; + WAYLAND_DISPLAY = "wayland-%i"; + XDG_SESSION_TYPE = "wayland"; + # the log is read by the test, not a terminal + NO_COLOR = "1"; + }; + serviceConfig = { + # the library writes KOMOREBI_ARGS (the log level) before it starts the unit + EnvironmentFile = "-%t/komorebi-%i.env"; + # a log file per run, emptied on every start, which the library reads + ExecStart = "${pkgs.runtimeShell} -c 'exec ${komorebi}/bin/komorebi $${KOMOREBI_ARGS} > %t/komorebi-%i.log 2>&1'"; + # what komorebi exits with when it is told to stop + SuccessExitStatus = 130; + }; + }; }; } diff --git a/nix/tests/vm/suites/kwin-events/default.nix b/nix/tests/vm/suites/kwin-events/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/kwin-events/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/kwin-events/test.py b/nix/tests/vm/suites/kwin-events/test.py new file mode 100644 index 00000000..975dc891 --- /dev/null +++ b/nix/tests/vm/suites/kwin-events/test.py @@ -0,0 +1,119 @@ +# The daemon reads a real KWin through its script. What only a real KWin can tell: that the script +# loads and reports the desktop, that KWin's signals reach the window manager as the events +# `komorebi/src/kwin/state.rs` and `komorebi/tests/wm_events.rs` feed it by hand, in the order KWin +# raised them (KWin activates a new window before it announces it), that the daemon moves nothing +# while its backend only reads, and that it takes its script out of KWin when it stops. +from komorebi_vm import Checks, Kde, daemon +from komorebi_vm.daemon import Event + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(1280, 720), scale=SCALE) + + +def daemon_log() -> str: + return kde.komorebi_log() + + +def handled(event: Event) -> bool: + return event in daemon.events(daemon_log()) + + +kde.spawn("foot -T before sleep 3000") +checks.check( + "a window is open before komorebi starts", + kde.wait_for(lambda: kde.wid("before") != "", timeout=30), +) +before = kde.wid("before") +where_it_opened = kde.rect(before) + +kde.start_komorebi("--log-level", "debug") +checks.check( + "the daemon loaded its script into KWin", + 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 script reported the window that was already open", + kde.wait_for(lambda: "1 valid windows identified" in daemon_log(), timeout=10), +) +checks.check("the daemon is still running", kde.komorebi_running()) + +print("== a window opens") +kde.spawn("foot -T alpha sleep 3000") +checks.check("KWin has it", kde.wait_for(lambda: kde.wid("alpha") != "", timeout=30)) +alpha = kde.wid("alpha") +checks.check( + "KWin's focus on it reached the daemon, by title", + kde.wait_for(lambda: "alpha" in daemon.window_ids(daemon_log()), timeout=10), +) +ids = daemon.window_ids(daemon_log()) +n = ids.get("alpha", -1) +shown = Event("Show", n, "WindowAdded") +focused = Event("FocusChange", n, "WindowActivated") +checks.check("the daemon handled a Show for it", kde.wait_for(lambda: handled(shown), timeout=10)) +checks.check("... and a FocusChange", kde.wait_for(lambda: handled(focused), timeout=10)) +seen = daemon.events(daemon_log()) +checks.check( + "the Show came first, although KWin activates a window before it announces it", + shown in seen and focused in seen and seen.index(shown) < seen.index(focused), +) + +print("== the focus moves") +kde.activate(before) +checks.check( + "the window that was open before is focused, and the daemon knows it", + kde.wait_for(lambda: "before" in daemon.window_ids(daemon_log()), timeout=10), +) +m = daemon.window_ids(daemon_log()).get("before", -1) +checks.check( + "a FocusChange for it", + kde.wait_for(lambda: handled(Event("FocusChange", m, "WindowActivated")), timeout=10), +) + +print("== minimize, restore, close") +kde.minimize(alpha) +checks.check( + "minimizing is a Minimize", + kde.wait_for(lambda: handled(Event("Minimize", n, "WindowMinimized")), timeout=10), +) +kde.activate(alpha) +checks.check( + "activating a minimized window brings it back: a Restore", + kde.wait_for(lambda: handled(Event("Restore", n, "WindowRestored")), timeout=10), +) +kde.close(alpha) +checks.check( + "closing is a Destroy", + kde.wait_for(lambda: handled(Event("Destroy", n, "WindowRemoved")), timeout=10), +) +mine = [e.kind for e in daemon.events(daemon_log()) if e.window == n] +print(f" the events of alpha, in order: {mine}") +in_order = [kind for kind in mine if kind in ("Show", "Minimize", "Restore", "Destroy")] +checks.check( + "alpha's events came in the order they happened", + in_order == ["Show", "Minimize", "Restore", "Destroy"], +) + +print("== nothing was moved") +checks.check( + "the daemon asked to tile, and was told the backend only reads", + "the KWin backend only reads the desktop" in daemon_log(), +) +checks.check( + "the window that was open before is where KWin put it", kde.rect(before) == where_it_opened +) + +print("== stop") +kde.stop_komorebi() +checks.check("the daemon exited", not kde.komorebi_running()) +checks.check( + "the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded(), timeout=10) +) +checks.check("the windows are still there", kde.wid("before") != "") + +kde.stop() +checks.finish()