From 426409fcfc839c739da87e50fcc9994e85efaf89 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 09:11:25 -0700 Subject: [PATCH 001/255] chore(repo): a workspace of two crates komorebi for KDE is built up as a Cargo workspace with one crate per concern, the way komorebi and komorebi for Mac are. The first two crates are the `komorebi` daemon, which does nothing yet but report its version, and `version`, which owns the string every binary of the workspace reports. `version` reads the commit from git when HEAD is on a branch, and from COMMIT_HASH otherwise. A jj workspace leaves HEAD detached, so `.cargo/config.toml` defaults the variable to `unknown` (nix will set the real commit), and a plain `cargo build` in a jj checkout compiles. The tooling files come from komorebi for Mac: the licence, deny.toml (trimmed to the licences in use), rustfmt.toml and the toolchain file. `just check` runs the formatting check, clippy and rustdoc with warnings denied, and the tests. rustfmt.toml uses an unstable option, so formatting needs a nightly rustfmt. The `rg` calls in `just lint` name a path because rg reads stdin when it is given none and stdin is not a terminal. The README and CONTRIBUTING.md say how to run, check and commit. --- .cargo/config.toml | 5 + .gitignore | 4 + CONTRIBUTING.md | 64 +++ Cargo.lock | 1025 +++++++++++++++++++++++++++++++++++++ Cargo.toml | 14 + LICENSE.md | 108 ++++ README.md | 36 ++ deny.toml | 37 ++ justfile | 21 + komorebi/Cargo.toml | 10 + komorebi/src/main.rs | 15 + komorebi/tests/version.rs | 18 + rust-toolchain.toml | 2 + rustfmt.toml | 1 + version/Cargo.toml | 10 + version/build.rs | 40 ++ version/src/lib.rs | 33 ++ 17 files changed, 1443 insertions(+) create mode 100644 .cargo/config.toml create mode 100644 .gitignore create mode 100644 CONTRIBUTING.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 deny.toml create mode 100644 justfile create mode 100644 komorebi/Cargo.toml create mode 100644 komorebi/src/main.rs create mode 100644 komorebi/tests/version.rs create mode 100644 rust-toolchain.toml create mode 100644 rustfmt.toml create mode 100644 version/Cargo.toml create mode 100644 version/build.rs create mode 100644 version/src/lib.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 00000000..ffba5900 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,5 @@ +[env] +# The version crate reads the commit from git when HEAD is on a branch, and from +# this variable otherwise (a detached HEAD, which jj leaves, or a build with no +# .git directory). Nix sets the real commit, which takes precedence over this. +COMMIT_HASH = "unknown" diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..181f029f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target +/result* +/.direnv +/.vm diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..7a7d3d34 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,64 @@ +# Contributing to the Project + +The project is a collection of contributions from both the project leaders and +community members. There are many ways to contribute, this can include content +in the project repositories, as well as contributing in public and private +conversation, assisting users, writing blog posts, and many other ways. + +## How contributions are made + +Contributions to the project primarily happen in the project source +repositories, but may also occur in other places, such as discussion forums and +public and private discourse. + +## Contributing content to the Project + +In order for the project leaders to manage sustained progress toward the +project goals and maintain project velocity, focus and quality, the project may +adjust the license terms over time. + +Content contributed to the project must therefore be provided under +sufficiently liberal terms to allow these operations to proceed unimpeded. As +such contributions are accepted with the following understanding: + +* Contributed content is licensed under the terms of the 0-BSD license +* Contributors accept the terms of the project license at the time of + contribution + +By making a contribution, you accept both the current project license terms, +and that all contributions that you have made are provided under the terms of +the 0-BSD license. + +## Working on the code + +`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. Formatting needs a nightly `rustfmt`, because +[`rustfmt.toml`](rustfmt.toml) uses an unstable option; `just fmt` applies it. + +## Commits + +Commit messages follow the +[Conventional Commits](https://www.conventionalcommits.org/) specification: +`type(scope): description`. The scope is the Rust module the change is in +(`wm`, `kwin`, `layouts`), `repo` for repository files and markdown, `nix` for +the flake and `github` for workflows. Every line of a message, the header +included, is at most 80 columns, and the body says why the change is made. + +Documentation lands in the commit that changes the behavior it describes, not +in a later one. + +## Zero-Clause BSD + +```text +Permission to use, copy, modify, and/or distribute this software for +any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE +FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY +DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +``` \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..72b77353 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1025 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", + "terminal_size", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "const_format" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3decb4d6965448659923544a634a0571ba44cede4e11ef15a5a317126840454" +dependencies = [ + "const_format_proc_macros", + "konst", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "941b570269a642506f08cb5b688c04bfa6cfd41a26f8bcdc49db8fd00c0ab659" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "git2" +version = "0.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b88256088d75a56f8ecfa070513a775dd9107f6530ef14919dac831af9cfe2b" +dependencies = [ + "bitflags", + "libc", + "libgit2-sys", + "log", + "url", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "is_debug" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fe266d2e243c931d8190177f20bf7f24eed45e96f39e87dc49a27b32d12d407" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "komorebi" +version = "0.1.0" +dependencies = [ + "clap", + "version", +] + +[[package]] +name = "konst" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" +dependencies = [ + "konst_macro_rules", +] + +[[package]] +name = "konst_macro_rules" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libgit2-sys" +version = "0.18.8+1.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f7c568b25d7489bc3fb2988ed69ab111d2944d2f5fec3d5c987fe545ea97b50" +dependencies = [ + "cc", + "libc", + "libz-sys", + "pkg-config", +] + +[[package]] +name = "libz-sys" +version = "1.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f710a23e6dbf193214fd46ca56a9d6864e550abe86202184532ae7275e46de19" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "shadow-rs" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c798acfc78a69c7b038adde44084d8df875555b091da42c90ae46257cdcc41a" +dependencies = [ + "const_format", + "git2", + "is_debug", + "time", + "tzdb", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "terminal_size" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" +dependencies = [ + "rustix", + "windows-sys", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tz-rs" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fc6c929ffa10fb34f4a3c7e9a73620a83ef2e85e47f9ec3381b8289e6762f42" + +[[package]] +name = "tzdb" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d4e985b6dda743ae7fd4140c28105316ffd75bc58258ee6cc12934e3eb7a0c" +dependencies = [ + "iana-time-zone", + "tz-rs", + "tzdb_data", +] + +[[package]] +name = "tzdb_data" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "febaa995f6852367564e16c3369988b99d471d43ed12b1255b8d294661797f1c" +dependencies = [ + "tz-rs", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version" +version = "0.1.0" +dependencies = [ + "shadow-rs", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..f3c18759 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,14 @@ +[workspace] + +resolver = "2" +members = ["komorebi", "version"] + +[workspace.package] +version = "0.1.0" + +[workspace.dependencies] +clap = { version = "4", features = ["derive", "wrap_help"] } +shadow-rs = "1" + +[workspace.metadata.crane] +name = "komorebi-workspace" diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..8796dd2f --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,108 @@ +# Komorebi License + +Version 2.0.0 + +## Acceptance + +In order to get any license under these terms, you must agree +to them as both strict obligations and conditions to all +your licenses. + +## Copyright License + +The licensor grants you a copyright license for the software +to do everything you might do with the software that would +otherwise infringe the licensor's copyright in it for any +permitted purpose. However, you may only distribute the source +code of the software according to the [Distribution License]( +#distribution-license), you may only make changes according +to the [Changes License](#changes-license), and you may not +otherwise distribute the software or new works based on the +software. + +## Distribution License + +The licensor grants you an additional copyright license to +distribute copies of the source code of the software. Your +license to distribute covers distributing the source code of +the software with changes permitted by the [Changes License]( +#changes-license). + +## Changes License + +The licensor grants you an additional copyright license to +make changes for any permitted purpose. + +## Patent License + +The licensor grants you a patent license for the software that +covers patent claims the licensor can license, or becomes able +to license, that you would infringe by using the software. + +## Personal Uses + +Personal use for research, experiment, and testing for +the benefit of public knowledge, personal study, private +entertainment, hobby projects, amateur pursuits, or religious +observance, without any anticipated commercial application, +is use for a permitted purpose. + +## Fair Use + +You may have "fair use" rights for the software under the +law. These terms do not limit them. + +## No Other Rights + +These terms do not allow you to sublicense or transfer any of +your licenses to anyone else, or prevent the licensor from +granting licenses to anyone else. These terms do not imply +any other licenses. + +## Patent Defense + +If you make any written claim that the software infringes or +contributes to infringement of any patent, your patent license +for the software granted under these terms ends immediately. If +your company makes such a claim, your patent license ends +immediately for work on behalf of your company. + +## Violations + +The first time you are notified in writing that you have +violated any of these terms, or done anything with the software +not covered by your licenses, your licenses can nonetheless +continue if you come into full compliance with these terms, +and take practical steps to correct past violations, within +32 days of receiving notice. Otherwise, all your licenses +end immediately. + +## No Liability + +***As far as the law allows, the software comes as is, without +any warranty or condition, and the licensor will not be liable +to you for any damages arising out of these terms or the use +or nature of the software, under any kind of legal claim.*** + +## Definitions + +The **licensor** is the individual or entity offering these +terms, and the **software** is the software the licensor makes +available under these terms. + +**You** refers to the individual or entity agreeing to these +terms. + +**Your company** is any legal entity, sole proprietorship, +or other kind of organization that you work for, plus all +organizations that have control over, are under the control of, +or are under common control with that organization. **Control** +means ownership of substantially all the assets of an entity, +or the power to direct its management and policies by vote, +contract, or otherwise. Control can be direct or indirect. + +**Your licenses** are all the licenses granted to you for the +software under these terms. + +**Use** means anything you do with the software requiring one +of your licenses. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 00000000..0147a807 --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +# komorebi for KDE + +A tiling window manager for KDE Plasma on Wayland, in the family of +[komorebi](https://github.com/LGUG2Z/komorebi) for Windows and +[komorebi for Mac](https://github.com/LGUG2Z/komorebi-for-mac). The daemon +decides where each window goes, and KWin, the window manager of Plasma, does the +moving and the drawing. + +## Running it locally + +```sh +cargo run --bin komorebi --locked -- --version +``` + +The `rust-toolchain.toml` at the root selects the Rust toolchain. + +## Crates + +- [`komorebi`](komorebi): the daemon. +- [`version`](version): the version string every binary reports. + +## Checks + +`just check` runs the formatting check, clippy with warnings denied, the tests +and rustdoc with warnings denied. Formatting needs a nightly `rustfmt`, because +[`rustfmt.toml`](rustfmt.toml) uses an unstable option. + +## Documentation + +`cargo doc --workspace --no-deps --open` builds the API documentation. +[`CONTRIBUTING.md`](CONTRIBUTING.md) says how to work on the code. + +## License + +komorebi for KDE is under the [Komorebi License](LICENSE.md). Contributions +are accepted under the terms in [`CONTRIBUTING.md`](CONTRIBUTING.md). diff --git a/deny.toml b/deny.toml new file mode 100644 index 00000000..241fefff --- /dev/null +++ b/deny.toml @@ -0,0 +1,37 @@ +[graph] +targets = [ + "x86_64-unknown-linux-gnu", + "aarch64-unknown-linux-gnu", + "aarch64-apple-darwin", +] +all-features = false +no-default-features = false + +[output] +feature-depth = 1 + +[licenses] +allow = ["Apache-2.0", "MIT", "Unicode-3.0", "Zlib", "LicenseRef-Komorebi-2.0"] +confidence-threshold = 0.8 + +[[licenses.clarify]] +crate = "komorebi" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[[licenses.clarify]] +crate = "version" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + +[bans] +multiple-versions = "allow" +wildcards = "allow" +highlight = "all" +workspace-default-features = "allow" +external-default-features = "allow" + +[sources] +unknown-registry = "deny" +unknown-git = "deny" +allow-registry = ["https://github.com/rust-lang/crates.io-index"] diff --git a/justfile b/justfile new file mode 100644 index 00000000..50230bb6 --- /dev/null +++ b/justfile @@ -0,0 +1,21 @@ +export RUST_BACKTRACE := "full" + +# format the Rust sources (needs a nightly rustfmt: rustfmt.toml uses unstable options) +fmt: + cargo fmt + +# everything a change has to pass before it is pushed +check: lint + 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 macros the codebase has agreed not to use +lint: + test -z "$(rg 'eyre!' --type rust .)" || (echo "eyre! macro not allowed"; false) + test -z "$(rg 'dbg!' --type rust .)" || (echo "dbg! macro not allowed"; false) + test -z "$(rg 'println!' --type rust ./komorebi/src)" || (echo "println! macro not allowed"; false) + +run target *args: + cargo run --bin {{ target }} --locked -- {{ args }} diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml new file mode 100644 index 00000000..57dd1555 --- /dev/null +++ b/komorebi/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "komorebi" +version.workspace = true +description = "A tiling window manager for KDE Plasma" +edition = "2024" + +[dependencies] +version = { path = "../version" } + +clap = { workspace = true } diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs new file mode 100644 index 00000000..6fe29ec1 --- /dev/null +++ b/komorebi/src/main.rs @@ -0,0 +1,15 @@ +//! The komorebi daemon: a tiling window manager for KDE Plasma. +//! +//! The daemon owns the layout of every window and asks KWin, the window +//! manager of Plasma, to put each one where the layout says. + +use clap::Parser; + +/// A tiling window manager for KDE Plasma. +#[derive(Parser)] +#[clap(author, about, version = version::LONG_VERSION)] +struct Opts {} + +fn main() { + Opts::parse(); +} diff --git a/komorebi/tests/version.rs b/komorebi/tests/version.rs new file mode 100644 index 00000000..e5d7e05e --- /dev/null +++ b/komorebi/tests/version.rs @@ -0,0 +1,18 @@ +//! `komorebi --version` reports the workspace version. + +use std::process::Command; + +#[test] +fn reports_the_package_version() { + let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) + .arg("--version") + .output() + .expect("komorebi runs"); + + assert!(output.status.success()); + + let stdout = String::from_utf8(output.stdout).expect("utf-8 output"); + let expected = format!("komorebi {}", env!("CARGO_PKG_VERSION")); + + assert_eq!(stdout.lines().next(), Some(expected.as_str())); +} diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 00000000..292fe499 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "stable" diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..63df91e0 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +imports_granularity = "Item" diff --git a/version/Cargo.toml b/version/Cargo.toml new file mode 100644 index 00000000..ac610fad --- /dev/null +++ b/version/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "version" +edition = "2024" +version.workspace = true + +[dependencies] +shadow-rs = { workspace = true } + +[build-dependencies] +shadow-rs = { workspace = true } diff --git a/version/build.rs b/version/build.rs new file mode 100644 index 00000000..1b80c0a1 --- /dev/null +++ b/version/build.rs @@ -0,0 +1,40 @@ +use std::fs::File; +use std::io::Write; + +use shadow_rs::SdResult; +use shadow_rs::ShadowBuilder; + +fn main() { + let shadow_build = ShadowBuilder::builder().hook(raw_hook).build().unwrap(); + + let is_flake_build = shadow_build + .map + .get("BRANCH") + .map_or_else(|| true, |entry| entry.v.is_empty()); + + if is_flake_build { + ShadowBuilder::builder().hook(flake_hook).build().unwrap(); + } +} + +const RAW_VERSION_CONST: &str = r##"pub const LONG_VERSION:&str = shadow_rs::formatcp!(r#"{} +branch:{} +commit_hash:{} +build_env:{},{}"#,PKG_VERSION, BRANCH, COMMIT_HASH, RUST_VERSION, RUST_CHANNEL +); +"##; + +fn raw_hook(mut file: &File) -> SdResult<()> { + writeln!(file, "{RAW_VERSION_CONST}")?; + Ok(()) +} + +const FLAKE_VERSION_CONST: &str = r##"pub const LONG_VERSION:&str = shadow_rs::formatcp!(r#"{} +commit_hash:{} +build_env:{},{}"#,PKG_VERSION, env!("COMMIT_HASH"), RUST_VERSION, RUST_CHANNEL +);"##; + +fn flake_hook(mut file: &File) -> SdResult<()> { + writeln!(file, "{FLAKE_VERSION_CONST}")?; + Ok(()) +} diff --git a/version/src/lib.rs b/version/src/lib.rs new file mode 100644 index 00000000..0746a915 --- /dev/null +++ b/version/src/lib.rs @@ -0,0 +1,33 @@ +//! The version string every komorebi binary reports. +//! +//! [`LONG_VERSION`] is the package version followed by the commit the binary +//! was built from and the Rust toolchain that built it. The binaries pass it to +//! their command line parsers, so `komorebi --version` and +//! `komorebic --version` report the same thing. +//! +//! # Where the commit comes from +//! +//! A build from a git checkout whose `HEAD` is on a branch asks git for the +//! branch and the commit. Any other build has nothing to ask: a detached `HEAD` +//! (which is what a jj workspace leaves), a source tree with no `.git` +//! directory, or a sandboxed nix build. Such a build reads the commit from the +//! `COMMIT_HASH` environment variable, and does not compile without it. +//! [`.cargo/config.toml`](https://github.com/LGUG2Z/komorebi-for-kde/blob/master/.cargo/config.toml) +//! defaults the variable to `unknown`, and nix sets it to the real commit. + +shadow_rs::shadow!(build); + +/// The package version, the commit and the toolchain of this build, one per +/// line. +/// +/// The first line is the package version, which every crate in the workspace +/// shares. +/// +/// # Example +/// +/// ```rust +/// let first_line = version::LONG_VERSION.lines().next(); +/// +/// assert_eq!(first_line, Some(env!("CARGO_PKG_VERSION"))); +/// ``` +pub use build::LONG_VERSION; From 9524b777b3279248247fafeff67818266bec7d8a Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 09:12:22 -0700 Subject: [PATCH 002/255] build(nix): build and check on Linux and macOS The flake builds the workspace with crane and checks it the way `just check` does, so that CI and a laptop run the same things: `komorebi-workspace-fmt` (nightly rustfmt, since rustfmt.toml uses unstable options), `-clippy` with warnings denied, `-doc` with rustdoc warnings denied, `-toml-fmt`, `-deny` and `-nextest`. Treefmt and a pre-commit hook format Rust, Nix, TOML and the justfile. `nix develop` gives a toolchain with the nightly rustfmt, cargo-deny, nextest and udeps. Linux is where komorebi runs, so only Linux gets packages and the overlay. An Apple silicon Mac gets the dev shell, the formatter and the checks; the tests there run against the fake desktop that arrives with the backend trait. x86_64-darwin is left out because nixpkgs 26.11 dropped it, and the flake follows the tip of nixpkgs-unstable. The commit hash is a constant (`nix-check`) for the dependencies and for every check, and the real one only goes into the final build. The version crate reads it with `env!`, so putting it in the shared arguments would rebuild the dependencies and rerun every check for each commit. The README and CONTRIBUTING.md describe `nix develop` and `nix flake check`. --- .envrc | 1 + CONTRIBUTING.md | 10 ++- README.md | 14 ++- flake.lock | 157 +++++++++++++++++++++++++++++++++ flake.nix | 225 ++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 402 insertions(+), 5 deletions(-) create mode 100644 .envrc create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/.envrc b/.envrc new file mode 100644 index 00000000..8392d159 --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7a7d3d34..7574fec0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,10 +31,16 @@ the 0-BSD license. ## Working on the code +`nix develop` (or [direnv](https://direnv.net), through the [`.envrc`](.envrc)) +provides the Rust toolchain, a nightly `rustfmt` and the tools the checks use. +[`rustfmt.toml`](rustfmt.toml) uses an unstable option, which is why the +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. Formatting needs a nightly `rustfmt`, because -[`rustfmt.toml`](rustfmt.toml) uses an unstable option; `just fmt` applies it. +warnings denied. `just fmt` formats the Rust sources, and `nix fmt` every file +type the repository has. `nix flake check` is what CI runs; it builds the same +checks, plus `cargo deny`, as derivations. ## Commits diff --git a/README.md b/README.md index 0147a807..883344a9 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,15 @@ moving and the drawing. ## Running it locally ```sh +nix develop cargo run --bin komorebi --locked -- --version ``` -The `rust-toolchain.toml` at the root selects the Rust toolchain. +`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 +use. With [direnv](https://direnv.net), the [`.envrc`](.envrc) does it on +`cd`. On Linux, `nix run .#komorebi -- --version` builds and runs the daemon +without a checkout of the toolchain. ## Crates @@ -22,8 +27,11 @@ The `rust-toolchain.toml` at the root selects the Rust toolchain. ## Checks `just check` runs the formatting check, clippy with warnings denied, the tests -and rustdoc with warnings denied. Formatting needs a nightly `rustfmt`, because -[`rustfmt.toml`](rustfmt.toml) uses an unstable option. +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. A Mac +runs the tests against the fake desktop, since KWin only exists on Linux. +`nix fmt` formats every file the checks look at. ## Documentation diff --git a/flake.lock b/flake.lock new file mode 100644 index 00000000..4c760a2d --- /dev/null +++ b/flake.lock @@ -0,0 +1,157 @@ +{ + "nodes": { + "crane": { + "locked": { + "lastModified": 1792350552, + "narHash": "sha256-292lvpvxTGKryKxh3/3tcIVi85CwYGdl4oOi113Sob8=", + "owner": "ipetkov", + "repo": "crane", + "rev": "e675a36b7377bebe41d548388a2501cbb16d380d", + "type": "github" + }, + "original": { + "owner": "ipetkov", + "repo": "crane", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1767039857, + "narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=", + "owner": "NixOS", + "repo": "flake-compat", + "rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-parts": { + "inputs": { + "nixpkgs-lib": "nixpkgs-lib" + }, + "locked": { + "lastModified": 1790898470, + "narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "024633cd702b10285db5cb19b40ad48d2399ba60", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "git-hooks-nix": { + "inputs": { + "flake-compat": "flake-compat", + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1791909798, + "narHash": "sha256-VAhpCOmrun/KXimYfR8NM88bciKCui7CqHHhThSzgag=", + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "1ba1dbfe28738c9a71c266be6efa5b89e75491a9", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "git-hooks.nix", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1792842277, + "narHash": "sha256-pGPnZGi8y9d76xNeracniXO3dsYVROEmMkMc8jD0Ihc=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "d3b13ad75cc492690728f9307e443dec9ef9a20e", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs-lib": { + "locked": { + "lastModified": 1790477367, + "narHash": "sha256-oujbxmVKDhci2E4EM3KyAbRUgp5/IsCoiA/LfEF7OOk=", + "owner": "nix-community", + "repo": "nixpkgs.lib", + "rev": "f7cd230690d9fc982d06129f9189b101fddcfa3b", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixpkgs.lib", + "type": "github" + } + }, + "root": { + "inputs": { + "crane": "crane", + "flake-parts": "flake-parts", + "git-hooks-nix": "git-hooks-nix", + "nixpkgs": "nixpkgs", + "rust-overlay": "rust-overlay", + "treefmt-nix": "treefmt-nix" + } + }, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1793086596, + "narHash": "sha256-ObKS44vw4IIVpQ69YJzUGjZ0IwnpWoUlwjJSY7gefdo=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "c7e9d512653a35ef4d5879c3df4d44d7b78d0e6d", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + }, + "treefmt-nix": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1791885023, + "narHash": "sha256-C3alQ2MEt0zVrUSho5NUDo3jmhbff72++bfwoqT9Omo=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "0d6d739a833ba9a9c93034862e4a7b061a062a1c", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 00000000..7a4f69af --- /dev/null +++ b/flake.nix @@ -0,0 +1,225 @@ +{ + description = "komorebi for KDE Plasma"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + flake-parts.url = "github:hercules-ci/flake-parts"; + crane.url = "github:ipetkov/crane"; + rust-overlay.url = "github:oxalica/rust-overlay"; + rust-overlay.inputs.nixpkgs.follows = "nixpkgs"; + treefmt-nix.url = "github:numtide/treefmt-nix"; + treefmt-nix.inputs.nixpkgs.follows = "nixpkgs"; + git-hooks-nix.url = "github:cachix/git-hooks.nix"; + git-hooks-nix.inputs.nixpkgs.follows = "nixpkgs"; + }; + + outputs = + inputs@{ + self, + nixpkgs, + flake-parts, + crane, + rust-overlay, + ... + }: + let + mkPkgs = + system: + import nixpkgs { + inherit system; + overlays = [ (import rust-overlay) ]; + }; + + mkKomorebiPackages = + { pkgs }: + let + toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; + craneLib = (crane.mkLib pkgs).overrideToolchain toolchain; + # rustfmt.toml uses options only a nightly rustfmt knows + craneLibFmt = (crane.mkLib pkgs).overrideToolchain ( + pkgs.rust-bin.nightly.latest.minimal.override { extensions = [ "rustfmt" ]; } + ); + + src = craneLib.cleanCargoSource ./.; + + commonArgs = { + inherit src; + pname = "komorebi-workspace"; + version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).workspace.package.version; + strictDeps = true; + # The version crate wants a commit at compile time. It is a constant here, so that the + # dependencies and every check are the same derivations for every commit; only the final + # build below knows the real one. + COMMIT_HASH = "nix-check"; + }; + + cargoArtifacts = craneLib.buildDepsOnly commonArgs; + + individualCrateArgs = commonArgs // { + inherit cargoArtifacts; + doCheck = false; + doDoc = false; + }; + + fullBuild = craneLib.buildPackage ( + individualCrateArgs + // { + COMMIT_HASH = self.rev or (pkgs.lib.removeSuffix "-dirty" self.dirtyRev); + } + ); + + extractBinary = + binaryName: + pkgs.runCommand "komorebi-${binaryName}" { meta = fullBuild.meta // { }; } '' + mkdir -p $out/bin + cp ${fullBuild}/bin/${binaryName} $out/bin/ + ''; + in + { + inherit + craneLib + craneLibFmt + src + commonArgs + individualCrateArgs + fullBuild + ; + komorebi = extractBinary "komorebi"; + }; + in + flake-parts.lib.mkFlake { inherit inputs; } { + # Linux is what komorebi runs on. An Apple silicon Mac gets the dev shell, the formatter and the + # checks, which run the same tests against the fake desktop. nixpkgs dropped x86_64-darwin in + # 26.11. + systems = [ + "aarch64-linux" + "x86_64-linux" + "aarch64-darwin" + ]; + + imports = [ + inputs.treefmt-nix.flakeModule + inputs.git-hooks-nix.flakeModule + ]; + + perSystem = + { + config, + lib, + system, + ... + }: + let + pkgs = mkPkgs system; + build = mkKomorebiPackages { inherit pkgs; }; + nightlyRustfmt = pkgs.rust-bin.nightly.latest.rustfmt; + nightlyToolchain = pkgs.rust-bin.nightly.latest.default; + rustToolchainWithNightlyRustfmt = pkgs.symlinkJoin { + name = "rust-toolchain-with-nightly-rustfmt"; + paths = [ + nightlyRustfmt + (pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml) + ]; + }; + # cargo-udeps needs a nightly compiler + cargo-udeps = pkgs.writeShellScriptBin "cargo-udeps" '' + export PATH="${nightlyToolchain}/bin:$PATH" + exec ${pkgs.cargo-udeps}/bin/cargo-udeps "$@" + ''; + in + { + treefmt = { + projectRootFile = "flake.nix"; + programs = { + deadnix.enable = true; + just.enable = true; + nixfmt.enable = true; + taplo.enable = true; + rustfmt = { + enable = true; + package = nightlyRustfmt; + }; + }; + }; + + checks = { + komorebi-workspace-fmt = build.craneLibFmt.cargoFmt { inherit (build) src; }; + + komorebi-workspace-clippy = build.craneLib.cargoClippy ( + build.individualCrateArgs + // { + cargoClippyExtraArgs = "--workspace --all-targets -- -D warnings"; + } + ); + + komorebi-workspace-doc = build.craneLib.cargoDoc ( + build.individualCrateArgs + // { + cargoDocExtraArgs = "--workspace --no-deps"; + env.RUSTDOCFLAGS = "-D warnings"; + } + ); + + komorebi-workspace-toml-fmt = build.craneLib.taploFmt { + src = lib.sources.sourceFilesBySuffices build.src [ ".toml" ]; + }; + + komorebi-workspace-deny = build.craneLib.cargoDeny { inherit (build) src; }; + + komorebi-workspace-nextest = build.craneLib.cargoNextest ( + build.individualCrateArgs // { doCheck = true; } + ); + }; + + packages = lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { + inherit (build) komorebi; + komorebi-full = build.fullBuild; + default = build.fullBuild; + }; + + apps = lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { + komorebi = { + type = "app"; + program = "${build.komorebi}/bin/komorebi"; + meta.description = "The komorebi daemon"; + }; + default = config.apps.komorebi; + }; + + devShells.default = pkgs.mkShell { + name = "komorebi"; + + RUST_BACKTRACE = "full"; + + inputsFrom = [ build.fullBuild ]; + + packages = [ + rustToolchainWithNightlyRustfmt + cargo-udeps + + pkgs.cargo-deny + pkgs.cargo-nextest + pkgs.jq + pkgs.just + pkgs.ripgrep + ]; + }; + + pre-commit = { + check.enable = true; + settings.hooks.treefmt = { + enable = true; + package = config.treefmt.build.wrapper; + pass_filenames = false; + }; + }; + }; + + flake = { + overlays.default = final: _: { + inherit ((mkKomorebiPackages { pkgs = mkPkgs final.stdenv.hostPlatform.system; })) komorebi; + }; + overlays.komorebi = self.overlays.default; + }; + }; +} From 3a20a60823a13b8e20e9b2588cae4b0922f57aa6 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 09:17:51 -0700 Subject: [PATCH 003/255] ci(github): check with nix on every push `ci.yaml` runs two jobs on GitHub-hosted runners, gated on the repository name so that forks do not run them. `cargo-deny` checks licenses, advisories and sources. `lint` runs `nix flake check`, which builds every check of the flake, and the repository's own macro rules from the justfile. The triggers are the ones komorebi for Mac uses: pull requests, pushes to master, feature and hotfix branches, version tags, a weekly schedule and a manual run. The Nix store is cached with cache-nix-action, which needs no account. komorebi follows the tip of nixpkgs-unstable, so `flake.lock` moves, and KWin with it. `update-flake-lock.yaml` opens a pull request each week with the title `chore(deps): flake.lock: Update`; the same jobs run on it, which is what says whether the new KWin still works. Dependabot keeps the actions and the crates up to date, and the pull request template carries over from komorebi for Mac. CONTRIBUTING.md describes what CI runs. --- .github/dependabot.yml | 21 +++++++++++ .github/pull_request_template.md | 7 ++++ .github/workflows/ci.yaml | 46 ++++++++++++++++++++++++ .github/workflows/update-flake-lock.yaml | 25 +++++++++++++ CONTRIBUTING.md | 9 +++++ 5 files changed, 108 insertions(+) create mode 100644 .github/dependabot.yml create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/ci.yaml create mode 100644 .github/workflows/update-flake-lock.yaml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..92e09e76 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,21 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + assignees: + - "LGUG2Z" + commit-message: + prefix: chore + include: scope + + - package-ecosystem: "cargo" + directory: "/" + schedule: + interval: "weekly" + assignees: + - "LGUG2Z" + commit-message: + prefix: chore + include: scope \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..5059bfde --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,7 @@ + diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 00000000..b84c775b --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,46 @@ +# Every job is gated on the repository, so that a fork does not run them on its own runners. + +name: ci + +on: + pull_request: + branches: + - "*" + push: + branches: + - master + - feature/* + - hotfix/* + tags: + - v* + schedule: + - cron: "30 0 * * 0" # Every Sunday at 00:30 UTC + workflow_dispatch: + +jobs: + cargo-deny: + if: github.repository == 'LGUG2Z/komorebi-for-kde' + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: EmbarkStudios/cargo-deny-action@v2 + + # Everything that does not need a virtual machine: the formatting, clippy, rustdoc and the tests, + # as derivations. The jobs that boot KWin are separate. + lint: + if: github.repository == 'LGUG2Z/komorebi-for-kde' + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: cachix/install-nix-action@v31 + - uses: nix-community/cache-nix-action@v7 + with: + primary-key: nix-${{ runner.os }}-${{ hashFiles('flake.lock', '**/Cargo.lock') }} + restore-prefixes-first-match: nix-${{ runner.os }}- + gc-max-store-size-linux: 8G + - run: nix flake check -L + - run: nix develop --command just lint diff --git a/.github/workflows/update-flake-lock.yaml b/.github/workflows/update-flake-lock.yaml new file mode 100644 index 00000000..8507438e --- /dev/null +++ b/.github/workflows/update-flake-lock.yaml @@ -0,0 +1,25 @@ +# komorebi tracks the tip of nixpkgs-unstable, so the lock moves every week. The pull request runs +# the same jobs as any other, which is what says whether the new KWin still works. + +name: update-flake-lock + +on: + schedule: + - cron: "0 3 * * 1" # Every Monday at 03:00 UTC + workflow_dispatch: + +jobs: + update: + if: github.repository == 'LGUG2Z/komorebi-for-kde' + runs-on: ubuntu-24.04 + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v7 + - uses: cachix/install-nix-action@v31 + - uses: DeterminateSystems/update-flake-lock@v29 + with: + commit-msg: "chore(deps): flake.lock: Update" + pr-title: "chore(deps): flake.lock: Update" + pr-assignees: LGUG2Z diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7574fec0..2b129d43 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -42,6 +42,15 @@ warnings denied. `just fmt` formats the Rust sources, and `nix fmt` every file type the repository has. `nix flake check` is what CI runs; it builds the same checks, plus `cargo deny`, as derivations. +## Continuous integration + +[`ci.yaml`](.github/workflows/ci.yaml) runs on every pull request and on every +push to `master`, `feature/*` and `hotfix/*`, in this repository only. The +`lint` job runs `nix flake check` and the repository's own lint rules, and +`cargo-deny` checks licenses and advisories. A weekly +[workflow](.github/workflows/update-flake-lock.yaml) opens a pull request that +moves `flake.lock`, and the same jobs run on it. + ## Commits Commit messages follow the From 3c51b9b4bf49d9b8d0b80e159b18aa34870c7e93 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 09:29:51 -0700 Subject: [PATCH 004/255] build(nix): a NixOS test framework for headless KWin The unit tests run against a fake desktop and cannot say whether KWin does what the daemon asks. This adds the other half: NixOS machines with Plasma in them, a real KWin, and a Python library to drive it. Every directory under `nix/tests/vm/suites` is a test. The generator lists the directory, so a new suite appears as `checks..vm-NAME` on Linux and as `legacyPackages..vm.NAME` everywhere, with no edit to the flake. A suite names its tier and its node and has a `test.py`; `legacyPackages..vmTiers` lists the names of each tier as JSON for the CI matrix, `vmGuests` the guests to build on a Linux builder, and `vmTcg` the same suites for a machine with no KVM. `scale` multiplies every wait: 1 for KVM, 1.5 for HVF, 8 for TCG. The headless node runs `kwin_wayland --virtual` as user units of a lingering user, one pair of units per session (`session-bus@NAME`, `kwin-virtual@NAME`), so a test can run several sessions with their own bus and socket. A virtual KWin has no output to draw on, so anything that needs pixels or a pointer needs the session node. The library, `komorebi_vm`, has `Checks` (counted checks that fail once, at the end) and `Kde` (start a session, run clients and tools inside it, read windows through kdotool, poll with `wait_for`). It depends on a small `Machine` protocol rather than on the test driver. The `vm-lib` check runs its unit tests against a fake machine, with ruff and ty. The driver type checks each `test.py` with ty, which is how a protocol that did not match `QemuMachine.execute` was caught. `vm-kwin` starts a KWin with two outputs, spawns a foot window, reads it back, starts a second session and checks that it cannot see the first. On a Mac the guest is built on a Linux builder and the driver run directly, because the macOS nix sandbox cannot give QEMU the hypervisor: `scripts/vm-mac`, `just vm NAME`. docs/dev/vm-tests.md covers this, adding a test, and the builder. --- .github/pull_request_template.md | 5 + CONTRIBUTING.md | 7 + README.md | 7 +- docs/dev/vm-tests.md | 116 ++++++++++++++ flake.nix | 35 +++++ justfile | 20 +++ nix/tests/vm/default.nix | 100 +++++++++++++ nix/tests/vm/lib/komorebi_vm/__init__.py | 18 +++ nix/tests/vm/lib/komorebi_vm/checks.py | 41 +++++ nix/tests/vm/lib/komorebi_vm/kde.py | 183 +++++++++++++++++++++++ nix/tests/vm/lib/komorebi_vm/machine.py | 32 ++++ nix/tests/vm/lib/komorebi_vm/py.typed | 0 nix/tests/vm/lib/pyproject.toml | 24 +++ nix/tests/vm/lib/tests/__init__.py | 0 nix/tests/vm/lib/tests/conftest.py | 46 ++++++ nix/tests/vm/lib/tests/test_checks.py | 33 ++++ nix/tests/vm/lib/tests/test_kde.py | 102 +++++++++++++ nix/tests/vm/nodes/headless.nix | 67 +++++++++ nix/tests/vm/nodes/options.nix | 14 ++ nix/tests/vm/suites/kwin/default.nix | 5 + nix/tests/vm/suites/kwin/test.py | 31 ++++ scripts/vm-mac | 38 +++++ 22 files changed, 923 insertions(+), 1 deletion(-) create mode 100644 docs/dev/vm-tests.md create mode 100644 nix/tests/vm/default.nix create mode 100644 nix/tests/vm/lib/komorebi_vm/__init__.py create mode 100644 nix/tests/vm/lib/komorebi_vm/checks.py create mode 100644 nix/tests/vm/lib/komorebi_vm/kde.py create mode 100644 nix/tests/vm/lib/komorebi_vm/machine.py create mode 100644 nix/tests/vm/lib/komorebi_vm/py.typed create mode 100644 nix/tests/vm/lib/pyproject.toml create mode 100644 nix/tests/vm/lib/tests/__init__.py create mode 100644 nix/tests/vm/lib/tests/conftest.py create mode 100644 nix/tests/vm/lib/tests/test_checks.py create mode 100644 nix/tests/vm/lib/tests/test_kde.py create mode 100644 nix/tests/vm/nodes/headless.nix create mode 100644 nix/tests/vm/nodes/options.nix create mode 100644 nix/tests/vm/suites/kwin/default.nix create mode 100644 nix/tests/vm/suites/kwin/test.py create mode 100755 scripts/vm-mac diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 5059bfde..7a794518 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -5,3 +5,8 @@ By opening this PR, you confirm that you have read, understood and agree to this project's `CONTRIBUTING.md`. --> + + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2b129d43..9209dddd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -42,6 +42,13 @@ warnings denied. `just fmt` formats the Rust sources, and `nix fmt` every file type the repository has. `nix flake check` is what CI runs; it builds the same checks, plus `cargo deny`, as derivations. +## VM tests + +A change that needs a real KWin to be checked comes with a VM test, next to +the Rust test that covers the same behavior against the fake desktop. +[`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) says how they are laid out, how +to run one (`just vm NAME`) and how to add one. + ## Continuous integration [`ci.yaml`](.github/workflows/ci.yaml) runs on every pull request and on every diff --git a/README.md b/README.md index 883344a9..01d29827 100644 --- a/README.md +++ b/README.md @@ -33,10 +33,15 @@ and the tests under `cargo nextest`, on Linux and on an Apple silicon Mac. A Mac runs the tests against the fake desktop, since KWin only exists on Linux. `nix fmt` formats every file the checks look at. +The VM tests boot NixOS with Plasma and run a real KWin. `just vm NAME` runs +one; [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) has the details, including +how to run them on a Mac. + ## Documentation `cargo doc --workspace --no-deps --open` builds the API documentation. -[`CONTRIBUTING.md`](CONTRIBUTING.md) says how to work on the code. +[`CONTRIBUTING.md`](CONTRIBUTING.md) says how to work on the code, and +[`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) how the VM tests work. ## License diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md new file mode 100644 index 00000000..02bd441d --- /dev/null +++ b/docs/dev/vm-tests.md @@ -0,0 +1,116 @@ +# VM tests + +The unit tests run against a fake desktop. They cannot say whether KWin does +what the daemon asks of it, so a second kind of test boots a NixOS virtual +machine with Plasma in it, starts a real KWin, and drives it. This page says how +they are laid out, how to run them, and how to add one. + +## What runs where + +| Where | How | Accelerator | +|---|---|---| +| CI, `x86_64-linux` | `nix build -L .#checks.x86_64-linux.vm-NAME` | KVM | +| A Linux machine with KVM | `just vm NAME` | KVM | +| A Mac | `just vm NAME`, which runs `scripts/vm-mac` | HVF | +| A Linux machine with no KVM | `nix build -L .#legacyPackages.SYSTEM.vmTcg.NAME` | TCG | + +TCG is software emulation. It is slow enough that only short suites are worth +running that way, and the library's `scale` argument (below) is 8 for it. + +Each suite is a directory under +[`nix/tests/vm/suites`](../../nix/tests/vm/suites). The generator in +[`nix/tests/vm/default.nix`](../../nix/tests/vm/default.nix) lists that +directory, so a new suite is a new directory and nothing else: it appears as +`checks..vm-NAME` on Linux and as `legacyPackages..vm.NAME` +everywhere. `legacyPackages..vmTiers` lists the names of each tier as +JSON, which is what CI reads. + +A suite has two files: + +- `default.nix` sets `tier` (`"fast"` or `"slow"`), `kind` (the node it runs on) + and `timeoutMinutes`. +- `test.py` is the test, a Python script for the NixOS test driver. It is + prefixed with `SCALE = `, how many times slower than KVM the machine + is. + +## Nodes + +`kind` picks a file under +[`nix/tests/vm/nodes`](../../nix/tests/vm/nodes). + +`headless` is a machine with Plasma installed and no login. Each KWin a test +starts is a pair of user units of the test user, `session-bus@NAME` (a private +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. + +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. + +## The library + +Suites import from `komorebi_vm`, in +[`nix/tests/vm/lib`](../../nix/tests/vm/lib). It does not depend on the test +driver. It depends on the small `Machine` protocol, and its unit tests pass a +fake machine, so the `vm-lib` check tests it without booting anything. The +check also runs `ruff` and `ty` over it. The driver type checks every +`test.py` with `ty` and `ruff` too, so a typo in a suite fails the build, not +the run. + +- `Checks` counts checks and fails once, at the end, so that one failure does + not hide the ones after it. `finish()` prints `passed: N failed: M`. +- `Kde` is one KWin session. `Kde.headless(machine, name, size=, outputs=, + scale=)` starts the units and waits for KWin to own its name on the private + bus. `wid`, `rect`, `title` and `active` read windows through `kdotool`, + `outputs` counts the enabled outputs through `kscreen-doctor`, `spawn` starts + a client, and `wait_for(predicate, timeout)` polls, with the timeout + multiplied by `scale`. + +Poll for what the test needs with `wait_for`. A fixed sleep is too long on +KVM and too short on TCG. + +## Running a test on a Mac + +QEMU has to run on the Mac to use HVF, and the guest is Linux, so the guest's +closure is built on a Linux builder and the driver runs on the Mac. The nix +sandbox on macOS cannot give QEMU the hypervisor, so `scripts/vm-mac` runs the +driver directly instead of building the check. + +```sh +export KOMOREBI_BUILDER=ssh-ng://builder@localhost +export NIX_SSHOPTS="-p 31022 -i $HOME/.ssh/builder_ed25519 -o IdentitiesOnly=yes" +just vm kwin +``` + +`KOMOREBI_BUILDER` is the store URL of an `aarch64-linux` builder you can +reach. `nix run nixpkgs#darwin.linux-builder` starts one, with one core and 3 GB +of memory by default; a Plasma guest needs more than that (6 cores and 10 GB +worked, at time of writing, 2026-10-27), and the builder's 20 GB disk holds one +Plasma system closure of about 10 GB, so run `nix-collect-garbage` on it +between builds of different guests. + +The script prints where the artifacts (screenshots, logs) are, under +`.vm/out/NAME`. + +## Writing a test + +1. Create `nix/tests/vm/suites/NAME/default.nix` and `test.py`. Start from + [`suites/kwin`](../../nix/tests/vm/suites/kwin). +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`. +4. If the test covers behavior the daemon has, write the Rust test that covers + the same behavior against the fake desktop in the same commit, and say in + the VM test's first comment what only a real KWin can tell. + +Add `git add -N` for new files first: a flake only sees files git knows about. + +## Looking inside a failed run + +`nix build -L` prints the guest's console. Run the driver by hand, as +`scripts/vm-mac` does, to keep the screenshots. For an interactive session +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. diff --git a/flake.nix b/flake.nix index 7a4f69af..09f742a8 100644 --- a/flake.nix +++ b/flake.nix @@ -112,6 +112,12 @@ let pkgs = mkPkgs system; build = mkKomorebiPackages { inherit pkgs; }; + isLinux = pkgs.stdenv.hostPlatform.isLinux; + # a Mac runs the guests under HVF, which is slower than KVM + vm = import ./nix/tests/vm { + hostPkgs = pkgs; + scale = if isLinux then 1 else 1.5; + }; nightlyRustfmt = pkgs.rust-bin.nightly.latest.rustfmt; nightlyToolchain = pkgs.rust-bin.nightly.latest.default; rustToolchainWithNightlyRustfmt = pkgs.symlinkJoin { @@ -169,6 +175,30 @@ komorebi-workspace-nextest = build.craneLib.cargoNextest ( build.individualCrateArgs // { doCheck = true; } ); + + vm-lib = vm.lib; + } + # The VM tests need QEMU with KVM, so only Linux checks them. A Mac runs the same tests + # through legacyPackages..vm, see docs/dev/vm-tests.md. + // lib.optionalAttrs isLinux ( + lib.mapAttrs' (name: test: lib.nameValuePair "vm-${name}" test) vm.suites + ); + + legacyPackages = { + # every suite, as a test with a `driver`, on every system + vm = vm.suites; + # the suites of each tier, for the CI matrix + vmTiers = vm.tiers; + # the guests of every suite, to build on a Linux builder when the host is a Mac + vmGuests = vm.guests; + } + // lib.optionalAttrs isLinux { + # the same suites on a machine with no KVM, which is slow but works anywhere + vmTcg = + (import ./nix/tests/vm { + hostPkgs = pkgs; + scale = 8; + }).suites; }; packages = lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { @@ -202,6 +232,11 @@ pkgs.jq pkgs.just pkgs.ripgrep + + # the VM test library + pkgs.ruff + pkgs.ty + (pkgs.python3.withPackages (ps: [ ps.pytest ])) ]; }; diff --git a/justfile b/justfile index 50230bb6..2120a566 100644 --- a/justfile +++ b/justfile @@ -17,5 +17,25 @@ lint: test -z "$(rg 'dbg!' --type rust .)" || (echo "dbg! macro not allowed"; false) test -z "$(rg 'println!' --type rust ./komorebi/src)" || (echo "println! macro not allowed"; false) +# one VM test, on this machine: `just vm kwin`. Linux boots the guest under KVM through the +# flake check; a Mac builds the guest on a builder and runs the driver (see docs/dev/vm-tests.md) +vm name: + #!/usr/bin/env bash + set -euo pipefail + if [ "$(uname)" = Darwin ]; then + scripts/vm-mac {{ name }} + else + nix build -L .#checks.{{ arch() }}-linux.vm-{{ name }} + fi + +# every VM test, in the order of the flake +vm-all: + #!/usr/bin/env bash + set -euo pipefail + system=$(nix eval --raw --impure --expr builtins.currentSystem) + for name in $(nix eval --json ".#legacyPackages.$system.vm" --apply builtins.attrNames | jq -r '.[]'); do + just vm "$name" + done + run target *args: cargo run --bin {{ target }} --locked -- {{ args }} diff --git a/nix/tests/vm/default.nix b/nix/tests/vm/default.nix new file mode 100644 index 00000000..96255143 --- /dev/null +++ b/nix/tests/vm/default.nix @@ -0,0 +1,100 @@ +# The NixOS VM tests. Every directory under `suites/` is one test, `checks..vm-` +# (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 +# 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, + scale ? 1, +}: +let + inherit (hostPkgs) lib; + + # the library the suites import, built for the python of the test driver + komorebiVm = + ps: + ps.buildPythonPackage { + pname = "komorebi-vm"; + version = "0.1.0"; + pyproject = true; + src = lib.fileset.toSource { + root = ./lib; + fileset = ./lib; + }; + build-system = [ ps.setuptools ]; + doCheck = false; + }; + + # unit tests of the library against a fake machine, and the linters over it + libCheck = + let + python = hostPkgs.python3.withPackages (ps: [ + ps.pytest + (komorebiVm ps) + ]); + in + hostPkgs.runCommand "vm-lib" + { + nativeBuildInputs = [ + python + hostPkgs.ruff + hostPkgs.ty + ]; + src = lib.fileset.toSource { + root = ./lib; + fileset = ./lib; + }; + } + '' + cp -r $src lib && chmod -R u+w lib && cd lib + ruff check . + ruff format --check . + ty check --python ${python} . + pytest -q -p no:cacheprovider + touch $out + ''; + + suiteNames = lib.attrNames ( + lib.filterAttrs (_: type: type == "directory") (builtins.readDir ./suites) + ); + + suiteDefs = lib.genAttrs suiteNames (name: import (./suites + "/${name}")); + + mkSuite = + name: + let + dir = ./suites + "/${name}"; + suite = suiteDefs.${name}; + in + hostPkgs.testers.runNixOSTest { + name = "komorebi-${name}"; + extraPythonPackages = ps: [ (komorebiVm ps) ]; + globalTimeout = builtins.ceil (suite.timeoutMinutes * 60 * scale); + passthru.tier = suite.tier; + + nodes.machine = { + imports = [ (./nodes + "/${suite.kind}.nix") ]; + }; + + testScript = '' + SCALE = ${toString scale} + '' + + builtins.readFile (dir + "/${suite.script or "test.py"}"); + }; + + suites = lib.genAttrs suiteNames mkSuite; +in +{ + inherit suites; + lib = libCheck; + + # the suites of each tier, for the CI matrix: { fast = [ "kwin" ... ]; slow = [ ... ]; } + tiers = lib.groupBy (name: suiteDefs.${name}.tier) suiteNames; + + # the guests of every suite, so that a Mac can build them on a Linux builder first + guests = lib.mapAttrs ( + _: test: lib.mapAttrs (_: node: node.system.build.toplevel) test.nodes + ) suites; +} diff --git a/nix/tests/vm/lib/komorebi_vm/__init__.py b/nix/tests/vm/lib/komorebi_vm/__init__.py new file mode 100644 index 00000000..4d2c4b4a --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/__init__.py @@ -0,0 +1,18 @@ +"""Helpers for the NixOS VM tests of komorebi for KDE. + +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`). + +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.checks import Checks +from komorebi_vm.kde import Kde, Rect +from komorebi_vm.machine import Machine + +__all__ = ["Checks", "Kde", "Machine", "Rect"] diff --git a/nix/tests/vm/lib/komorebi_vm/checks.py b/nix/tests/vm/lib/komorebi_vm/checks.py new file mode 100644 index 00000000..a14616a8 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/checks.py @@ -0,0 +1,41 @@ +"""Counted checks, so that one failure does not hide the ones after it.""" + +from collections.abc import Callable + + +class Checks: + """Collects the outcome of every check and fails once, at the end. + + A suite is a long scenario: a failure in the middle should not stop the + rest from running, because the rest says what else is broken. `finish` + prints the totals and raises if any check failed. + """ + + def __init__(self) -> None: + self.passed = 0 + self.failed = 0 + + def ok(self, description: str) -> None: + """Records a check that passed.""" + self.passed += 1 + print(f" ok {description}") + + def bad(self, description: str) -> None: + """Records a check that failed.""" + self.failed += 1 + print(f" FAIL {description}") + + def check(self, description: str, condition: bool | Callable[[], bool]) -> bool: + """Records `condition` (or what calling it returns) and returns it.""" + holds = condition() if callable(condition) else condition + if holds: + self.ok(description) + else: + self.bad(description) + return holds + + def finish(self) -> None: + """Prints `passed: N failed: M` and raises if any check failed.""" + print(f"passed: {self.passed} failed: {self.failed}") + if self.failed: + raise AssertionError(f"{self.failed} checks failed") diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py new file mode 100644 index 00000000..8b0faa4b --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -0,0 +1,183 @@ +"""A KWin session inside a test machine, and the tools to look at it.""" + +import shlex +import time +from collections.abc import Callable +from dataclasses import dataclass + +from komorebi_vm.machine import Machine + + +@dataclass(frozen=True) +class Rect: + """A window's position and size, in pixels.""" + + x: int + y: int + w: int + h: int + + def overlaps(self, other: "Rect") -> bool: + """Returns true if and only if the two rectangles share at least one pixel.""" + return ( + self.x < other.x + other.w + and other.x < self.x + self.w + and self.y < other.y + other.h + and other.y < self.y + self.h + ) + + +class Kde: + """One KWin session of the test user, with its own session bus and Wayland socket. + + The node runs `kwin_wayland` and the bus as user units (see + `nix/tests/vm/nodes/headless.nix`), so several sessions can run side by + side under different names and none touches another. Every command is run + as the test user, with the environment of the named session. + + `scale` multiplies every wait: 1 under KVM, more where the machine is + slower (HVF on a Mac, TCG anywhere). + """ + + def __init__( + self, + machine: Machine, + name: str, + *, + user: str = "komorebi", + uid: int = 1000, + scale: float = 1.0, + ) -> None: + self.machine = machine + self.name = name + self.user = user + self.uid = uid + self.scale = scale + + @classmethod + def headless( + cls, + machine: Machine, + name: str, + *, + size: tuple[int, int] = (1920, 1080), + outputs: int = 1, + scale: float = 1.0, + user: str = "komorebi", + uid: int = 1000, + ) -> "Kde": + """Starts `kwin_wayland --virtual` with `outputs` outputs of `size`, and waits for it.""" + kde = cls(machine, name, user=user, uid=uid, scale=scale) + machine.succeed(f"loginctl show-user {user} >/dev/null") + width, height = size + args = f"--width {width} --height {height} --output-count {outputs}" + kde.as_user(f"echo KWIN_ARGS={shlex.quote(args)} > {kde.runtime}/kwin-virtual-{name}.env") + kde.systemctl("start", f"session-bus@{name}.service", f"kwin-virtual@{name}.service") + if not kde.wait_for(lambda: kde.has_name("org.kde.KWin"), timeout=60): + log = machine.execute(f"journalctl _UID={uid} --no-pager -n 40")[1] + raise AssertionError(f"KWin did not come up:\n{log}") + return kde + + @property + def runtime(self) -> str: + """The test user's runtime directory.""" + return f"/run/user/{self.uid}" + + @property + def env(self) -> str: + """The `VAR=value` words that put a command inside this session.""" + pairs = { + "XDG_RUNTIME_DIR": self.runtime, + "DBUS_SESSION_BUS_ADDRESS": f"unix:path={self.runtime}/session-{self.name}.bus", + "WAYLAND_DISPLAY": f"wayland-{self.name}", + "KDE_SESSION_VERSION": "6", + "XDG_CURRENT_DESKTOP": "KDE", + "XDG_SESSION_TYPE": "wayland", + "QT_QPA_PLATFORM": "wayland", + "GDK_BACKEND": "wayland", + } + return " ".join(f"{key}={shlex.quote(value)}" for key, value in pairs.items()) + + def as_user(self, command: str) -> str: + """Runs `command` as the test user, and fails the test unless it succeeds.""" + return self.machine.succeed(self._wrap(command, session=False)) + + def run(self, command: str) -> tuple[int, str]: + """Runs `command` inside the session and returns its status and output.""" + return self.machine.execute(self._wrap(command)) + + def sh(self, command: str) -> str: + """Runs `command` inside the session, and fails the test unless it succeeds.""" + return self.machine.succeed(self._wrap(command)) + + def spawn(self, command: str) -> None: + """Starts `command` in the background inside the session, as a client of KWin.""" + self.sh(f"setsid nohup {command} >/dev/null 2>&1 < /dev/null &") + + def systemctl(self, *args: str) -> str: + """Runs `systemctl --user` as the test user.""" + return self.as_user("systemctl --user " + " ".join(args)) + + def stop(self) -> None: + """Stops the session's KWin and its bus.""" + self.systemctl( + "stop", f"kwin-virtual@{self.name}.service", f"session-bus@{self.name}.service" + ) + + def wait_for( + self, + predicate: Callable[[], bool], + timeout: float = 10, + interval: float = 0.1, + ) -> bool: + """Polls `predicate` until it holds or `timeout` seconds (times `scale`) pass.""" + deadline = time.monotonic() + timeout * self.scale + while True: + if predicate(): + return True + if time.monotonic() >= deadline: + return False + time.sleep(interval) + + def has_name(self, name: str) -> bool: + """Returns true if and only if `name` is owned on the session bus.""" + status, _ = self.run(f"busctl --user --no-pager list | grep -q '^{name} '") + return status == 0 + + def wid(self, title: str) -> str: + """The id of the first window whose title is exactly `title`, or the empty string.""" + pattern = shlex.quote(f"^{title}$") + return self.run(f"kdotool search --name {pattern} | head -1")[1].strip() + + def rect(self, wid: str) -> Rect: + """The position and size KWin reports for the window.""" + out = self.sh(f"kdotool getwindowgeometry {shlex.quote(wid)}") + position = size = None + for line in out.splitlines(): + words = line.split() + if words[:1] == ["Position:"]: + position = words[1] + elif words[:1] == ["Geometry:"]: + size = words[1] + if position is None or size is None: + raise AssertionError(f"no geometry in {out!r}") + x, y = (int(v) for v in position.split(",")) + w, h = (int(v) for v in size.split("x")) + return Rect(x, y, w, h) + + def title(self, wid: str) -> str: + """The title of the window.""" + return self.sh(f"kdotool getwindowname {shlex.quote(wid)}").strip().splitlines()[-1] + + def active(self) -> str: + """The id of the window KWin has focused, or the empty string.""" + lines = self.run("kdotool getactivewindow")[1].strip().splitlines() + return lines[-1] if lines else "" + + def outputs(self) -> int: + """The number of outputs KWin has enabled.""" + return int(self.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'")) + + def _wrap(self, command: str, session: bool = True) -> str: + env = self.env if session else f"XDG_RUNTIME_DIR={shlex.quote(self.runtime)}" + return f"runuser -u {self.user} -- env {env} sh -c {shlex.quote(command)}" diff --git a/nix/tests/vm/lib/komorebi_vm/machine.py b/nix/tests/vm/lib/komorebi_vm/machine.py new file mode 100644 index 00000000..6162ecf8 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/machine.py @@ -0,0 +1,32 @@ +"""The part of the NixOS test driver's `Machine` that the library uses. + +The driver's own class is not importable outside a test run, so the library +depends on this protocol instead, and its unit tests pass a fake. The methods +take only what the library passes; the driver's accept more (a timeout, whether +to check the exit status), which does not stop its class from satisfying the +protocol. +""" + +from pathlib import Path +from typing import Protocol + + +class Machine(Protocol): + """A virtual machine the test can run commands on, as root.""" + + @property + def out_dir(self) -> Path: + """The directory that screenshots and other artifacts go to.""" + ... + + def execute(self, command: str, /) -> tuple[int, str]: + """Runs `command` and returns its exit status and its output.""" + ... + + def succeed(self, *commands: str) -> str: + """Runs each command and fails the test unless it exits with status 0.""" + ... + + def fail(self, *commands: str) -> str: + """Runs each command and fails the test if it exits with status 0.""" + ... diff --git a/nix/tests/vm/lib/komorebi_vm/py.typed b/nix/tests/vm/lib/komorebi_vm/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/nix/tests/vm/lib/pyproject.toml b/nix/tests/vm/lib/pyproject.toml new file mode 100644 index 00000000..110f6bf6 --- /dev/null +++ b/nix/tests/vm/lib/pyproject.toml @@ -0,0 +1,24 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "komorebi-vm" +version = "0.1.0" +description = "Helpers for the NixOS VM tests of komorebi for KDE" +requires-python = ">=3.12" + +[tool.setuptools] +packages = ["komorebi_vm"] + +[tool.setuptools.package-data] +komorebi_vm = ["py.typed"] + +[tool.ruff] +line-length = 100 + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B", "SIM"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/nix/tests/vm/lib/tests/__init__.py b/nix/tests/vm/lib/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/nix/tests/vm/lib/tests/conftest.py b/nix/tests/vm/lib/tests/conftest.py new file mode 100644 index 00000000..089a9f9b --- /dev/null +++ b/nix/tests/vm/lib/tests/conftest.py @@ -0,0 +1,46 @@ +"""A fake machine that records commands and answers from a script.""" + +from collections.abc import Callable +from pathlib import Path + +import pytest + + +class FakeMachine: + """Answers `execute` with the first matching reply, and records every command.""" + + out_dir = Path("/tmp") + + def __init__(self) -> None: + self.commands: list[str] = [] + self.replies: list[tuple[Callable[[str], bool], tuple[int, str]]] = [] + + def reply(self, contains: str, status: int = 0, output: str = "") -> None: + """Makes any command containing `contains` answer with `status` and `output`.""" + self.replies.append((lambda command: contains in command, (status, output))) + + def execute(self, command: str, /) -> tuple[int, str]: + self.commands.append(command) + for matches, answer in self.replies: + if matches(command): + return answer + return 0, "" + + def succeed(self, *commands: str) -> str: + output = "" + for command in commands: + status, output = self.execute(command) + assert status == 0, f"{command!r} exited with {status}: {output}" + return output + + def fail(self, *commands: str) -> str: + output = "" + for command in commands: + status, output = self.execute(command) + assert status != 0, f"{command!r} succeeded: {output}" + return output + + +@pytest.fixture +def machine() -> FakeMachine: + return FakeMachine() diff --git a/nix/tests/vm/lib/tests/test_checks.py b/nix/tests/vm/lib/tests/test_checks.py new file mode 100644 index 00000000..168ac0d2 --- /dev/null +++ b/nix/tests/vm/lib/tests/test_checks.py @@ -0,0 +1,33 @@ +import pytest + +from komorebi_vm import Checks + + +def test_counts_passes_and_failures(capsys: pytest.CaptureFixture[str]) -> None: + checks = Checks() + + assert checks.check("a holds", True) + assert not checks.check("b does not hold", False) + + assert (checks.passed, checks.failed) == (1, 1) + out = capsys.readouterr().out + assert " ok a holds" in out + assert " FAIL b does not hold" in out + + +def test_a_callable_condition_is_called() -> None: + checks = Checks() + + assert checks.check("lazy", lambda: 1 + 1 == 2) + + +def test_finish_raises_only_when_something_failed(capsys: pytest.CaptureFixture[str]) -> None: + checks = Checks() + checks.check("fine", True) + checks.finish() + assert "passed: 1 failed: 0" in capsys.readouterr().out + + checks.check("broken", False) + with pytest.raises(AssertionError, match="1 checks failed"): + checks.finish() + assert "passed: 1 failed: 1" in capsys.readouterr().out diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py new file mode 100644 index 00000000..e96752e7 --- /dev/null +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -0,0 +1,102 @@ +import shlex + +import pytest + +from komorebi_vm import Kde, Rect + +from .conftest import FakeMachine + + +def inner(command: str) -> str: + """The script a wrapped command hands to `sh -c`, with one level of quoting removed.""" + return shlex.split(command)[-1] + + +def test_commands_run_as_the_user_inside_the_named_session(machine: FakeMachine) -> None: + kde = Kde(machine, "main") + + kde.sh("kdotool getactivewindow") + + (command,) = machine.commands + assert command.startswith("runuser -u komorebi -- env ") + assert "WAYLAND_DISPLAY=wayland-main" in command + assert "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/session-main.bus" in command + assert "XDG_RUNTIME_DIR=/run/user/1000" in command + + +def test_two_sessions_do_not_share_a_socket(machine: FakeMachine) -> None: + assert "wayland-a" in Kde(machine, "a").env + assert "wayland-b" in Kde(machine, "b").env + assert "wayland-a" not in Kde(machine, "b").env + + +def test_as_user_has_no_session_in_its_environment(machine: FakeMachine) -> None: + Kde(machine, "main").as_user("systemctl --user is-system-running") + + (command,) = machine.commands + assert "WAYLAND_DISPLAY" not in command + assert "XDG_RUNTIME_DIR=/run/user/1000" in command + + +def test_headless_writes_the_arguments_and_starts_the_units(machine: FakeMachine) -> None: + machine.reply("busctl", status=0) + + Kde.headless(machine, "main", size=(1280, 720), outputs=2) + + scripts = [inner(command) for command in machine.commands if " sh -c " in command] + assert ( + "echo KWIN_ARGS='--width 1280 --height 720 --output-count 2'" + " > /run/user/1000/kwin-virtual-main.env" + ) in scripts + assert "systemctl --user start session-bus@main.service kwin-virtual@main.service" in scripts + + +def test_headless_reports_the_journal_when_kwin_does_not_come_up(machine: FakeMachine) -> None: + machine.reply("busctl", status=1) + machine.reply("journalctl", output="kwin: no GPU") + + with pytest.raises(AssertionError, match="kwin: no GPU"): + Kde.headless(machine, "main", scale=0.01) + + +def test_wait_for_scales_its_timeout(machine: FakeMachine) -> None: + kde = Kde(machine, "main", scale=0.0) + + assert not kde.wait_for(lambda: False, timeout=100) + assert kde.wait_for(lambda: True, timeout=0) + + +def test_rect_parses_what_kdotool_prints(machine: FakeMachine) -> None: + machine.reply( + "getwindowgeometry", output="Window {abc}\n Position: 10,20\n Geometry: 300x400\n" + ) + + assert Kde(machine, "main").rect("{abc}") == Rect(10, 20, 300, 400) + + +def test_rect_fails_on_output_it_does_not_understand(machine: FakeMachine) -> None: + machine.reply("getwindowgeometry", output="nothing useful") + + with pytest.raises(AssertionError, match="no geometry"): + Kde(machine, "main").rect("{abc}") + + +def test_overlap() -> None: + assert Rect(0, 0, 10, 10).overlaps(Rect(5, 5, 10, 10)) + assert not Rect(0, 0, 10, 10).overlaps(Rect(10, 0, 10, 10)) + assert not Rect(0, 0, 10, 10).overlaps(Rect(0, 10, 10, 10)) + + +def test_wid_is_the_first_match(machine: FakeMachine) -> None: + machine.reply("kdotool search", output="{one}\n") + + assert Kde(machine, "main").wid("alpha") == "{one}" + + +def test_active_is_the_last_line(machine: FakeMachine) -> None: + machine.reply("getactivewindow", output="noise\n{two}\n") + + assert Kde(machine, "main").active() == "{two}" + machine.replies.clear() + machine.reply("getactivewindow", output="") + assert Kde(machine, "main").active() == "" diff --git a/nix/tests/vm/nodes/headless.nix b/nix/tests/vm/nodes/headless.nix new file mode 100644 index 00000000..72b237ee --- /dev/null +++ b/nix/tests/vm/nodes/headless.nix @@ -0,0 +1,67 @@ +# 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. +{ + config, + lib, + pkgs, + ... +}: +{ + imports = [ ./options.nix ]; + + # KWin, its plugins and the environment a session expects + services.desktopManager.plasma6.enable = true; + hardware.graphics.enable = true; + + users.users.komorebi = { + isNormalUser = true; + uid = 1000; + # keeps the user manager, and so /run/user/1000, alive without a login + linger = true; + }; + + virtualisation = { + memorySize = 3072; + cores = 2; + # KWin wants a DRM render node, which needs a GPU. The test driver adds one on aarch64 only. + qemu.options = lib.optionals (config.komorebi.vm.renderNode && pkgs.stdenv.hostPlatform.isx86_64) [ + "-device virtio-gpu-pci" + ]; + }; + + environment.systemPackages = with pkgs; [ + foot + jq + kdotool + kdePackages.libkscreen + kdePackages.qttools + ]; + + systemd.user.services = { + "session-bus@" = { + description = "The private session bus of the test session %i"; + serviceConfig.ExecStart = "${pkgs.dbus}/bin/dbus-daemon --session --address=unix:path=%t/session-%i.bus --nofork --nopidfile"; + }; + + "kwin-virtual@" = { + description = "A headless KWin for the test session %i"; + requires = [ "session-bus@%i.service" ]; + after = [ "session-bus@%i.service" ]; + environment = { + DBUS_SESSION_BUS_ADDRESS = "unix:path=%t/session-%i.bus"; + XDG_SESSION_TYPE = "wayland"; + # software rendering makes KWin skip every animating effect unless told otherwise + KWIN_EFFECTS_FORCE_ANIMATIONS = "1"; + # script print() goes through qCDebug, which is off by default + QT_LOGGING_RULES = "kwin_scripting.debug=true;js.debug=true;qml.debug=true"; + }; + serviceConfig = { + # the library writes KWIN_ARGS (size, number of outputs) before it starts the unit + EnvironmentFile = "-%t/kwin-virtual-%i.env"; + ExecStart = "${pkgs.kdePackages.kwin}/bin/kwin_wayland --virtual --socket wayland-%i --no-lockscreen --no-global-shortcuts $KWIN_ARGS"; + }; + }; + }; +} diff --git a/nix/tests/vm/nodes/options.nix b/nix/tests/vm/nodes/options.nix new file mode 100644 index 00000000..95be6131 --- /dev/null +++ b/nix/tests/vm/nodes/options.nix @@ -0,0 +1,14 @@ +# The options the test nodes share. +{ lib, ... }: +{ + options.komorebi.vm.renderNode = lib.mkOption { + type = lib.types.bool; + default = true; + description = '' + Give an x86_64 guest a virtio-gpu, so that KWin has a DRM render node. A node that draws sets + this to false: the virtio-gpu would be a second display, KWin would draw on it, and a + screenshot, which is of the other one, would show nothing. The test driver adds the one + virtio-gpu an aarch64 guest has, whatever this says. + ''; + }; +} diff --git a/nix/tests/vm/suites/kwin/default.nix b/nix/tests/vm/suites/kwin/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/kwin/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/kwin/test.py b/nix/tests/vm/suites/kwin/test.py new file mode 100644 index 00000000..a861e743 --- /dev/null +++ b/nix/tests/vm/suites/kwin/test.py @@ -0,0 +1,31 @@ +# What the harness itself promises: a headless KWin comes up with the outputs asked for, a client +# gets a window on it, and the library sees both. +from komorebi_vm import Checks, Kde + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() + +kde = Kde.headless(machine, "main", size=(1280, 720), outputs=2, scale=SCALE) +checks.check("KWin owns its name on the private bus", kde.has_name("org.kde.KWin")) +checks.check("KWin has the two outputs that were asked for", lambda: kde.outputs() == 2) + +kde.spawn("foot -T alpha sleep 3000") +checks.check("a window appears", kde.wait_for(lambda: kde.wid("alpha") != "", timeout=30)) +wid = kde.wid("alpha") +checks.check("the library reads its title back", lambda: kde.title(wid) == "alpha") +rect = kde.rect(wid) +print(f"alpha is at {rect}") +checks.check("it has a size", rect.w > 0 and rect.h > 0) + +other = Kde.headless(machine, "other", size=(800, 600), scale=SCALE) +checks.check("a second session is its own KWin", lambda: other.outputs() == 1) +checks.check("it does not see the first session's window", other.wid("alpha") == "") +other.stop() + +kde.stop() +checks.check("stopping the session releases its name", not kde.has_name("org.kde.KWin")) + +checks.finish() diff --git a/scripts/vm-mac b/scripts/vm-mac new file mode 100755 index 00000000..537fdb99 --- /dev/null +++ b/scripts/vm-mac @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Runs one VM test on a Mac, where the guest is Linux and the host is not. +# +# scripts/vm-mac NAME [driver arguments] +# +# The guest's closure is built on a Linux builder, copied back, and the test driver then runs +# on the Mac under HVF. The driver is run directly, not through `nix build`, because the nix +# sandbox on macOS cannot give QEMU the hypervisor. Artifacts (screenshots, logs) land in +# `.vm/out/NAME`. +# +# The builder is yours: set KOMOREBI_BUILDER to its store URL (for example +# `ssh-ng://builder@localhost`) and, if it needs them, NIX_SSHOPTS. docs/dev/vm-tests.md +# says what a builder has to be. +set -euo pipefail + +name="${1:?usage: scripts/vm-mac NAME [driver arguments]}" +shift +builder="${KOMOREBI_BUILDER:?set KOMOREBI_BUILDER to the store URL of a Linux builder}" +cd "$(dirname "$0")/.." +test="path:$PWD#legacyPackages.aarch64-darwin.vm.$name" +[ -d .git ] && test="git+file://$PWD#legacyPackages.aarch64-darwin.vm.$name" + +echo "== building the guests on $builder" +nix eval --json "$test.nodes" --apply 'nodes: builtins.mapAttrs (_: node: node.system.build.toplevel.drvPath) nodes' | + jq -r '.[]' | + while read -r drv; do + out=$(nix build "$drv^out" --eval-store auto --store "$builder" --no-link --print-out-paths) + nix copy --from "$builder" --substitute-on-destination --no-check-sigs "$out" + done + +echo "== building the driver" +driver=$(nix build "$test.driver" --builders '' --no-link --print-out-paths) + +out="$PWD/.vm/out/$name" +mkdir -p "$out" +echo "== running $name (artifacts in $out)" +cd "$out" +exec "$driver/bin/nixos-test-driver" -o . "$@" From fec9c2773a3b9df1f18d6b5a6823e2b28bed2f0d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 09:43:11 -0700 Subject: [PATCH 005/255] build(nix): a Plasma session node for tests A virtual KWin has no output to draw on, so every test about pixels, and later about the pointer, needs a real session. The `session` node is the headless node plus a login: plasma-login-manager logs the test user in by itself, the way nixpkgs' own `plasma6` test does, and Plasma draws on the machine's display. The choice of login manager is made in `nodes/session.nix` and nowhere else, and the file says how to switch to sddm. The node adds no display device. The test driver gives every aarch64 guest one virtio-gpu and takes screenshots of it; a second device is a second KWin output that screenshots never show, which is what a first attempt did (a blank 1280x800 console). `Kde.session` attaches to the session once the desktop is up: the shell is running, the user manager knows the Wayland display, and the splash screen has gone. The display is read from the user manager because plasma-login-manager's greeter has its own KWin and takes `wayland-0`, and the user's session gets `wayland-1`. The splash condition is there because KSplash has over a thousand colors on it, so a "not blank" check passed on the splash screen. NixOS wraps programs, which is why processes are found by their command lines: `pgrep -x plasmashell` never matches `.plasmashell-wrapped`, and an exact match for the splash would have passed because nothing matched. `Kde.shot` returns a screenshot as a Pillow image. `vm-render-smoke` is the first slow suite: it starts a session, opens a terminal, and checks the middle of the window is dark and that the desktop behind it has thousands of colors. On aarch64 under HVF five runs gave the same screenshot, with the desktop up after 34 seconds. docs/dev/vm-tests.md describes the node and the two traps. --- docs/dev/vm-tests.md | 31 ++++++++- nix/tests/vm/default.nix | 1 + nix/tests/vm/lib/komorebi_vm/__init__.py | 2 +- nix/tests/vm/lib/komorebi_vm/kde.py | 66 +++++++++++++++++++- nix/tests/vm/lib/komorebi_vm/machine.py | 4 ++ nix/tests/vm/lib/pyproject.toml | 1 + nix/tests/vm/lib/tests/conftest.py | 12 ++-- nix/tests/vm/lib/tests/test_kde.py | 35 +++++++++++ nix/tests/vm/nodes/headless.nix | 4 +- nix/tests/vm/nodes/session.nix | 52 +++++++++++++++ nix/tests/vm/suites/render-smoke/default.nix | 5 ++ nix/tests/vm/suites/render-smoke/test.py | 44 +++++++++++++ 12 files changed, 247 insertions(+), 10 deletions(-) create mode 100644 nix/tests/vm/nodes/session.nix create mode 100644 nix/tests/vm/suites/render-smoke/default.nix create mode 100644 nix/tests/vm/suites/render-smoke/test.py diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index 02bd441d..0c34d991 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -48,6 +48,21 @@ place windows and answer questions about them, but it cannot take a screenshot. 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. +`session` is the headless node plus a login: plasma-login-manager logs the test +user in by itself, as in nixpkgs' own `plasma6` test, and Plasma draws on the +machine's display device. It is the node for anything that needs pixels. The +choice of login manager is made in +[`nodes/session.nix`](../../nix/tests/vm/nodes/session.nix) and nowhere else; +the file says how to switch to sddm, the other one that has been seen to work. +Its display is 1280x800, because screenshots are taken of the machine's one +display device: the `virtio-gpu-pci` that the test driver adds to every aarch64 +guest, and the default VGA of an x86_64 one. The node sets +`komorebi.vm.renderNode` to false, so that an x86_64 guest does not get a second +device: KWin would draw on it, and the screenshot would show the other one. + +On aarch64 under HVF, at time of writing (2026-10-27), the session has the +Wayland socket after 11 to 19 seconds and a painted desktop after 35 seconds. + ## The library Suites import from `komorebi_vm`, in @@ -66,10 +81,24 @@ the run. `outputs` counts the enabled outputs through `kscreen-doctor`, `spawn` starts a client, and `wait_for(predicate, timeout)` polls, with the timeout multiplied by `scale`. +- `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. Poll for what the test needs with `wait_for`. A fixed sleep is too long on KVM and too short on TCG. +Two traps are worth knowing about before writing a screenshot test: + +- A splash screen is not a blank screen. KSplash has more than a thousand colors + on it, so "the screenshot is not blank" passes while Plasma is still + starting. `Kde.session` waits for the splash process to exit, and a test + should check a pixel it knows, such as the middle of a terminal. +- NixOS wraps programs, so a process's name is the wrapper's (`.plasmashell-wrapped`), + and `pgrep -x plasmashell` never matches. Match the command line instead, with + a bracket in the pattern (`pgrep -f '[p]lasmashell'`) so that the shell running + `pgrep` does not match itself. + ## Running a test on a Mac QEMU has to run on the Mac to use HVF, and the guest is Linux, so the guest's @@ -108,7 +137,7 @@ Add `git add -N` for new files first: a flake only sees files git knows about. ## Looking inside a failed run -`nix build -L` prints the guest's console. Run the driver by hand, as +`nix build -L` prints the guest's console, and a session test keeps its screenshots. Run the driver by hand, as `scripts/vm-mac` does, to keep the screenshots. For an interactive session 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 diff --git a/nix/tests/vm/default.nix b/nix/tests/vm/default.nix index 96255143..66fc2b82 100644 --- a/nix/tests/vm/default.nix +++ b/nix/tests/vm/default.nix @@ -24,6 +24,7 @@ let fileset = ./lib; }; build-system = [ ps.setuptools ]; + dependencies = [ ps.pillow ]; doCheck = false; }; diff --git a/nix/tests/vm/lib/komorebi_vm/__init__.py b/nix/tests/vm/lib/komorebi_vm/__init__.py index 4d2c4b4a..6b771634 100644 --- a/nix/tests/vm/lib/komorebi_vm/__init__.py +++ b/nix/tests/vm/lib/komorebi_vm/__init__.py @@ -4,7 +4,7 @@ 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`). + the tools to look at it (`kdotool`, `busctl`, `kscreen-doctor`, screenshots). 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 diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index 8b0faa4b..9c2c9fb5 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -5,6 +5,8 @@ import time from collections.abc import Callable from dataclasses import dataclass +from PIL import Image + from komorebi_vm.machine import Machine @@ -35,6 +37,10 @@ class Kde: side under different names and none touches another. Every command is run as the test user, with the environment of the named session. + A session node has one more: the user's own Plasma session, which + [`Kde.session`][] attaches to. Its bus is `$XDG_RUNTIME_DIR/bus` and its + Wayland socket is whatever the user manager says it is. + `scale` multiplies every wait: 1 under KVM, more where the machine is slower (HVF on a Mac, TCG anywhere). """ @@ -47,12 +53,16 @@ class Kde: user: str = "komorebi", uid: int = 1000, scale: float = 1.0, + bus: str | None = None, + wayland_display: str | None = None, ) -> None: self.machine = machine self.name = name self.user = user self.uid = uid self.scale = scale + self._bus = bus + self._wayland_display = wayland_display @classmethod def headless( @@ -78,6 +88,49 @@ class Kde: raise AssertionError(f"KWin did not come up:\n{log}") return kde + @classmethod + def session( + cls, + machine: Machine, + *, + user: str = "komorebi", + uid: int = 1000, + scale: float = 1.0, + timeout: float = 300, + ) -> "Kde": + """Attaches to the user's Plasma session once its desktop is up. + + The session is up when the shell is running, the user manager knows the + Wayland socket, and the splash screen has gone. The last condition is + the one a screenshot test depends on: a splash screen already has + thousands of colors on it. NixOS wraps its programs, so the processes + are found by their command lines (`pgrep -x` would see only the wrapper's + name), with the first letter in brackets so that the pattern does not + match the shell that runs `pgrep`. + """ + kde = cls(machine, "session", user=user, uid=uid, scale=scale) + kde._bus = f"unix:path={kde.runtime}/bus" + if not kde.wait_for(lambda: kde.run("pgrep -f '[p]lasmashell'")[0] == 0, timeout=timeout): + raise AssertionError("plasmashell did not start") + + def display() -> str: + out = kde.as_user("systemctl --user show-environment") + return next( + ( + line.split("=", 1)[1] + for line in out.splitlines() + if line.startswith("WAYLAND_DISPLAY=") + ), + "", + ) + + if not kde.wait_for(lambda: display() != "", timeout=timeout): + raise AssertionError("the user manager never learned the Wayland display") + kde._wayland_display = display() + if not kde.wait_for(lambda: kde.run("pgrep -f '[k]splashqml'")[0] != 0, timeout=timeout): + raise AssertionError("the splash screen did not go away") + return kde + @property def runtime(self) -> str: """The test user's runtime directory.""" @@ -88,8 +141,9 @@ class Kde: """The `VAR=value` words that put a command inside this session.""" pairs = { "XDG_RUNTIME_DIR": self.runtime, - "DBUS_SESSION_BUS_ADDRESS": f"unix:path={self.runtime}/session-{self.name}.bus", - "WAYLAND_DISPLAY": f"wayland-{self.name}", + "DBUS_SESSION_BUS_ADDRESS": self._bus + or f"unix:path={self.runtime}/session-{self.name}.bus", + "WAYLAND_DISPLAY": self._wayland_display or f"wayland-{self.name}", "KDE_SESSION_VERSION": "6", "XDG_CURRENT_DESKTOP": "KDE", "XDG_SESSION_TYPE": "wayland", @@ -174,6 +228,14 @@ class Kde: lines = self.run("kdotool getactivewindow")[1].strip().splitlines() return lines[-1] if lines else "" + def shot(self, name: str) -> Image.Image: + """Takes a screenshot of the machine's display and returns it, as RGB. + + The file is also kept as `NAME.png` in the test's output directory. + """ + self.machine.screenshot(name) + return Image.open(self.machine.out_dir / f"{name}.png").convert("RGB") + def outputs(self) -> int: """The number of outputs KWin has enabled.""" return int(self.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'")) diff --git a/nix/tests/vm/lib/komorebi_vm/machine.py b/nix/tests/vm/lib/komorebi_vm/machine.py index 6162ecf8..17a17e12 100644 --- a/nix/tests/vm/lib/komorebi_vm/machine.py +++ b/nix/tests/vm/lib/komorebi_vm/machine.py @@ -30,3 +30,7 @@ class Machine(Protocol): def fail(self, *commands: str) -> str: """Runs each command and fails the test if it exits with status 0.""" ... + + def screenshot(self, filename: str, /) -> None: + """Saves a PNG of the machine's display as `filename` in `out_dir`.""" + ... diff --git a/nix/tests/vm/lib/pyproject.toml b/nix/tests/vm/lib/pyproject.toml index 110f6bf6..3378f686 100644 --- a/nix/tests/vm/lib/pyproject.toml +++ b/nix/tests/vm/lib/pyproject.toml @@ -7,6 +7,7 @@ name = "komorebi-vm" version = "0.1.0" description = "Helpers for the NixOS VM tests of komorebi for KDE" requires-python = ">=3.12" +dependencies = ["pillow"] [tool.setuptools] packages = ["komorebi_vm"] diff --git a/nix/tests/vm/lib/tests/conftest.py b/nix/tests/vm/lib/tests/conftest.py index 089a9f9b..67827553 100644 --- a/nix/tests/vm/lib/tests/conftest.py +++ b/nix/tests/vm/lib/tests/conftest.py @@ -4,14 +4,15 @@ from collections.abc import Callable from pathlib import Path import pytest +from PIL import Image class FakeMachine: """Answers `execute` with the first matching reply, and records every command.""" - out_dir = Path("/tmp") + def __init__(self, out_dir: Path) -> None: + self.out_dir = out_dir - def __init__(self) -> None: self.commands: list[str] = [] self.replies: list[tuple[Callable[[str], bool], tuple[int, str]]] = [] @@ -26,6 +27,9 @@ class FakeMachine: return answer return 0, "" + def screenshot(self, filename: str, /) -> None: + Image.new("RGB", (4, 4), (10, 20, 30)).save(self.out_dir / f"{filename}.png") + def succeed(self, *commands: str) -> str: output = "" for command in commands: @@ -42,5 +46,5 @@ class FakeMachine: @pytest.fixture -def machine() -> FakeMachine: - return FakeMachine() +def machine(tmp_path: Path) -> FakeMachine: + return FakeMachine(tmp_path) diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index e96752e7..bf149f6a 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -100,3 +100,38 @@ def test_active_is_the_last_line(machine: FakeMachine) -> None: machine.replies.clear() machine.reply("getactivewindow", output="") assert Kde(machine, "main").active() == "" + + +def test_session_attaches_to_the_users_bus_and_the_display_the_manager_reports( + machine: FakeMachine, +) -> None: + machine.reply("show-environment", output="PATH=/bin\nWAYLAND_DISPLAY=wayland-1\n") + machine.reply("[k]splashqml", status=1) + + kde = Kde.session(machine, timeout=0) + + assert "WAYLAND_DISPLAY=wayland-1" in kde.env + assert "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus" in kde.env + + +def test_session_waits_for_the_splash_screen_to_go(machine: FakeMachine) -> None: + machine.reply("show-environment", output="WAYLAND_DISPLAY=wayland-1\n") + machine.reply("[k]splashqml", status=0) + + with pytest.raises(AssertionError, match="splash"): + Kde.session(machine, timeout=0) + + +def test_session_fails_when_the_shell_never_starts(machine: FakeMachine) -> None: + machine.reply("[p]lasmashell", status=1) + + with pytest.raises(AssertionError, match="plasmashell"): + Kde.session(machine, timeout=0) + + +def test_shot_returns_the_screenshot_as_rgb(machine: FakeMachine) -> None: + image = Kde(machine, "main").shot("desktop") + + assert image.size == (4, 4) + assert image.getpixel((0, 0)) == (10, 20, 30) + assert (machine.out_dir / "desktop.png").exists() diff --git a/nix/tests/vm/nodes/headless.nix b/nix/tests/vm/nodes/headless.nix index 72b237ee..04655b61 100644 --- a/nix/tests/vm/nodes/headless.nix +++ b/nix/tests/vm/nodes/headless.nix @@ -23,8 +23,8 @@ }; virtualisation = { - memorySize = 3072; - cores = 2; + memorySize = lib.mkDefault 3072; + cores = lib.mkDefault 2; # KWin wants a DRM render node, which needs a GPU. The test driver adds one on aarch64 only. qemu.options = lib.optionals (config.komorebi.vm.renderNode && pkgs.stdenv.hostPlatform.isx86_64) [ "-device virtio-gpu-pci" diff --git a/nix/tests/vm/nodes/session.nix b/nix/tests/vm/nodes/session.nix new file mode 100644 index 00000000..ebc68060 --- /dev/null +++ b/nix/tests/vm/nodes/session.nix @@ -0,0 +1,52 @@ +# A real Plasma Wayland session that logs in by itself, on a machine that can draw. Everything the +# headless node has is here too, so a test can still start a virtual KWin next to it. +# +# The choice of login manager is made here and nowhere else. nixpkgs' own `plasma6` test uses +# plasma-login-manager, so that is what this node follows; sddm with a Wayland greeter is the other +# one that has been seen to work, and replacing the first block below with +# `services.displayManager.sddm = { enable = true; wayland.enable = true; };` and +# `services.displayManager.defaultSession = "plasma";` switches to it. +{ pkgs, ... }: +{ + imports = [ ./headless.nix ]; + + # the one display this node has is the one screenshots are taken of + komorebi.vm.renderNode = false; + + services.xserver.enable = true; + services.displayManager = { + plasma-login-manager.enable = true; + autoLogin = { + enable = true; + user = "komorebi"; + }; + }; + + virtualisation = { + memorySize = 4096; + cores = 4; + }; + + # An idle lock screen or a dimmed display changes what a screenshot shows, and a display that has + # gone to sleep gets no frame callbacks from KWin, so clients stop answering resizes. + environment.etc."xdg/kscreenlockerrc".text = '' + [Daemon] + Autolock=false + LockOnResume=false + ''; + environment.etc."xdg/powerdevilrc".text = '' + [AC][Display] + DimDisplayWhenIdle=false + TurnOffDisplayWhenIdle=false + + [AC][SuspendAndShutdown] + AutoSuspendAction=0 + ''; + + environment.systemPackages = [ pkgs.kdePackages.konsole ]; + + # Nothing adds a display device here (see komorebi.vm.renderNode above). The test driver gives + # every aarch64 guest a virtio-gpu, and an x86_64 guest has the default VGA; screenshots are taken + # of that one, and a second device would be a second head that KWin draws on and the screenshot + # never shows. +} diff --git a/nix/tests/vm/suites/render-smoke/default.nix b/nix/tests/vm/suites/render-smoke/default.nix new file mode 100644 index 00000000..743bab13 --- /dev/null +++ b/nix/tests/vm/suites/render-smoke/default.nix @@ -0,0 +1,5 @@ +{ + tier = "slow"; + kind = "session"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/render-smoke/test.py b/nix/tests/vm/suites/render-smoke/test.py new file mode 100644 index 00000000..77b0e621 --- /dev/null +++ b/nix/tests/vm/suites/render-smoke/test.py @@ -0,0 +1,44 @@ +# A Plasma session draws a desktop in the test machine, so that every test after this one can trust +# a screenshot. KSplash has thousands of colors on it too, so "not blank" is not the check: the +# splash has to be gone and a window has to be painted on the desktop. +import time + +from komorebi_vm import Checks, Kde + +start_all() +started = time.monotonic() +machine.wait_for_unit("multi-user.target") + +checks = Checks() + +kde = Kde.session(machine, scale=SCALE) +print(f"the desktop is up after {time.monotonic() - started:.0f}s") + + +def konsole() -> str: + return kde.run("kdotool search --class konsole | head -1")[1].strip() + + +kde.spawn("konsole") +checks.check("a window appears", kde.wait_for(lambda: konsole() != "", timeout=60)) +rect = kde.rect(konsole()) +checks.check("the window has a size", rect.w > 0 and rect.h > 0) + + +def painted() -> bool: + image = kde.shot("desktop") + center = image.getpixel((rect.x + rect.w // 2, rect.y + rect.h // 2)) + assert isinstance(center, tuple) + # the terminal's background is dark; the wallpaper behind it is not + return sum(center) < 3 * 90 + + +checks.check("the window is painted on the screen", kde.wait_for(painted, timeout=60)) + +image = kde.shot("desktop") +colors = image.getcolors(maxcolors=image.width * image.height) +assert colors is not None +print(f"the screenshot is {image.size[0]}x{image.size[1]} with {len(colors)} colors") +checks.check("the desktop behind it is drawn", len(colors) > 5000) + +checks.finish() From 0725705298d1b880fe742996983604066215df8f Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 09:44:34 -0700 Subject: [PATCH 006/255] ci(github): run the VM tests on KVM `discover` asks the flake for the suites of each tier (`legacyPackages.x86_64-linux.vmTiers`) and hands them to two matrices, so a new directory under `nix/tests/vm/suites` is run without an edit to the workflow. `vm-fast` runs the fast tier on every pull request, one machine per suite, as a sandboxed `nix build` of the check. `vm-slow` runs on master, every week, and on a pull request labeled `ci:vm-slow`; it builds the driver and runs it by hand, outside the sandbox, so that the screenshots and journals of a failed run are uploaded with `if: always()`. A composite action installs nix with the store cached and, for the VM jobs, frees disk space (a Plasma guest is a closure of about 10 GB), writes the udev rule that makes /dev/kvm writable for the runner's user, checks it with `test -w`, and adds `kvm` to nix's system features. KVM on hosted runners is documented for public repositories only. Whether this private repository has it is not known: the first run of these jobs says, and if it does not, they need a different runner. `lint` no longer runs `nix flake check`: on Linux that now boots every VM suite, which a runner with no KVM cannot do. It builds the checks that need no virtual machine, and `vm-lib`, the library's own tests. CONTRIBUTING.md and docs/dev/vm-tests.md say what runs where. --- .github/actions/nix/action.yaml | 44 +++++++++++++++++ .github/workflows/ci.yaml | 84 +++++++++++++++++++++++++++++---- CONTRIBUTING.md | 11 +++-- README.md | 3 +- docs/dev/vm-tests.md | 8 ++++ 5 files changed, 136 insertions(+), 14 deletions(-) create mode 100644 .github/actions/nix/action.yaml diff --git a/.github/actions/nix/action.yaml b/.github/actions/nix/action.yaml new file mode 100644 index 00000000..c342eb47 --- /dev/null +++ b/.github/actions/nix/action.yaml @@ -0,0 +1,44 @@ +name: nix +description: Install nix on a hosted runner, with the store cached and, on request, KVM enabled + +inputs: + kvm: + description: Make /dev/kvm usable and tell nix that this machine can run NixOS tests + default: "false" + +runs: + using: composite + steps: + # A Plasma guest is a closure of about 10 GB, and a hosted runner has little free space on / + # until the toolchains it ships with are gone. + - name: Free disk space + if: inputs.kvm == 'true' + shell: bash + run: | + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL + df -h / + + # The udev rule is what makes /dev/kvm writable for the runner's user. KVM on hosted runners + # is documented for public repositories; `test -w` is what says whether this one has it. + - name: Enable KVM + if: inputs.kvm == 'true' + shell: bash + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | + sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + test -w /dev/kvm + + # This action only installs nix. It does not use the Cachix service, and no Cachix cache, account + # or token is configured anywhere in this repository. + - uses: cachix/install-nix-action@v31 + with: + extra_nix_config: | + system-features = nixos-test benchmark big-parallel ${{ inputs.kvm == 'true' && 'kvm' || '' }} + + - uses: nix-community/cache-nix-action@v7 + with: + primary-key: nix-${{ runner.os }}-${{ hashFiles('flake.lock', '**/Cargo.lock') }} + restore-prefixes-first-match: nix-${{ runner.os }}- + gc-max-store-size-linux: 8G diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index b84c775b..ffb4a22d 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -27,8 +27,9 @@ jobs: fetch-depth: 0 - uses: EmbarkStudios/cargo-deny-action@v2 - # Everything that does not need a virtual machine: the formatting, clippy, rustdoc and the tests, - # as derivations. The jobs that boot KWin are separate. + # Everything that does not need a virtual machine: the formatting, clippy, rustdoc, the tests and + # the VM library's own tests, as derivations. The jobs that boot KWin are separate, and `nix flake + # check` is not used here because on Linux it would run those suites with no KVM. lint: if: github.repository == 'LGUG2Z/komorebi-for-kde' runs-on: ubuntu-24.04 @@ -36,11 +37,76 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: cachix/install-nix-action@v31 - - uses: nix-community/cache-nix-action@v7 - with: - primary-key: nix-${{ runner.os }}-${{ hashFiles('flake.lock', '**/Cargo.lock') }} - restore-prefixes-first-match: nix-${{ runner.os }}- - gc-max-store-size-linux: 8G - - run: nix flake check -L + - uses: ./.github/actions/nix + - name: Build every check that needs no virtual machine + run: | + nix eval --json .#checks.x86_64-linux --apply builtins.attrNames | + jq -r '(.[] | select(startswith("vm-") | not)), "vm-lib"' | + sed 's|^|.#checks.x86_64-linux.|' | + xargs nix build -L --no-link - run: nix develop --command just lint + + # The suites are found in the flake, so that a new directory under nix/tests/vm/suites is run + # without an edit here. + discover: + if: github.repository == 'LGUG2Z/komorebi-for-kde' + runs-on: ubuntu-24.04 + outputs: + fast: ${{ steps.tiers.outputs.fast }} + slow: ${{ steps.tiers.outputs.slow }} + steps: + - uses: actions/checkout@v7 + - uses: ./.github/actions/nix + - id: tiers + run: | + tiers=$(nix eval --json .#legacyPackages.x86_64-linux.vmTiers) + echo "fast=$(jq -c '.fast // []' <<<"$tiers")" >> "$GITHUB_OUTPUT" + echo "slow=$(jq -c '.slow // []' <<<"$tiers")" >> "$GITHUB_OUTPUT" + + # The pull request gate: the suites that take minutes, each in its own machine, in a sandboxed + # `nix build` like any other check. + vm-fast: + needs: discover + if: github.repository == 'LGUG2Z/komorebi-for-kde' && needs.discover.outputs.fast != '[]' + runs-on: ubuntu-24.04 + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + suite: ${{ fromJson(needs.discover.outputs.fast) }} + steps: + - uses: actions/checkout@v7 + - uses: ./.github/actions/nix + with: + kvm: "true" + - run: nix build -L .#checks.x86_64-linux.vm-${{ matrix.suite }} + + # The suites that draw and move a pointer. They run on master, every week, and on a pull + # request with the label `ci:vm-slow`. The driver is run by hand, outside the sandbox, so that + # the screenshots and the journals of a failed run can be uploaded. + vm-slow: + needs: discover + if: >- + github.repository == 'LGUG2Z/komorebi-for-kde' && needs.discover.outputs.slow != '[]' && + (github.ref == 'refs/heads/master' || github.event_name == 'schedule' || + github.event_name == 'workflow_dispatch' || + contains(github.event.pull_request.labels.*.name, 'ci:vm-slow')) + runs-on: ubuntu-24.04 + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + suite: ${{ fromJson(needs.discover.outputs.slow) }} + steps: + - uses: actions/checkout@v7 + - uses: ./.github/actions/nix + with: + kvm: "true" + - run: nix build -L .#legacyPackages.x86_64-linux.vm.${{ matrix.suite }}.driver -o driver + - run: mkdir -p out && cd out && ../driver/bin/nixos-test-driver -o . + - if: always() + uses: actions/upload-artifact@v7 + with: + name: vm-${{ matrix.suite }}-${{ github.sha }} + path: out/ + retention-days: 7 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9209dddd..f63caf46 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,8 +39,9 @@ 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 -type the repository has. `nix flake check` is what CI runs; it builds the same -checks, plus `cargo deny`, as derivations. +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. ## VM tests @@ -53,8 +54,10 @@ to run one (`just vm NAME`) and how to add one. [`ci.yaml`](.github/workflows/ci.yaml) runs on every pull request and on every push to `master`, `feature/*` and `hotfix/*`, in this repository only. The -`lint` job runs `nix flake check` and the repository's own lint rules, and -`cargo-deny` checks licenses and advisories. A weekly +`lint` job builds every check that needs no virtual machine and runs the +repository's own lint rules, `cargo-deny` checks licenses and advisories, and +the VM tests run on KVM in two jobs: `vm-fast` on every pull request and +`vm-slow` on `master`, every week, and on pull requests labeled `ci:vm-slow`. A weekly [workflow](.github/workflows/update-flake-lock.yaml) opens a pull request that moves `flake.lock`, and the same jobs run on it. diff --git a/README.md b/README.md index 01d29827..02969688 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,8 @@ without a checkout of the toolchain. `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. A Mac +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. diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index 0c34d991..12b584c5 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -14,6 +14,14 @@ they are laid out, how to run them, and how to add one. | A Mac | `just vm NAME`, which runs `scripts/vm-mac` | HVF | | A Linux machine with no KVM | `nix build -L .#legacyPackages.SYSTEM.vmTcg.NAME` | TCG | +CI runs the `fast` tier on every pull request and the `slow` tier on `master`, +every week, and on pull requests labeled `ci:vm-slow` +([`ci.yaml`](../../.github/workflows/ci.yaml)). The slow jobs run the driver +by hand instead of building the check, so that the screenshots and journals of a +failed run can be uploaded as an artifact. KVM on GitHub-hosted runners is +documented for public repositories; the first step of each VM job checks that +`/dev/kvm` is writable and fails there if it is not. + TCG is software emulation. It is slow enough that only short suites are worth running that way, and the library's `scale` argument (below) is 8 for it. From 507c51f0c0c79eaf365d145225b727266cb9bfc2 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 10:01:50 -0700 Subject: [PATCH 007/255] feat(core): the vocabulary the window manager is written in Configuration, commands and the layout code all speak in the same small types: how a new window is added to a workspace, what happens to a window that crosses a monitor boundary, which kind of window a border colour is for, how an application is matched by what it calls itself. They are defined once, in `core`, with the layout types re-exported next to them so that the rest of the crate imports from one place. The layouts themselves are `komorebi-layouts` from komorebi, a git dependency as in komorebi for Mac, at f08aa55 (the tip of master when this was written). That revision has the fix for resizing a tile by dragging its edge (LGUG2Z/komorebi#1765) and the placement helpers this port uses, so nothing is vendored. The crate pulls in serde_yaml, which has an advisory (RUSTSEC-2024-0449, unmaintained unsafe-libyaml) for reading the Windows-only custom layouts; nothing here calls it, and deny.toml says so where it ignores the advisory. The module also has what the rest is built from. `Ring` is a list with one focused element, which monitors, workspaces and containers each keep their children in; it has the unit tests and the example upstream's version never had. `lockable_sequence` keeps locked containers at their positions when others are inserted or removed around them. `core::pathext` resolves environment variables in configured paths, and `core::config_generation` has the rules that match an application, with tests for the two shapes a rule takes in JSON (an object, and a list that must all match). Types that belong to a feature come with the feature: the socket messages, the placement rules and the animation styles are not here. The `impl_ring_elements` macro waits for the first type that uses it. Every module has a `//!` summary, and the README says what the library has. --- Cargo.lock | 679 ++++++++++++++++++++++++- Cargo.toml | 11 + README.md | 9 +- deny.toml | 11 + komorebi/Cargo.toml | 12 + komorebi/src/core/config_generation.rs | 161 ++++++ komorebi/src/core/mod.rs | 254 +++++++++ komorebi/src/core/pathext.rs | 223 ++++++++ komorebi/src/lib.rs | 8 + komorebi/src/lockable_sequence.rs | 368 ++++++++++++++ komorebi/src/ring.rs | 138 +++++ 11 files changed, 1871 insertions(+), 3 deletions(-) create mode 100644 komorebi/src/core/config_generation.rs create mode 100644 komorebi/src/core/mod.rs create mode 100644 komorebi/src/core/pathext.rs create mode 100644 komorebi/src/lib.rs create mode 100644 komorebi/src/lockable_sequence.rs create mode 100644 komorebi/src/ring.rs diff --git a/Cargo.lock b/Cargo.lock index 72b77353..3e2d3efb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,21 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "addr2line" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "android_system_properties" version = "0.1.6" @@ -61,12 +76,54 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "backtrace" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-link", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -91,6 +148,18 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + [[package]] name = "clap" version = "4.6.7" @@ -132,6 +201,33 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "color-eyre" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5920befb47832a6d61ee3a3a846565cfa39b331331e68a3b1d1116630f2f26d" +dependencies = [ + "backtrace", + "color-spantrace", + "eyre", + "indenter", + "once_cell", + "owo-colors", + "tracing-error", +] + +[[package]] +name = "color-spantrace" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8b88ea9df13354b55bc7234ebcce36e6ef896aca2e42a15de9e10edce01b427" +dependencies = [ + "once_cell", + "owo-colors", + "tracing-core", + "tracing-error", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -165,11 +261,79 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror", +] + [[package]] name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] [[package]] name = "displaydoc" @@ -182,6 +346,18 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.14" @@ -192,6 +368,17 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "eyre" +version = "0.6.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08309dbcc659c5549a24ddb9b27027640641b282ef5768267c7e675558986a3" +dependencies = [ + "autocfg", + "indenter", + "once_cell", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -242,25 +429,49 @@ dependencies = [ "r-efi", ] +[[package]] +name = "gimli" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" + [[package]] name = "git2" version = "0.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b88256088d75a56f8ecfa070513a775dd9107f6530ef14919dac831af9cfe2b" dependencies = [ - "bitflags", + "bitflags 2.13.2", "libc", "libgit2-sys", "log", "url", ] +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -368,6 +579,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -389,6 +606,35 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indenter" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5" + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + [[package]] name = "is_debug" version = "1.1.0" @@ -401,6 +647,66 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -427,9 +733,30 @@ name = "komorebi" version = "0.1.0" dependencies = [ "clap", + "komorebi-layouts", + "schemars 1.2.3", + "serde", + "serde_json_lenient", + "serde_with", + "strum", "version", ] +[[package]] +name = "komorebi-layouts" +version = "0.1.42" +source = "git+https://github.com/LGUG2Z/komorebi?rev=f08aa55511d77ca56ab0e789efabeb0a237a463e#f08aa55511d77ca56ab0e789efabeb0a237a463e" +dependencies = [ + "clap", + "color-eyre", + "schemars 1.2.3", + "serde", + "serde_json_lenient", + "serde_yaml", + "strum", + "tracing", +] + [[package]] name = "konst" version = "0.2.20" @@ -445,6 +772,12 @@ version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.191" @@ -493,12 +826,36 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", +] + [[package]] name = "num-conv" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "num_threads" version = "0.1.8" @@ -508,6 +865,15 @@ dependencies = [ "libc", ] +[[package]] +name = "object" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -520,6 +886,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "owo-colors" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -538,6 +910,21 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -577,13 +964,39 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + [[package]] name = "rustix" version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", @@ -596,6 +1009,49 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.9", +] + [[package]] name = "serde" version = "1.0.229" @@ -603,6 +1059,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -625,6 +1082,88 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_json_lenient" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e033097bf0d2b59a62b42c18ebbb797503839b26afdda2c4e1415cb6c813540" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +dependencies = [ + "base64", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.2", + "jiff", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.2", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "shadow-rs" version = "1.7.1" @@ -638,6 +1177,15 @@ dependencies = [ "tzdb", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" @@ -668,6 +1216,27 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "syn" version = "2.0.119" @@ -711,6 +1280,35 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + [[package]] name = "time" version = "0.3.55" @@ -753,6 +1351,65 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-error" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b1581020d7a273442f5b45074a6a57d5757ad0a47dac0e9f0bd57b81936f3db" +dependencies = [ + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "sharded-slab", + "thread_local", + "tracing-core", +] + [[package]] name = "tz-rs" version = "0.7.3" @@ -791,6 +1448,12 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + [[package]] name = "url" version = "2.5.8" @@ -815,6 +1478,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "vcpkg" version = "0.2.15" @@ -1023,3 +1692,9 @@ dependencies = [ "quote", "syn 3.0.9", ] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index f3c18759..cfbbd0c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,8 +7,19 @@ members = ["komorebi", "version"] version = "0.1.0" [workspace.dependencies] +# upstream's layouts, at a revision that has the fix for resizing a tile by dragging its edge +# (LGUG2Z/komorebi#1765) and the placement helpers komorebi for KDE uses +komorebi-layouts = { git = "https://github.com/LGUG2Z/komorebi", rev = "f08aa55511d77ca56ab0e789efabeb0a237a463e", features = [ + "schemars", +] } + clap = { version = "4", features = ["derive", "wrap_help"] } +color-eyre = "0.6" +schemars = "1.1" +serde = { version = "1", features = ["derive"] } +serde_json = { package = "serde_json_lenient", version = "0.2" } shadow-rs = "1" +tracing = "0.1" [workspace.metadata.crane] name = "komorebi-workspace" diff --git a/README.md b/README.md index 02969688..8bc7172c 100644 --- a/README.md +++ b/README.md @@ -21,9 +21,16 @@ without a checkout of the toolchain. ## Crates -- [`komorebi`](komorebi): the daemon. +- [`komorebi`](komorebi): the daemon, and the library behind it. The library has + the vocabulary the window manager is written in (`core`), 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 +for each, are `komorebi-layouts` from [komorebi](https://github.com/LGUG2Z/komorebi), +a git dependency at the revision `Cargo.toml` pins. + ## Checks `just check` runs the formatting check, clippy with warnings denied, the tests diff --git a/deny.toml b/deny.toml index 241fefff..99171afc 100644 --- a/deny.toml +++ b/deny.toml @@ -10,6 +10,11 @@ no-default-features = false [output] 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" }, +] + [licenses] allow = ["Apache-2.0", "MIT", "Unicode-3.0", "Zlib", "LicenseRef-Komorebi-2.0"] confidence-threshold = 0.8 @@ -19,6 +24,11 @@ crate = "komorebi" expression = "LicenseRef-Komorebi-2.0" license-files = [] +[[licenses.clarify]] +crate = "komorebi-layouts" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "version" expression = "LicenseRef-Komorebi-2.0" @@ -35,3 +45,4 @@ external-default-features = "allow" unknown-registry = "deny" unknown-git = "deny" allow-registry = ["https://github.com/rust-lang/crates.io-index"] +allow-git = ["https://github.com/LGUG2Z/komorebi"] diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 57dd1555..31244095 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -5,6 +5,18 @@ description = "A tiling window manager for KDE Plasma" edition = "2024" [dependencies] +komorebi-layouts = { workspace = true } version = { path = "../version" } clap = { workspace = true } +schemars = { workspace = true, optional = true } +serde = { workspace = true } +serde_with = { version = "3", features = ["schemars_1"] } +strum = { version = "0.28", features = ["derive"] } + +[dev-dependencies] +serde_json = { workspace = true } + +[features] +default = ["schemars"] +schemars = ["dep:schemars"] diff --git a/komorebi/src/core/config_generation.rs b/komorebi/src/core/config_generation.rs new file mode 100644 index 00000000..273eee18 --- /dev/null +++ b/komorebi/src/core/config_generation.rs @@ -0,0 +1,161 @@ +//! Rules that match an application by how it identifies itself. +//! +//! A [`MatchingRule`] is the form every list of rules in the configuration takes: a single +//! [`IdWithIdentifier`], or a list of them that must all match. + +use serde::Deserialize; +use serde::Serialize; +use strum::Display; + +use super::ApplicationIdentifier; + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +/// Rule for matching applications +pub enum MatchingRule { + /// Simple matching rule which must evaluate to true + Simple(IdWithIdentifier), + /// Composite matching rule where all conditions must evaluate to true + Composite(Vec), +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Rule for assigning applications to a workspace +pub struct WorkspaceMatchingRule { + /// Target monitor index + pub monitor_index: usize, + /// Target workspace index + pub workspace_index: usize, + /// Matching rule for the application + pub matching_rule: MatchingRule, + /// Whether to apply the rule only when the application is initially launched + pub initial_only: bool, +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Rule for matching applications +pub struct IdWithIdentifier { + /// Kind of identifier to target + pub kind: ApplicationIdentifier, + /// Target identifier + pub id: String, + #[serde(skip_serializing_if = "Option::is_none")] + /// Matching strategy to use + pub matching_strategy: Option, +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Display)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Strategy for matching identifiers +pub enum MatchingStrategy { + /// Should not be used, only kept for backward compatibility + Legacy, + /// Equals + Equals, + /// Starts With + StartsWith, + /// Ends With + EndsWith, + /// Contains + Contains, + /// Regex + Regex, + /// Does not end with + DoesNotEndWith, + /// Does not start with + DoesNotStartWith, + /// Does not equal + DoesNotEqual, + /// Does not contain + DoesNotContain, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct IdWithIdentifierAndComment { + pub kind: ApplicationIdentifier, + pub id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub matching_strategy: Option, +} + +impl From for IdWithIdentifier { + fn from(value: IdWithIdentifierAndComment) -> Self { + Self { + kind: value.kind, + id: value.id.clone(), + matching_strategy: value.matching_strategy, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_rule_that_is_an_object_is_simple() { + let rule: MatchingRule = serde_json::from_str( + r#"{ "kind": "Exe", "id": "foot", "matching_strategy": "Equals" }"#, + ) + .expect("parses"); + + assert_eq!( + rule, + MatchingRule::Simple(IdWithIdentifier { + kind: ApplicationIdentifier::Exe, + id: "foot".to_string(), + matching_strategy: Some(MatchingStrategy::Equals), + }) + ); + } + + #[test] + fn a_rule_that_is_a_list_is_composite() { + let rule: MatchingRule = serde_json::from_str( + r#"[{ "kind": "Exe", "id": "foot" }, { "kind": "Title", "id": "scratch", "matching_strategy": "StartsWith" }]"#, + ) + .expect("parses"); + + let MatchingRule::Composite(parts) = rule else { + panic!("a list of objects is a composite rule"); + }; + assert_eq!(parts.len(), 2); + assert_eq!( + parts[1].matching_strategy, + Some(MatchingStrategy::StartsWith) + ); + } + + #[test] + fn the_matching_strategy_is_left_out_when_there_is_none() { + let rule = IdWithIdentifier { + kind: ApplicationIdentifier::Class, + id: "firefox".to_string(), + matching_strategy: None, + }; + + let json = serde_json::to_string(&rule).expect("serializes"); + + assert_eq!(json, r#"{"kind":"Class","id":"firefox"}"#); + } + + #[test] + fn a_commented_rule_becomes_a_plain_one() { + let commented: IdWithIdentifierAndComment = serde_json::from_str( + r#"{ "kind": "Path", "id": "/usr/bin/kcalc", "comment": "a calculator" }"#, + ) + .expect("parses"); + + let plain = IdWithIdentifier::from(commented); + + assert_eq!(plain.kind, ApplicationIdentifier::Path); + assert_eq!(plain.id, "/usr/bin/kcalc"); + assert_eq!(plain.matching_strategy, None); + } +} diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs new file mode 100644 index 00000000..a3e0c917 --- /dev/null +++ b/komorebi/src/core/mod.rs @@ -0,0 +1,254 @@ +//! The vocabulary of the window manager: the enums and small structs that configuration, +//! commands and the layout code are written in. +//! +//! The layout types ([`DefaultLayout`], [`Rect`], [`OperationDirection`] and the rest) are +//! those of `komorebi-layouts`, re-exported here so that the rest of the crate has one place to +//! import from. [`pathext`] resolves environment variables in configured paths and +//! [`config_generation`] holds the rules that match applications by what they are called. + +use clap::ValueEnum; +use serde::Deserialize; +use serde::Serialize; +use strum::Display; +use strum::EnumString; + +// Re-export types from komorebi-layouts +pub use komorebi_layouts::Arrangement; +pub use komorebi_layouts::Axis; +pub use komorebi_layouts::CycleDirection; +pub use komorebi_layouts::DEFAULT_RATIO; +pub use komorebi_layouts::DEFAULT_SECONDARY_RATIO; +pub use komorebi_layouts::DefaultLayout; +pub use komorebi_layouts::Direction; +pub use komorebi_layouts::GridLayoutOptions; +pub use komorebi_layouts::Layout; +pub use komorebi_layouts::LayoutDefaultEntry; +pub use komorebi_layouts::LayoutOptions; +pub use komorebi_layouts::MAX_RATIO; +pub use komorebi_layouts::MAX_RATIOS; +pub use komorebi_layouts::MIN_RATIO; +pub use komorebi_layouts::OperationDirection; +pub use komorebi_layouts::Rect; +pub use komorebi_layouts::ScrollingLayoutOptions; +pub use komorebi_layouts::Sizing; +pub use komorebi_layouts::validate_ratios; + +// Keep local modules that aren't in komorebi-layouts +pub mod config_generation; +pub mod pathext; + +#[derive( + Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Operation behavior for temporarily unmanaged and floating windows +pub enum OperationBehaviour { + /// Process commands on temporarily unmanaged/floated windows + #[default] + Op, + /// Ignore commands on temporarily unmanaged/floated windows + NoOp, +} + +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq)] +pub struct WindowManagementBehaviour { + /// The current WindowContainerBehaviour to be used + pub current_behaviour: WindowContainerBehaviour, + /// Override of `current_behaviour` to open new windows as floating windows + /// that can be later toggled to tiled, when false it will default to + /// `current_behaviour` again. + pub float_override: bool, + /// Determines if a new window should be spawned floating when on the floating layer and the + /// floating layer behavior is set to float. This value is always calculated when checking for + /// the management behavior on a specific workspace. + pub floating_layer_override: bool, + /// The floating layer behavior to be used if the float override is being used + pub floating_layer_behaviour: FloatingLayerBehaviour, + /// The `Placement` to be used when toggling a window to float + pub toggle_float_placement: Placement, + /// The `Placement` to be used when spawning a window on the floating layer with the + /// `FloatingLayerBehaviour` set to `FloatingLayerBehaviour::Float` + pub floating_layer_placement: Placement, + /// The `Placement` to be used when spawning a window with float override active + pub float_override_placement: Placement, + /// The `Placement` to be used when spawning a window that matches a 'floating_applications' rule + pub float_rule_placement: Placement, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Window container behavior when a new window is opened +pub enum WindowContainerBehaviour { + /// Create a new container for each new window + #[default] + Create, + /// Append new windows to the focused window container + Append, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Floating layer behavior when a new window is opened +pub enum FloatingLayerBehaviour { + /// Tile new windows (unless they match a float rule or float override is active) + #[default] + Tile, + /// Float new windows + Float, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Window hiding position +pub enum WindowHidingPosition { + /// Hide windows in the bottom left corner of the screen + #[default] + BottomLeft, + /// Hide windows in the bottom right corner of the screen + BottomRight, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Placement behavior for floating windows +pub enum Placement { + /// Does not change the size or position of the window + #[default] + None, + /// Center the window without changing the size + Center, + /// Center the window and resize it according to the `AspectRatio` + CenterAndResize, +} + +impl FloatingLayerBehaviour { + pub fn should_float(&self) -> bool { + match self { + FloatingLayerBehaviour::Tile => false, + FloatingLayerBehaviour::Float => true, + } + } +} + +impl Placement { + pub fn should_center(&self) -> bool { + match self { + Placement::None => false, + Placement::Center | Placement::CenterAndResize => true, + } + } + + pub fn should_resize(&self) -> bool { + match self { + Placement::None | Placement::Center => false, + Placement::CenterAndResize => true, + } + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Focus follows mouse implementation +/// +/// The two exist on Windows. On KDE the compositor does it, so both ask KWin for its +/// "focus follows mouse" focus policy. +pub enum FocusFollowsMouseImplementation { + /// Custom FFM implementation (slightly more CPU-intensive) + Komorebi, + /// Native (legacy) Windows FFM implementation + Windows, +} + +#[derive( + Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Move behavior when the operation works across a monitor boundary +pub enum MoveBehaviour { + /// Swap the window container with the window container at the edge of the adjacent monitor + #[default] + Swap, + /// Insert the window container into the focused workspace on the adjacent monitor + Insert, + /// Do nothing if trying to move a window container in the direction of an adjacent monitor + NoOp, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Behavior when an action would cross a monitor boundary +pub enum CrossBoundaryBehaviour { + /// Attempt to perform actions across a workspace boundary + Workspace, + /// Attempt to perform actions across a monitor boundary + #[default] + Monitor, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Behavior when focusing in a direction while a monocle container is active +pub enum MonocleFocusBehaviour { + /// Cycle the monocle container to the next/previous container in the workspace + Cycle, + /// Do nothing, allowing focus to fall through to cross-monitor logic + #[default] + NoOp, +} + +#[derive( + Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Application identifier +pub enum ApplicationIdentifier { + /// Executable name + #[serde(alias = "exe")] + Exe, + /// Role or subrole + #[serde(alias = "class")] + Class, + /// Window title + #[serde(alias = "title")] + Title, + /// Executable path + #[serde(alias = "path")] + Path, +} + +#[derive( + Copy, + Clone, + Debug, + Default, + Serialize, + Deserialize, + Display, + EnumString, + ValueEnum, + PartialEq, + Eq, + Hash, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum WindowKind { + Single, + Stack, + Monocle, + #[default] + Unfocused, + UnfocusedLocked, + Floating, +} diff --git a/komorebi/src/core/pathext.rs b/komorebi/src/core/pathext.rs new file mode 100644 index 00000000..729f7e88 --- /dev/null +++ b/komorebi/src/core/pathext.rs @@ -0,0 +1,223 @@ +//! Resolving environment variables in the paths of the configuration. + +use std::collections::HashMap; +use std::ffi::OsStr; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +use serde::Deserialize; +use serde::Serialize; + +/// Path extension trait +pub trait PathExt { + /// Resolve environment variable components in a path. + /// + /// Resolves the following formats: + /// - CMD: `%variable%` + /// - PowerShell: `$Env:variable` + /// - Bash: `$variable`. + fn replace_env(&self) -> PathBuf; +} + +/// Blanket implementation for all types that can be converted to a `Path`. +impl> PathExt for P { + fn replace_env(&self) -> PathBuf { + let mut out = PathBuf::new(); + + for c in self.as_ref().components() { + match c { + #[allow(unused_mut)] + Component::Normal(mut c) => { + #[cfg(target_os = "windows")] + // Special case for ~ and $HOME, replace with $Env:USERPROFILE + if c == OsStr::new("~") || c.eq_ignore_ascii_case("$HOME") { + c = OsStr::new("$Env:USERPROFILE"); + } + + #[cfg(unix)] + // Special case for ~, replace with $HOME (macOS and Linux) + if c == OsStr::new("~") { + c = OsStr::new("$HOME"); + } + + let bytes = c.as_encoded_bytes(); + + // %LOCALAPPDATA% + let var = if bytes[0] == b'%' && bytes[bytes.len() - 1] == b'%' { + Some(&bytes[1..bytes.len() - 1]) + } else { + // prefix length is 5 for $Env: and 1 for $ + // so we take the minimum of 5 and the length of the bytes + let prefix = &bytes[..5.min(bytes.len())]; + let prefix = unsafe { OsStr::from_encoded_bytes_unchecked(prefix) }; + + // $Env:LOCALAPPDATA + if prefix.eq_ignore_ascii_case("$Env:") { + Some(&bytes[5..]) + } else if bytes[0] == b'$' { + // $LOCALAPPDATA + Some(&bytes[1..]) + } else { + // not a variable + None + } + }; + + // if component is a variable, get the value from the environment + if let Some(var) = var { + let var = unsafe { OsStr::from_encoded_bytes_unchecked(var) }; + if let Some(value) = std::env::var_os(var) { + out.push(value); + continue; + } + } + + // if not a variable, or a value couldn't be obtained from environemnt + // then push the component as is + out.push(c); + } + + // other components are pushed as is + _ => out.push(c), + } + } + + out + } +} + +/// Replace environment variables in a path. This is a wrapper around +/// [`PathExt::replace_env`] to be used in Clap arguments parsing. +pub fn replace_env_in_path(input: &str) -> Result { + Ok(input.replace_env()) +} + +/// A wrapper around [`PathBuf`] that has a custom [Deserialize] implementation +/// that uses [`PathExt::replace_env`] to resolve environment variables +#[derive(Clone, Debug)] +pub struct ResolvedPathBuf(PathBuf); + +impl ResolvedPathBuf { + /// Create a new [`ResolvedPathBuf`] from a [`PathBuf`] + pub fn new(path: PathBuf) -> Self { + Self(path.replace_env()) + } +} + +impl From for PathBuf { + fn from(path: ResolvedPathBuf) -> Self { + path.0 + } +} + +impl serde_with::SerializeAs for ResolvedPathBuf { + fn serialize_as(path: &PathBuf, serializer: S) -> Result + where + S: serde::Serializer, + { + path.serialize(serializer) + } +} + +impl<'de> serde_with::DeserializeAs<'de, PathBuf> for ResolvedPathBuf { + fn deserialize_as(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let path = PathBuf::deserialize(deserializer)?; + Ok(path.replace_env()) + } +} + +#[cfg(feature = "schemars")] +impl serde_with::schemars_1::JsonSchemaAs for ResolvedPathBuf { + fn schema_name() -> std::borrow::Cow<'static, str> { + std::borrow::Cow::Borrowed("PathBuf") + } + + fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ + "type": "string", + "description": "A file system path. Environment variables like $VAR are automatically resolved." + }) + } +} + +/// Custom deserializer for [`Option>`] that uses +/// [`PathExt::replace_env`] to resolve environment variables in the paths. +/// +/// This is used in `WorkspaceConfig` struct because we can't use +/// #[serde_with::serde_as] as it doesn't handle [`Option>`] +/// quite well and generated compiler errors that can't be fixed because of Rust's orphan rule. +pub fn resolve_option_hashmap_usize_path<'de, D>( + deserializer: D, +) -> Result>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let map = Option::>::deserialize(deserializer)?; + Ok(map.map(|map| map.into_iter().map(|(k, v)| (k, v.replace_env())).collect())) +} + +#[cfg(test)] +mod tests { + use super::*; + + // helper functions + fn expected>(p: P) -> PathBuf { + // Ensure that the path is using the correct path separator for the OS. + p.as_ref().components().collect::() + } + + fn resolve>(p: P) -> PathBuf { + p.replace_env() + } + + #[test] + fn resolves_env_vars() { + // Set a variable for testing + unsafe { + std::env::set_var("VAR", "VALUE"); + } + + // %VAR% format + assert_eq!(resolve("/path/%VAR%/d"), expected("/path/VALUE/d")); + // $env:VAR format + assert_eq!(resolve("/path/$env:VAR/d"), expected("/path/VALUE/d")); + // $VAR format + assert_eq!(resolve("/path/$VAR/d"), expected("/path/VALUE/d")); + + // non-existent variable + assert_eq!(resolve("/path/%ASD%/to/d"), expected("/path/%ASD%/to/d")); + assert_eq!( + resolve("/path/$env:ASD/to/d"), + expected("/path/$env:ASD/to/d") + ); + assert_eq!(resolve("/path/$ASD/to/d"), expected("/path/$ASD/to/d")); + + #[cfg(target_os = "windows")] + { + // Set a $env:USERPROFILE variable for testing + unsafe { + std::env::set_var("USERPROFILE", "C:\\Users\\user"); + } + + // ~ and $HOME should be replaced with $Env:USERPROFILE + assert_eq!(resolve("~"), expected("C:\\Users\\user")); + assert_eq!(resolve("$HOME"), expected("C:\\Users\\user")); + } + + #[cfg(unix)] + { + // Set a $env:USERPROFILE variable for testing + unsafe { + std::env::set_var("HOME", "/Users/user"); + } + + // ~ and $HOME should be replaced with $Env:USERPROFILE + assert_eq!(resolve("~"), expected("/Users/user")); + assert_eq!(resolve("$HOME"), expected("/Users/user")); + } + } +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs new file mode 100644 index 00000000..b42ba833 --- /dev/null +++ b/komorebi/src/lib.rs @@ -0,0 +1,8 @@ +//! The komorebi daemon's library: the vocabulary the window manager is written in and the data +//! structures it is built from. + +#[macro_use] +pub mod ring; + +pub mod core; +pub mod lockable_sequence; diff --git a/komorebi/src/lockable_sequence.rs b/komorebi/src/lockable_sequence.rs new file mode 100644 index 00000000..421eb22d --- /dev/null +++ b/komorebi/src/lockable_sequence.rs @@ -0,0 +1,368 @@ +//! Lists in which some elements are locked in place. +//! +//! A locked container keeps its position in the layout when others are inserted, removed or +//! swapped around it. [`LockableSequence`] does that bookkeeping for a [`VecDeque`]. + +use std::collections::VecDeque; + +/// A trait for types that can be marked as locked or unlocked. +pub trait Lockable { + /// Returns `true` if the item is locked. + fn locked(&self) -> bool; + /// Sets the locked state of the item. + fn set_locked(&mut self, locked: bool) -> &mut Self; +} + +/// A sequence supporting insertion, removal, and swapping of elements while preserving the absolute +/// positions of locked items. +pub trait LockableSequence { + /// Inserts a value at `idx`, keeping locked elements at their absolute positions. + fn insert_respecting_locks(&mut self, idx: usize, value: T) -> usize; + /// Removes the element at `idx`, keeping locked elements at their absolute positions. + fn remove_respecting_locks(&mut self, idx: usize) -> Option; + /// Swaps the elements at indices `i` and `j`, keeping locked elements at their absolute positions. + fn swap_respecting_locks(&mut self, i: usize, j: usize); +} + +impl LockableSequence for VecDeque { + /// Insert `value` at logical index `idx`, with trying to keep locked elements + /// (`is_locked()`) anchored at their original positions. + /// + /// Returns the final index of the inserted element. + fn insert_respecting_locks(&mut self, mut idx: usize, value: T) -> usize { + // 1. Bounds check: if index is out of range, simply append. + if idx >= self.len() { + self.push_back(value); + return self.len() - 1; // last index + } + + // 2. Normal VecDeque insertion + self.insert(idx, value); + + // 3. Walk left-to-right once, swapping any misplaced locked element. After + // the VecDeque::insert all items after `idx` have moved right by one. For every locked + // element that is now to the right of an unlocked one, swap it back left exactly once. + for index in (idx + 1)..self.len() { + if self[index].locked() && !self[index - 1].locked() { + self.swap(index - 1, index); + + // If the element we just inserted participated in the swap, + // update `idx` so we can return its final location. + if idx == index - 1 { + idx = index; + } + } + } + idx + } + + /// Remove element at `idx`, with trying to keep locked elements + /// (`is_locked()`) anchored at their original positions. + /// + /// Returns the removed element, or `None` if `idx` is out of bounds. + fn remove_respecting_locks(&mut self, idx: usize) -> Option { + // 1. Bounds check: if index is out of range, do nothing. + if idx >= self.len() { + return None; + } + + // 2. Remove the element at the requested index. + // All elements after idx are now shifted left by 1. + let removed = self.remove(idx)?; + + // 3. If less than 2 elements remain, nothing to shift. + if self.len() < 2 { + return Some(removed); + } + + // 4. Iterate from the element just after the removed spot up to the second-to-last + // element, right-to-left. This loop "fixes" locked elements that were shifted left + // off their anchored positions: If a locked element now has an unlocked element + // to its right, swap them back to restore locked order. + for index in (idx..self.len() - 1).rev() { + // If current is locked and the next one is not locked, swap them. + if self[index].locked() && !self[index + 1].locked() { + self.swap(index, index + 1); + } + } + + // 5. Return the removed value. + Some(removed) + } + + /// Swaps the elements at indices `i` and `j`, along with their `locked` status, ensuring + /// the lock state remains associated with the position rather than the element itself. + fn swap_respecting_locks(&mut self, i: usize, j: usize) { + self.swap(i, j); + let locked_i = self[i].locked(); + let locked_j = self[j].locked(); + self[i].set_locked(locked_j); + self[j].set_locked(locked_i); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Debug, PartialEq)] + struct TestItem { + val: i32, + locked: bool, + } + + impl Lockable for TestItem { + fn locked(&self) -> bool { + self.locked + } + + fn set_locked(&mut self, locked: bool) -> &mut Self { + self.locked = locked; + self + } + } + + fn vals(v: &VecDeque) -> Vec { + v.iter().map(|x| x.val).collect() + } + + fn test_deque(items: &[(i32, bool)]) -> VecDeque { + items + .iter() + .cloned() + .map(|(val, locked)| TestItem { val, locked }) + .collect() + } + + #[test] + fn test_insert_respecting_locks() { + // Test case 1: Basic insertion with locked index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + // Insert at index 0, should shift elements while keeping index 2 locked + ring.insert_respecting_locks( + 0, + TestItem { + val: 99, + locked: false, + }, + ); + // Element '2' remains at index 2, element '1' that was at index 1 is now at index 3 + assert_eq!(vals(&ring), vec![99, 0, 2, 1, 3, 4]); + } + + // Test case 2: Insert at a locked index (should insert after locked) + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + // Try to insert at locked index 2, should insert at index 3 instead + let actual_index = ring.insert_respecting_locks( + 2, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 3); + assert_eq!(vals(&ring), vec![0, 1, 2, 99, 3, 4]); + } + + // Test case 3: Multiple locked indices + { + // Lock index 1 and 3 + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, true), (4, false)]); + // Insert at index 0, should maintain locked indices + ring.insert_respecting_locks( + 0, + TestItem { + val: 99, + locked: false, + }, + ); + // Elements '1' and '3' remain at indices 1 and 3 + assert_eq!(vals(&ring), vec![99, 1, 0, 3, 2, 4]); + } + + // Test case 4: Insert at end + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let actual_index = ring.insert_respecting_locks( + 5, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 5); + assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4, 99]); + } + + // Test case 5: Empty ring + { + let mut ring = test_deque(&[]); + // Insert into empty deque + let actual_index = ring.insert_respecting_locks( + 0, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 0); + assert_eq!(vals(&ring), vec![99]); + } + + // Test case 6: All indices locked + { + // Lock all indices + let mut ring = test_deque(&[(0, true), (1, true), (2, true), (3, true), (4, true)]); + // Try to insert at index 2, should insert at the end + let actual_index = ring.insert_respecting_locks( + 2, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 5); + assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4, 99]); + } + + // Test case 7: Consecutive locked indices + { + // Lock index 2 and 3 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, true), (4, false)]); + // Insert at index 1, should maintain consecutive locked indices + ring.insert_respecting_locks( + 1, + TestItem { + val: 99, + locked: false, + }, + ); + // Elements '2' and '3' remain at indices 2 and 3 + assert_eq!(vals(&ring), vec![0, 99, 2, 3, 1, 4]); + } + } + + #[test] + fn test_remove_respecting_locks() { + // Test case 1: Remove a non-locked index before a locked index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(0); + assert_eq!(removed.map(|x| x.val), Some(0)); + // Elements '2' remain at index 2 + assert_eq!(vals(&ring), vec![1, 3, 2, 4]); + } + + // Test case 2: Remove a locked index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(2); + assert_eq!(removed.map(|x| x.val), Some(2)); + // Elements should stay at the same places + assert_eq!(vals(&ring), vec![0, 1, 3, 4]); + } + + // Test case 3: Remove an index after a locked index + { + // Lock index 1 + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(3); + assert_eq!(removed.map(|x| x.val), Some(3)); + // Elements should stay at the same places + assert_eq!(vals(&ring), vec![0, 1, 2, 4]); + } + + // Test case 4: Multiple locked indices + { + // Lock index 1 and 3 + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, true), (4, false)]); + let removed = ring.remove_respecting_locks(0); + assert_eq!(removed.map(|x| x.val), Some(0)); + // Elements '1' and '3' remain at indices '1' and '3' + assert_eq!(vals(&ring), vec![2, 1, 4, 3]); + } + + // Test case 5: Remove the last element + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(4); + assert_eq!(removed.map(|x| x.val), Some(4)); + // Index 2 should still be at the same place + assert_eq!(vals(&ring), vec![0, 1, 2, 3]); + } + + // Test case 6: Invalid index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(10); + assert_eq!(removed, None); + // Deque unchanged + assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4]); + } + + // Test case 7: Remove enough elements to make a locked index invalid + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true)]); + ring.remove_respecting_locks(0); + // Index 2 should now be '1' + assert_eq!(vals(&ring), vec![1, 2]); + } + + // Test case 8: Removing an element before multiple locked indices + { + // Lock index 2 and 4 + let mut ring = test_deque(&[ + (0, false), + (1, false), + (2, true), + (3, false), + (4, true), + (5, false), + ]); + let removed = ring.remove_respecting_locks(1); + assert_eq!(removed.map(|x| x.val), Some(1)); + // Both indices should still be at the same place + assert_eq!(vals(&ring), vec![0, 3, 2, 5, 4]); + } + } + + #[test] + fn test_swap_respecting_locks_various_cases() { + // Swap unlocked and locked + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, false)]); + ring.swap_respecting_locks(0, 1); + assert_eq!(vals(&ring), vec![1, 0, 2, 3]); + assert!(!ring[0].locked); + assert!(ring[1].locked); + ring.swap_respecting_locks(0, 1); + assert_eq!(vals(&ring), vec![0, 1, 2, 3]); + assert!(!ring[0].locked); + assert!(ring[1].locked); + + // Both locked + let mut ring = test_deque(&[(0, true), (1, false), (2, true)]); + ring.swap_respecting_locks(0, 2); + assert_eq!(vals(&ring), vec![2, 1, 0]); + assert!(ring[0].locked); + assert!(!ring[1].locked); + assert!(ring[2].locked); + + // Both unlocked + let mut ring = test_deque(&[(0, false), (1, true), (2, false)]); + ring.swap_respecting_locks(0, 2); + assert_eq!(vals(&ring), vec![2, 1, 0]); + assert!(!ring[0].locked); + assert!(ring[1].locked); + assert!(!ring[2].locked); + } +} diff --git a/komorebi/src/ring.rs b/komorebi/src/ring.rs new file mode 100644 index 00000000..0e16e2fb --- /dev/null +++ b/komorebi/src/ring.rs @@ -0,0 +1,138 @@ +//! [`Ring`], a list of elements with one of them focused. +//! +//! Monitors, workspaces and containers each keep their children in a ring, so that "the focused +//! one" is the same thing everywhere. + +use std::collections::VecDeque; + +use serde::Deserialize; +use serde::Serialize; + +/// A list of elements, one of which is focused. +/// +/// The focused index is not guaranteed to be in range: [`Ring::focus`] stores what it is given, and +/// [`Ring::focused`] and [`Ring::focused_mut`] return `None` when it is out of range, as it is for +/// an empty ring. +/// +/// # Example +/// +/// ```rust +/// use komorebi::ring::Ring; +/// +/// let mut ring = Ring::default(); +/// ring.elements_mut().push_back("a"); +/// ring.elements_mut().push_back("b"); +/// ring.focus(1); +/// +/// assert_eq!(ring.focused(), Some(&"b")); +/// assert_eq!(ring.focused_idx(), 1); +/// ``` +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct Ring { + elements: VecDeque, + focused: usize, +} + +impl Default for Ring { + fn default() -> Self { + Self { + elements: VecDeque::default(), + focused: 0, + } + } +} + +impl Ring { + /// The elements, in order. + pub const fn elements(&self) -> &VecDeque { + &self.elements + } + + /// The elements, in order, to add to or remove from. + pub fn elements_mut(&mut self) -> &mut VecDeque { + &mut self.elements + } + + /// Focuses the element at `idx`. + pub fn focus(&mut self, idx: usize) { + self.focused = idx; + } + + /// The focused element, if the focused index is in range. + pub fn focused(&self) -> Option<&T> { + self.elements.get(self.focused) + } + + /// The index that is focused, in range or not. + pub const fn focused_idx(&self) -> usize { + self.focused + } + + /// The focused element, to change, if the focused index is in range. + pub fn focused_mut(&mut self) -> Option<&mut T> { + self.elements.get_mut(self.focused) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_empty_ring_focuses_nothing() { + let mut ring: Ring = Ring::default(); + + assert_eq!(ring.focused(), None); + assert_eq!(ring.focused_mut(), None); + assert_eq!(ring.focused_idx(), 0); + } + + #[test] + fn focus_selects_the_element_at_that_index() { + let mut ring = Ring::default(); + ring.elements_mut().extend([10, 20, 30]); + + ring.focus(2); + + assert_eq!(ring.focused(), Some(&30)); + assert_eq!(ring.focused_idx(), 2); + } + + #[test] + fn the_focused_element_can_be_changed_in_place() { + let mut ring = Ring::default(); + ring.elements_mut().extend([1, 2]); + ring.focus(1); + + if let Some(element) = ring.focused_mut() { + *element = 5; + } + + assert_eq!(ring.elements(), &[1, 5]); + } + + #[test] + fn a_focused_index_past_the_end_focuses_nothing() { + let mut ring = Ring::default(); + ring.elements_mut().push_back('a'); + + ring.focus(3); + + assert_eq!(ring.focused(), None); + assert_eq!(ring.focused_idx(), 3); + } + + #[test] + fn a_ring_round_trips_through_json() { + let mut ring = Ring::default(); + ring.elements_mut() + .extend(["a".to_string(), "b".to_string()]); + ring.focus(1); + + let json = serde_json::to_string(&ring).expect("serializes"); + let back: Ring = serde_json::from_str(&json).expect("deserializes"); + + assert_eq!(back, ring); + } +} From ed6a8e96c3b9d822af8a6d4dc80c100aae9e876d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 10:19:39 -0700 Subject: [PATCH 008/255] feat(backend): reach the compositor through one trait The window manager decides where every window goes, and asks a compositor to put it there. If it asked KWin directly, every test of its logic would have to boot a virtual machine, so everything it needs from the desktop goes through one trait, `Backend`: queries for windows, monitors, the focus and the pointer, and commands to move, focus, raise, minimize and close a window and to put the pointer somewhere. A real backend answers from a table that compositor events keep up to date, so a query never waits for the compositor; a command returns once it has been accepted, not once the client has acted. `FakeBackend` is the other implementation: an in-memory desktop that does what it is told, at once and exactly, and records every command so that a test can assert on what the window manager asked for. A test can also do what a user does without the window manager asking: move a window, close it, change the focus, turn a window into a dialog. It is strict where KWin is (a command about a window that is gone is an error) and clamps where a GTK4 client does (a minimum size). `with_backend` overrides the process-wide backend for the current thread only and puts the previous one back on drop, also on a panic, which is what keeps one test's desktop out of the next. The module is the first to have `#![deny(missing_docs)]`. The contract (what must be implemented, that a backend is `Send + Sync`) is proved by two `compile_fail` examples with their error codes, and the rules nothing checks are listed as such. docs/dev/ARCHITECTURE.md describes the trait, its roles and the layer that enforces each rule, and docs/dev/DESIGN.md has the first decisions with their reasons. Both grow with the code. --- Cargo.lock | 49 ++++ README.md | 19 +- docs/dev/ARCHITECTURE.md | 99 +++++++ docs/dev/DESIGN.md | 50 ++++ komorebi/Cargo.toml | 2 + komorebi/src/backend/fake.rs | 513 +++++++++++++++++++++++++++++++++++ komorebi/src/backend/mod.rs | 380 ++++++++++++++++++++++++++ komorebi/src/lib.rs | 1 + 8 files changed, 1109 insertions(+), 4 deletions(-) create mode 100644 docs/dev/ARCHITECTURE.md create mode 100644 docs/dev/DESIGN.md create mode 100644 komorebi/src/backend/fake.rs create mode 100644 komorebi/src/backend/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 3e2d3efb..5e1629d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -733,7 +733,9 @@ name = "komorebi" version = "0.1.0" dependencies = [ "clap", + "color-eyre", "komorebi-layouts", + "parking_lot", "schemars 1.2.3", "serde", "serde_json_lenient", @@ -820,6 +822,15 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -892,6 +903,29 @@ version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -964,6 +998,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "ref-cast" version = "1.0.27" @@ -1052,6 +1095,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "serde" version = "1.0.229" diff --git a/README.md b/README.md index 8bc7172c..4439ddc5 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,10 @@ without a checkout of the toolchain. ## Crates - [`komorebi`](komorebi): the daemon, and the library behind it. The library has - the vocabulary the window manager is written in (`core`), the `Ring` that - holds monitors, workspaces and containers, and the lists in which some - elements are locked in place. + 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 `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 @@ -45,10 +46,20 @@ The VM tests boot NixOS with Plasma and run a real KWin. `just vm NAME` runs one; [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) has the details, including how to run them on a Mac. +## How it fits together + +The daemon decides where every window goes and asks the compositor to put it +there. Everything it needs from the compositor is behind one trait, `Backend`, +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. + ## Documentation `cargo doc --workspace --no-deps --open` builds the API documentation. -[`CONTRIBUTING.md`](CONTRIBUTING.md) says how to work on the code, and +[`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. ## License diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md new file mode 100644 index 00000000..90ba1c37 --- /dev/null +++ b/docs/dev/ARCHITECTURE.md @@ -0,0 +1,99 @@ +# Architecture + +komorebi is a tiling window manager. It decides where every window goes and asks a +compositor to put it there. Everything it needs from the compositor is behind one trait, +[`Backend`](../../komorebi/src/backend/mod.rs), so the window manager is written, and +tested, without one. + +This page describes that trait, who implements and calls it, and where each of its rules +is enforced. It grows with the code: each part of the daemon that is added has its place +here. + +## Vocabulary + +- **Window**: a top-level surface a client has asked the compositor for, named by the + compositor's `u32` id. +- **Monitor**: a connected output, with its bounds and its work area (its bounds minus + the panels). +- **Compositor**: the program that owns the screen and the windows. On KDE Plasma it is + KWin. +- **Backend**: the implementation of the [`Backend`](../../komorebi/src/backend/mod.rs) + trait that talks to a compositor. +- **Fake**: [`FakeBackend`](../../komorebi/src/backend/fake.rs), the in-memory backend + the tests use. + +## Design + +The window manager reads the desktop and changes it through [`Backend`] and through +nothing else. A real backend answers from a table that compositor events keep up to date, +and sends commands to the compositor. The fake answers from a table the test fills in, and +records the commands. The window manager cannot tell them apart, which is the point: +the same logic runs against both. The reasons are in +[DESIGN.md](DESIGN.md#why-is-everything-the-window-manager-needs-behind-one-trait). + +## The model + +The desktop, as the window manager sees it, is two lists and a pointer: + +- **Windows**, each a [`WindowInfo`]: its id, process, title, `app_id`, executable, frame, + whether it is minimized, whether it is a normal application window (as opposed to a + dialog, a splash screen or a dock), and whether it is alive. A window that has been + destroyed stays in the table for a short time with `alive` false, so that the event that + mentions it can still be logged. +- **Monitors**, each a [`MonitorInfo`]: its id, name, an identity that survives a + hot-plug, its bounds and its work area. +- **The pointer**, a position if the compositor says where it is, and the **focus**, the id + of the window that has it. + +A command is one of: move and resize a window, focus it, raise it, minimize it or bring it +back, close it, and put the pointer in the middle of a rectangle. + +## The parts + +- [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the + process-wide handle ([`set_backend`], [`backend`], [`with_backend`]). +- [`backend::fake`](../../komorebi/src/backend/fake.rs): the fake. + +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 +its own thread with [`with_backend`], which puts the previous one back when the test is +done, also if it panics. + +## Traits and roles + +**[`Backend`] is the compositor.** It is implemented once for each compositor and once for +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. +- 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. +- A command about a window that does not exist, or is no longer alive, is an error. It + never panics. +- `shutdown`, `is_window`, `window_rect` and `monitor_from_point` have defaults, written in + terms of the queries. An implementor should not need to override them, except `shutdown` + when it created something in the compositor that has to be given up. + +## What is guaranteed, and by what + +| Rule | Enforced by | Proof | Escape hatch | +|---|---|---|---| +| A backend implements every query and command | type system: the methods have no defaults | `compile_fail,E0046` on [`Backend`] | none | +| A backend can be shared between threads | type system: `Backend: Send + Sync + 'static` | `compile_fail,E0277` on [`Backend`] | none | +| The window manager asks for a backend that was never installed | runtime error: [`backend`] panics, naming [`set_backend`] and [`with_backend`] | `# Panics` on [`backend`] | none | +| A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none | +| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error`, against the fake only | none | +| Queries never block on the compositor | convention only | none | none | +| 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. + +## Where to look in the code + +- [`komorebi/src/backend/mod.rs`](../../komorebi/src/backend/mod.rs): the trait. +- [`komorebi/src/backend/fake.rs`](../../komorebi/src/backend/fake.rs): the fake and its + tests. +- [`komorebi/src/core`](../../komorebi/src/core/mod.rs): the vocabulary the rest is written + in. diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md new file mode 100644 index 00000000..c51507cf --- /dev/null +++ b/docs/dev/DESIGN.md @@ -0,0 +1,50 @@ +# Design + +This document explains why komorebi for KDE is built the way it is, one decision at a time. +It is opinionated: these are the reasons behind the code, and reasonable people may disagree +with them. Where a reason was not written down, the entry says that it needs one. + +It grows with the code: a decision is added in the commit that makes it. + +## What is komorebi for KDE the port of? + +komorebi has a Windows implementation, the original, and a macOS one. The Windows one is +the reference. I used it as the reference for what to adapt, and I prefer what KDE and +Wayland do natively over a workaround that the other two platforms need. The events the +window manager reacts to follow the Windows ones (a window is shown, destroyed, focused, +minimized, moved, resized), and a window is a small `Copy` handle, as there. + +## Why is everything the window manager needs behind one trait? + +So that the window manager can be tested without a compositor. A test that needs a real +KWin has to boot a virtual machine, which takes a minute or more and needs QEMU with a +hypervisor ([vm-tests.md](vm-tests.md)); a test against an in-memory desktop takes +milliseconds and runs anywhere. The logic (which window goes where, what happens when one +closes, how a stack cycles) is tested with the second kind, and the VM tests are kept for +what only KWin can tell. + +The cost is that a second implementation has to be kept honest. A fake that does what it +is told is not KWin: a real client may refuse a size, a compositor may report an event the +fake never raises, and a fake that is too permissive hides a bug that a compositor would +show. The fake is therefore written to be strict where KWin is (a command about a window +that no longer exists is an error) and to clamp where a real client does (a window with a +minimum size keeps to it). + +## Why is the backend a process-wide singleton? + +So that a window can be a small `Copy` value that carries only its id. A window that +had to hold a reference to its backend would not be `Copy`, and every function that +moves, focuses or hides one would take a context argument as well. That is a lot of +plumbing for a thing that never changes while the daemon runs. + +The cost is a global. A test that wants a private desktop overrides it for its own thread +with `with_backend`, which restores the previous one afterwards, also on a panic. + +## Why does a backend answer from a table instead of asking the compositor? + +A query that waits for the compositor can wait for a long time, and the window manager +asks a lot of questions: every move of a container is followed by a look at where each +window ended up. A backend keeps a table that the compositor's events update, so a query +is a lookup. The trade-off is that the table can be a moment behind the compositor, which +is why a command returns when it has been accepted and not when the client has acted, and +why the frame a window really has is read back afterwards. diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 31244095..bc455c9c 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -9,6 +9,8 @@ komorebi-layouts = { workspace = true } version = { path = "../version" } clap = { workspace = true } +color-eyre = { workspace = true } +parking_lot = "0.12" schemars = { workspace = true, optional = true } serde = { workspace = true } serde_with = { version = "3", features = ["schemars_1"] } diff --git a/komorebi/src/backend/fake.rs b/komorebi/src/backend/fake.rs new file mode 100644 index 00000000..8e2ee60f --- /dev/null +++ b/komorebi/src/backend/fake.rs @@ -0,0 +1,513 @@ +//! An in-memory desktop, so that window manager logic can be tested without a compositor. +//! +//! A [`FakeBackend`] does what it is told, at once and exactly: a window asked to move to a +//! rectangle is at that rectangle, unless it was given a minimum size, which it then keeps to the +//! way a GTK4 client does. Every command is recorded, so that a test can assert on what the window +//! manager asked for, and a test can do what a user does (move a window, close it, change which +//! one has the focus) without the window manager having asked. +//! +//! # Example +//! +//! ```rust +//! use komorebi::backend::Backend; +//! use komorebi::backend::fake::Command; +//! use komorebi::backend::fake::FakeBackend; +//! use komorebi::core::Rect; +//! +//! let fake = FakeBackend::with_one_monitor(); +//! fake.open_window(1, "foot", "foot", "a terminal"); +//! +//! let tile = Rect { left: 0, top: 0, right: 960, bottom: 1050 }; +//! fake.set_rect(1, &tile)?; +//! +//! assert_eq!(fake.rect_of(1), Some(tile)); +//! assert_eq!(fake.commands(), [Command::SetRect(1, tile)]); +//! # Ok::<(), color_eyre::eyre::Report>(()) +//! ``` + +#![deny(missing_docs)] + +use super::Backend; +use super::MonitorInfo; +use super::WindowInfo; +use crate::core::Rect; +use color_eyre::eyre; +use parking_lot::Mutex; +use std::collections::HashMap; + +/// A command the window manager sent to the backend. +#[derive(Clone, Debug, PartialEq)] +pub enum Command { + /// [`Backend::set_rect`]: the window and the rectangle it was asked to take. + SetRect(u32, Rect), + /// [`Backend::focus`]: the window, and whether the pointer was to follow. + Focus(u32, bool), + /// [`Backend::raise`]. + Raise(u32), + /// [`Backend::minimize`]. + Minimize(u32), + /// [`Backend::unminimize`]. + Unminimize(u32), + /// [`Backend::close`]. + Close(u32), + /// [`Backend::center_cursor_in`]. + CenterCursor(Rect), +} + +#[derive(Default)] +struct State { + /// When set, a command about a window nobody opened creates that window first (see + /// [`FakeBackend::permissive`]). + permissive: bool, + windows: HashMap, + min_sizes: HashMap, + monitors: Vec, + foreground: Option, + cursor: Option<(i32, i32)>, + commands: Vec, +} + +/// An in-memory [`Backend`]. +/// +/// It has no windows and no monitors until a test adds them. The window manager reaches it through +/// [`crate::backend::backend`], installed with [`crate::backend::with_backend`]. +#[derive(Default)] +pub struct FakeBackend { + state: Mutex, +} + +impl FakeBackend { + /// Returns a fake with no monitors and no windows. + pub fn new() -> Self { + Self::default() + } + + /// Returns a fake that never refuses: a command about a window nobody opened creates it. + /// + /// The crate's own unit tests get one by default, so that a test of pure window manager logic, + /// which moves and focuses windows it never opened, needs no set-up. + pub fn permissive() -> Self { + let fake = Self::with_one_monitor(); + fake.state.lock().permissive = true; + fake + } + + /// Returns a fake with one 1920x1080 monitor, named `Virtual-0`, whose work area leaves 30 + /// pixels at the bottom for a panel. + pub fn with_one_monitor() -> Self { + let fake = Self::new(); + fake.add_monitor( + 1, + "Virtual-0", + Rect { + left: 0, + top: 0, + right: 1920, + bottom: 1080, + }, + Rect { + left: 0, + top: 0, + right: 1920, + bottom: 1050, + }, + ); + fake + } + + /// Adds a monitor. Its serial number identity is its name. + pub fn add_monitor(&self, id: u32, name: &str, size: Rect, work_area: Rect) { + self.state.lock().monitors.push(MonitorInfo { + id, + name: name.to_string(), + serial_number_id: name.to_string(), + size, + work_area, + }); + } + + /// Opens a window of an application. It starts at 800x600 at (100, 100), a normal window with + /// no focus. + pub fn open_window(&self, id: u32, exe: &str, class: &str, title: &str) { + self.state.lock().windows.insert( + id, + WindowInfo { + id, + pid: i32::try_from(id).unwrap_or_default() + 1000, + title: title.to_string(), + class: class.to_string(), + exe: exe.to_string(), + path: format!("/usr/bin/{exe}"), + rect: Rect { + left: 100, + top: 100, + right: 800, + bottom: 600, + }, + minimized: false, + normal: true, + alive: true, + }, + ); + } + + /// Destroys a window, as the user closing it does: the window manager is not asked. If it had + /// the focus, nothing has it now. + pub fn close_window_now(&self, id: u32) { + let mut state = self.state.lock(); + if let Some(window) = state.windows.get_mut(&id) { + window.alive = false; + } + if state.foreground == Some(id) { + state.foreground = None; + } + } + + /// Marks a window as a dialog, a splash screen, a utility window or the like, or as a normal + /// one again. + pub fn set_normal(&self, id: u32, normal: bool) { + if let Some(w) = self.state.lock().windows.get_mut(&id) { + w.normal = normal; + } + } + + /// Puts a window somewhere without the window manager having asked, as a user dragging it + /// does. + pub fn move_window_by_user(&self, id: u32, rect: Rect) { + if let Some(w) = self.state.lock().windows.get_mut(&id) { + w.rect = rect; + } + } + + /// Gives a window a minimum size. A [`Backend::set_rect`] for something smaller leaves it at + /// the minimum, which is how a GTK4 client answers. + pub fn set_min_size(&self, id: u32, width: i32, height: i32) { + self.state.lock().min_sizes.insert(id, (width, height)); + } + + /// Changes a window's title. + pub fn set_title(&self, id: u32, title: &str) { + if let Some(w) = self.state.lock().windows.get_mut(&id) { + w.title = title.to_string(); + } + } + + /// Changes which window has the focus, as the user does, without the window manager asking. + pub fn set_foreground(&self, id: Option) { + self.state.lock().foreground = id; + } + + /// Puts the pointer somewhere. + pub fn set_cursor(&self, x: i32, y: i32) { + self.state.lock().cursor = Some((x, y)); + } + + /// Returns where a window is, if it was ever opened. + pub fn rect_of(&self, id: u32) -> Option { + self.state.lock().windows.get(&id).map(|w| w.rect) + } + + /// Returns every command received so far, oldest first. + pub fn commands(&self) -> Vec { + self.state.lock().commands.clone() + } + + /// Forgets the commands received so far. + pub fn clear_commands(&self) { + self.state.lock().commands.clear(); + } + + fn record( + &self, + id: u32, + command: Command, + f: impl FnOnce(&mut State) -> T, + ) -> eyre::Result { + let mut state = self.state.lock(); + state.commands.push(command); + if state.permissive && !state.windows.contains_key(&id) { + state.windows.insert(id, permissive_window(id)); + } + match state.windows.get(&id) { + Some(w) if w.alive => Ok(f(&mut state)), + _ => eyre::bail!("no such window: {id}"), + } + } +} + +fn permissive_window(id: u32) -> WindowInfo { + WindowInfo { + id, + pid: i32::try_from(id).unwrap_or_default() + 1000, + title: format!("window {id}"), + class: format!("class.{id}"), + exe: format!("exe{id}"), + path: format!("/usr/bin/exe{id}"), + rect: Rect::default(), + minimized: false, + normal: true, + alive: true, + } +} + +impl Backend for FakeBackend { + fn windows(&self) -> Vec { + let state = self.state.lock(); + let mut windows: Vec<_> = state + .windows + .values() + .filter(|w| w.alive) + .cloned() + .collect(); + windows.sort_by_key(|w| w.id); + windows + } + + fn window(&self, id: u32) -> Option { + let mut state = self.state.lock(); + if state.permissive && !state.windows.contains_key(&id) { + state.windows.insert(id, permissive_window(id)); + } + state.windows.get(&id).cloned() + } + + fn foreground_window(&self) -> Option { + self.state.lock().foreground + } + + fn monitors(&self) -> eyre::Result> { + Ok(self.state.lock().monitors.clone()) + } + + fn cursor_pos(&self) -> Option<(i32, i32)> { + self.state.lock().cursor + } + + fn set_rect(&self, id: u32, rect: &Rect) -> eyre::Result<()> { + let rect = *rect; + self.record(id, Command::SetRect(id, rect), |state| { + let (min_w, min_h) = state.min_sizes.get(&id).copied().unwrap_or((0, 0)); + if let Some(w) = state.windows.get_mut(&id) { + w.rect = Rect { + left: rect.left, + top: rect.top, + right: rect.right.max(min_w), + bottom: rect.bottom.max(min_h), + }; + } + }) + } + + fn focus(&self, id: u32, mouse_follows_focus: bool) -> eyre::Result<()> { + self.record(id, Command::Focus(id, mouse_follows_focus), |state| { + state.foreground = Some(id); + if mouse_follows_focus && let Some(w) = state.windows.get(&id) { + state.cursor = Some(( + w.rect.left + w.rect.right / 2, + w.rect.top + w.rect.bottom / 2, + )); + } + }) + } + + fn raise(&self, id: u32) -> eyre::Result<()> { + self.record(id, Command::Raise(id), |_| ()) + } + + fn minimize(&self, id: u32) -> eyre::Result<()> { + self.record(id, Command::Minimize(id), |state| { + if let Some(w) = state.windows.get_mut(&id) { + w.minimized = true; + } + }) + } + + fn unminimize(&self, id: u32) -> eyre::Result<()> { + self.record(id, Command::Unminimize(id), |state| { + if let Some(w) = state.windows.get_mut(&id) { + w.minimized = false; + } + }) + } + + fn close(&self, id: u32) -> eyre::Result<()> { + self.record(id, Command::Close(id), |state| { + if let Some(w) = state.windows.get_mut(&id) { + w.alive = false; + } + }) + } + + fn center_cursor_in(&self, rect: &Rect) -> eyre::Result<()> { + let mut state = self.state.lock(); + state.commands.push(Command::CenterCursor(*rect)); + state.cursor = Some((rect.left + rect.right / 2, rect.top + rect.bottom / 2)); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tile(left: i32, width: i32) -> Rect { + Rect { + left, + top: 0, + right: width, + bottom: 1050, + } + } + + fn fake_with(ids: &[u32]) -> FakeBackend { + let fake = FakeBackend::with_one_monitor(); + for id in ids { + fake.open_window(*id, "foot", "foot", &format!("window {id}")); + } + fake + } + + #[test] + fn a_window_asked_to_move_is_where_it_was_asked() -> eyre::Result<()> { + let fake = fake_with(&[1]); + + fake.set_rect(1, &tile(10, 500))?; + + assert_eq!(fake.rect_of(1), Some(tile(10, 500))); + Ok(()) + } + + #[test] + fn a_window_keeps_to_its_minimum_size() -> eyre::Result<()> { + let fake = fake_with(&[1]); + fake.set_min_size(1, 600, 400); + + fake.set_rect(1, &tile(0, 300))?; + + let rect = fake.rect_of(1).expect("window 1 was opened"); + assert_eq!((rect.right, rect.bottom), (600, 1050)); + Ok(()) + } + + #[test] + fn every_command_is_recorded_in_order() -> eyre::Result<()> { + let fake = fake_with(&[1, 2]); + + fake.focus(1, false)?; + fake.raise(2)?; + fake.minimize(1)?; + fake.unminimize(1)?; + fake.close(2)?; + + assert_eq!( + fake.commands(), + [ + Command::Focus(1, false), + Command::Raise(2), + Command::Minimize(1), + Command::Unminimize(1), + Command::Close(2), + ] + ); + fake.clear_commands(); + assert!(fake.commands().is_empty()); + Ok(()) + } + + #[test] + fn a_command_about_a_window_nobody_opened_is_an_error() { + let fake = fake_with(&[1]); + + let error = fake.focus(9, false).expect_err("window 9 does not exist"); + + assert_eq!(error.to_string(), "no such window: 9"); + } + + #[test] + fn a_command_about_a_closed_window_is_an_error() { + let fake = fake_with(&[1]); + fake.close_window_now(1); + + assert!(fake.raise(1).is_err()); + } + + #[test] + fn a_permissive_fake_creates_the_windows_it_is_asked_about() -> eyre::Result<()> { + let fake = FakeBackend::permissive(); + + fake.focus(77, false)?; + + assert!(fake.is_window(77)); + assert_eq!(fake.foreground_window(), Some(77)); + Ok(()) + } + + #[test] + fn focusing_with_the_mouse_following_puts_the_pointer_in_the_middle_of_the_window() + -> eyre::Result<()> { + let fake = fake_with(&[1]); + fake.set_rect(1, &tile(100, 200))?; + + fake.focus(1, true)?; + + assert_eq!(fake.cursor_pos(), Some((200, 525))); + Ok(()) + } + + #[test] + fn focusing_without_the_mouse_following_leaves_the_pointer_alone() -> eyre::Result<()> { + let fake = fake_with(&[1]); + fake.set_cursor(5, 5); + + fake.focus(1, false)?; + + assert_eq!(fake.cursor_pos(), Some((5, 5))); + Ok(()) + } + + #[test] + fn closing_the_window_with_the_focus_leaves_nothing_focused() { + let fake = fake_with(&[1]); + fake.set_foreground(Some(1)); + + fake.close_window_now(1); + + assert_eq!(fake.foreground_window(), None); + } + + #[test] + fn what_the_user_does_is_not_a_command() { + let fake = fake_with(&[1]); + + fake.move_window_by_user(1, tile(300, 300)); + fake.set_title(1, "renamed"); + fake.set_normal(1, false); + + assert!(fake.commands().is_empty()); + assert_eq!(fake.rect_of(1), Some(tile(300, 300))); + let window = fake.window(1).expect("window 1 was opened"); + assert_eq!(window.title, "renamed"); + assert!(!window.normal); + } + + #[test] + fn windows_are_listed_by_id_and_a_destroyed_one_is_left_out() { + let fake = fake_with(&[3, 1, 2]); + fake.close_window_now(2); + + let ids: Vec<_> = fake.windows().iter().map(|w| w.id).collect(); + + assert_eq!(ids, [1, 3]); + } + + #[test] + fn the_cursor_can_be_centered_in_a_rectangle() -> eyre::Result<()> { + let fake = FakeBackend::new(); + + fake.center_cursor_in(&tile(0, 400))?; + + assert_eq!(fake.cursor_pos(), Some((200, 525))); + assert_eq!(fake.commands(), [Command::CenterCursor(tile(0, 400))]); + Ok(()) + } +} diff --git a/komorebi/src/backend/mod.rs b/komorebi/src/backend/mod.rs new file mode 100644 index 00000000..15de867f --- /dev/null +++ b/komorebi/src/backend/mod.rs @@ -0,0 +1,380 @@ +//! Everything the window manager needs from the desktop, behind one trait. +//! +//! The window manager logic (windows, containers, workspaces, monitors) never talks to KWin, to +//! `/proc` or to D-Bus. It talks to a [`Backend`]. A real backend asks the compositor; the one the +//! tests use is [`fake::FakeBackend`], an in-memory desktop that does what it is told and records +//! what it was asked. +//! +//! # The backend is process-wide +//! +//! The backend is a singleton, like the other globals of this crate, so that a window can be a +//! small `Copy` handle that carries only its id: `window.set_position(..)` needs no context passed +//! to it. [`set_backend`] installs it once at startup, and [`backend`] returns it. A test that needs +//! a private desktop uses [`with_backend`], which overrides the backend for the current thread +//! only and puts the previous one back afterwards, so tests cannot leak a desktop into each other. +//! +//! # Queries and commands +//! +//! Queries are answered from the backend's own table, which compositor events keep up to date, so +//! they never wait for the compositor. A window that has just been closed stays queryable for a +//! short time, with [`WindowInfo::alive`] false, so that the event that mentions it can still be +//! logged. Commands return once the compositor has accepted them, not once the client has acted on +//! them, and an implementation may batch them. + +#![deny(missing_docs)] + +use crate::core::Rect; +use color_eyre::eyre; +use parking_lot::RwLock; +use std::cell::RefCell; +use std::sync::Arc; + +pub mod fake; + +/// What the compositor currently knows about one window. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct WindowInfo { + /// The compositor's id for the window, which is how every other part of komorebi names it. + pub id: u32, + /// The id of the process that owns the window. + pub pid: i32, + /// The window's title. + pub title: String, + /// The Wayland `app_id` (the X11 `WM_CLASS` for a client that runs on XWayland). + pub class: String, + /// The file name of the executable, read from `/proc//exe`. + pub exe: String, + /// The full path of the executable. + pub path: String, + /// The window's frame. + pub rect: Rect, + /// Whether the window is minimized. + pub minimized: bool, + /// Whether the compositor considers this a normal application window, as opposed to a dialog, + /// a splash screen, a utility window, a dock and so on. + pub normal: bool, + /// False once the window has been destroyed. + pub alive: bool, +} + +/// A connected monitor, in logical pixels. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MonitorInfo { + /// The compositor's id for the monitor. + pub id: u32, + /// The name of the output (`DP-1`, `Virtual-0`). + pub name: String, + /// An identity for the monitor that stays the same across a hot-plug and a restart. + pub serial_number_id: String, + /// The monitor's bounds. + pub size: Rect, + /// `size` minus the panels and other areas the compositor reserves. + pub work_area: Rect, +} + +/// The desktop, as the window manager sees it. +/// +/// This is the **only** way the window manager reaches the compositor. Everything else in the crate +/// is testable without one. +/// +/// # Who implements it, who calls it +/// +/// A backend is implemented once per compositor, and by the in-memory [`fake::FakeBackend`]. It is +/// called by the window manager, through [`backend`]; nothing else should hold a reference to it. +/// +/// # Contract +/// +/// - Queries never block on the compositor and never fail, except [`Backend::monitors`], which may +/// fail when the compositor cannot say. +/// - A command about a window that does not exist, or is no longer alive, returns an error. It does +/// not panic. +/// - A backend is `Send + Sync`: the window manager calls it from several threads. +/// +/// The compiler enforces the first and last parts of the contract that it can see. A backend that +/// leaves out a method does not compile: +/// +/// ```rust,compile_fail,E0046 +/// use komorebi::backend::Backend; +/// +/// struct Nothing; +/// +/// impl Backend for Nothing {} +/// ``` +/// +/// And neither does one that cannot be shared between threads: +/// +/// ```rust,compile_fail,E0277 +/// # use std::rc::Rc; +/// # use color_eyre::eyre; +/// # use komorebi::backend::{Backend, MonitorInfo, WindowInfo}; +/// # use komorebi::core::Rect; +/// struct NotShareable(Rc); +/// +/// # impl Backend for NotShareable { +/// # fn windows(&self) -> Vec { vec![] } +/// # fn window(&self, _: u32) -> Option { None } +/// # fn foreground_window(&self) -> Option { None } +/// # fn monitors(&self) -> eyre::Result> { Ok(vec![]) } +/// # fn cursor_pos(&self) -> Option<(i32, i32)> { None } +/// # fn set_rect(&self, _: u32, _: &Rect) -> eyre::Result<()> { Ok(()) } +/// # fn focus(&self, _: u32, _: bool) -> eyre::Result<()> { Ok(()) } +/// # fn raise(&self, _: u32) -> eyre::Result<()> { Ok(()) } +/// # fn minimize(&self, _: u32) -> eyre::Result<()> { Ok(()) } +/// # fn unminimize(&self, _: u32) -> eyre::Result<()> { Ok(()) } +/// # fn close(&self, _: u32) -> eyre::Result<()> { Ok(()) } +/// # fn center_cursor_in(&self, _: &Rect) -> eyre::Result<()> { Ok(()) } +/// # } +/// ``` +pub trait Backend: Send + Sync + 'static { + // ---- queries ------------------------------------------------------------------------------- + + /// Returns every window on the desktop that is a candidate for management, ordered by id. + fn windows(&self) -> Vec; + + /// Returns what is known about the window, or `None` if the compositor has never heard of it. + fn window(&self, id: u32) -> Option; + + /// Returns the id of the window that has the focus, if any window does. + fn foreground_window(&self) -> Option; + + /// Returns every connected monitor. + /// + /// # Errors + /// + /// When the compositor cannot report its outputs. + fn monitors(&self) -> eyre::Result>; + + /// Returns where the pointer is, if the compositor says. + fn cursor_pos(&self) -> Option<(i32, i32)>; + + // ---- commands ------------------------------------------------------------------------------ + + /// Moves and resizes the window to `rect`, a position and a size. + /// + /// A client may refuse the size (a minimum size, for one), so the frame the window ends up with + /// is [`Backend::window_rect`], not `rect`. + /// + /// # Errors + /// + /// When the window does not exist or is no longer alive. + fn set_rect(&self, id: u32, rect: &Rect) -> eyre::Result<()>; + + /// Gives the window the focus, and, if `mouse_follows_focus`, puts the pointer in its middle. + /// + /// # Errors + /// + /// When the window does not exist or is no longer alive. + fn focus(&self, id: u32, mouse_follows_focus: bool) -> eyre::Result<()>; + + /// Raises the window above the others. + /// + /// # Errors + /// + /// When the window does not exist or is no longer alive. + fn raise(&self, id: u32) -> eyre::Result<()>; + + /// Minimizes the window. + /// + /// # Errors + /// + /// When the window does not exist or is no longer alive. + fn minimize(&self, id: u32) -> eyre::Result<()>; + + /// Brings a minimized window back. + /// + /// # Errors + /// + /// When the window does not exist or is no longer alive. + fn unminimize(&self, id: u32) -> eyre::Result<()>; + + /// Asks the window to close. + /// + /// # Errors + /// + /// When the window does not exist or is no longer alive. + fn close(&self, id: u32) -> eyre::Result<()>; + + /// Puts the pointer in the middle of `rect`. + /// + /// # Errors + /// + /// When the compositor refuses to move the pointer. + fn center_cursor_in(&self, rect: &Rect) -> eyre::Result<()>; + + // ---- provided ------------------------------------------------------------------------------ + + /// Called once as komorebi exits, after the window manager has put back what it moved, so that + /// the backend can give up whatever it created itself. + /// + /// The default does nothing. Implementors should not need to override it unless they created + /// something in the compositor. + fn shutdown(&self) {} + + /// Returns true if and only if the compositor has a live window with this id. + fn is_window(&self, id: u32) -> bool { + self.window(id).is_some_and(|w| w.alive) + } + + /// Returns the window's frame, if the compositor knows the window. + fn window_rect(&self, id: u32) -> Option { + self.window(id).map(|w| w.rect) + } + + /// Returns the id of the monitor whose bounds contain the point. + fn monitor_from_point(&self, x: i32, y: i32) -> Option { + self.monitors().ok()?.into_iter().find_map(|m| { + let (l, t) = (m.size.left, m.size.top); + let (r, b) = (l + m.size.right, t + m.size.bottom); + (x >= l && x < r && y >= t && y < b).then_some(m.id) + }) + } +} + +static BACKEND: RwLock>> = RwLock::new(None); + +thread_local! { + static OVERRIDE: RefCell>> = const { RefCell::new(None) }; +} + +/// Installs the process-wide backend. Called once at startup. +pub fn set_backend(backend: Arc) { + *BACKEND.write() = Some(backend); +} + +/// Returns the backend for this thread: the thread's override if there is one, else the +/// process-wide one. +/// +/// # Panics +/// +/// If no backend has been installed. That is a bug in the order of start-up, not a condition at +/// run time. Install one with [`set_backend`], or with [`with_backend`] in a test. +pub fn backend() -> Arc { + OVERRIDE + .with(|o| o.borrow().clone()) + .or_else(|| BACKEND.read().clone()) + .or_else(test_default) + .expect( + "no backend installed: call backend::set_backend (or backend::with_backend in tests)", + ) +} + +/// The crate's own unit tests get a private, permissive fake per thread when they install nothing, +/// so that a test of pure window manager logic needs no set-up. Everything else gets no default. +#[cfg(test)] +fn test_default() -> Option> { + OVERRIDE.with(|o| { + let backend: Arc = Arc::new(fake::FakeBackend::permissive()); + *o.borrow_mut() = Some(backend.clone()); + Some(backend) + }) +} + +#[cfg(not(test))] +fn test_default() -> Option> { + None +} + +/// Runs `f` with `backend` as this thread's backend, and puts the previous override back +/// afterwards, also when `f` panics. +/// +/// # Example +/// +/// ```rust +/// use std::sync::Arc; +/// +/// use komorebi::backend::Backend; +/// use komorebi::backend::backend; +/// use komorebi::backend::fake::FakeBackend; +/// use komorebi::backend::with_backend; +/// +/// let fake = Arc::new(FakeBackend::with_one_monitor()); +/// fake.open_window(7, "foot", "foot", "a terminal"); +/// +/// let titles = with_backend(fake.clone(), || { +/// backend().windows().into_iter().map(|w| w.title).collect::>() +/// }); +/// +/// assert_eq!(titles, ["a terminal"]); +/// ``` +pub fn with_backend(backend: Arc, f: impl FnOnce() -> R) -> R { + struct Restore(Option>); + impl Drop for Restore { + fn drop(&mut self) { + OVERRIDE.with(|o| *o.borrow_mut() = self.0.take()); + } + } + + let _restore = Restore(OVERRIDE.with(|o| o.borrow_mut().replace(backend))); + f() +} + +#[cfg(test)] +mod tests { + use super::*; + use fake::FakeBackend; + + #[test] + fn a_thread_that_installs_nothing_gets_a_permissive_fake_in_unit_tests() { + let id = 41; + + assert!(backend().window(id).is_some()); + } + + #[test] + fn with_backend_overrides_the_backend_and_puts_the_previous_one_back() { + let outer = Arc::new(FakeBackend::with_one_monitor()); + outer.open_window(1, "outer", "outer", "outer"); + let inner = Arc::new(FakeBackend::with_one_monitor()); + inner.open_window(2, "inner", "inner", "inner"); + + with_backend(outer, || { + with_backend(inner, || { + assert!(backend().is_window(2)); + assert!(!backend().is_window(1)); + }); + + assert!(backend().is_window(1)); + assert!(!backend().is_window(2)); + }); + } + + #[test] + fn with_backend_puts_the_previous_backend_back_when_the_closure_panics() { + let outer = Arc::new(FakeBackend::with_one_monitor()); + outer.open_window(1, "outer", "outer", "outer"); + + with_backend(outer, || { + let inner = Arc::new(FakeBackend::with_one_monitor()); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + with_backend(inner, || panic!("a test")) + })); + + assert!(result.is_err()); + assert!(backend().is_window(1)); + }); + } + + #[test] + fn the_provided_methods_are_answered_from_the_queries() { + let fake = FakeBackend::with_one_monitor(); + fake.open_window(5, "foot", "foot", "a terminal"); + + assert!(fake.is_window(5)); + assert!(!fake.is_window(6)); + assert_eq!(fake.window_rect(5), fake.rect_of(5)); + assert_eq!(fake.monitor_from_point(10, 10), Some(1)); + assert_eq!(fake.monitor_from_point(5000, 10), None); + } + + #[test] + fn a_destroyed_window_is_no_longer_a_window_but_can_still_be_asked_about() { + let fake = FakeBackend::with_one_monitor(); + fake.open_window(5, "foot", "foot", "a terminal"); + + fake.close_window_now(5); + + assert!(!fake.is_window(5)); + assert!(fake.window(5).is_some_and(|w| !w.alive)); + assert!(fake.windows().is_empty()); + } +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index b42ba833..fc7953b2 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -4,5 +4,6 @@ #[macro_use] pub mod ring; +pub mod backend; pub mod core; pub mod lockable_sequence; From c0345eb0e9e7925b875f992c7c29314fe4360697 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 12:01:50 -0700 Subject: [PATCH 009/255] feat(wm): windows, containers, workspaces and monitors The window manager tiles a tree of four levels: monitors, each with a ring of workspaces, each with a ring of containers, each with a ring of windows. It is the model komorebi has on Windows and macOS, and the first thing the daemon keeps that the backend does not give it. A window is a Copy handle that carries the compositor's id and asks the backend for everything else, so moving one is a call on the handle and needs no context passed to it. A workspace tiles itself: the layout gives each container a tile of the work area its monitor hands it, less the offset and the padding, and every window of the container is asked to move there. A locked container keeps its index because the workspace inserts, removes and swaps its containers through LockableSequence. This is tiling only. Stacks, monocle, maximize, the floating layer, resize adjustments, placement rules and the link between workspaces and KWin's desktops come with the commits that use them. impl_ring_elements!, which gives every holder of a ring the same accessors, lands here with its first users. --- Cargo.lock | 96 +++- Cargo.toml | 1 + README.md | 8 +- docs/dev/ARCHITECTURE.md | 59 ++- docs/dev/DESIGN.md | 4 +- komorebi/Cargo.toml | 3 + komorebi/src/container.rs | 218 +++++++++ komorebi/src/lib.rs | 18 + komorebi/src/monitor.rs | 416 +++++++++++++++++ komorebi/src/ring.rs | 67 ++- komorebi/src/window.rs | 304 ++++++++++++ komorebi/src/workspace.rs | 948 ++++++++++++++++++++++++++++++++++++++ 12 files changed, 2135 insertions(+), 7 deletions(-) create mode 100644 komorebi/src/container.rs create mode 100644 komorebi/src/monitor.rs create mode 100644 komorebi/src/window.rs create mode 100644 komorebi/src/workspace.rs diff --git a/Cargo.lock b/Cargo.lock index 5e1629d0..3eaaca44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -418,6 +418,17 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -713,7 +724,7 @@ version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" dependencies = [ - "getrandom", + "getrandom 0.4.3", "libc", ] @@ -735,12 +746,15 @@ dependencies = [ "clap", "color-eyre", "komorebi-layouts", + "nanoid", "parking_lot", + "pastey", "schemars 1.2.3", "serde", "serde_json_lenient", "serde_with", "strum", + "tracing", "version", ] @@ -852,6 +866,15 @@ dependencies = [ "adler2", ] +[[package]] +name = "nanoid" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8" +dependencies = [ + "rand", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -926,6 +949,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -974,6 +1003,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -998,6 +1036,36 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1546,6 +1614,12 @@ dependencies = [ "shadow-rs", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -1688,6 +1762,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" diff --git a/Cargo.toml b/Cargo.toml index cfbbd0c5..9421cf18 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ komorebi-layouts = { git = "https://github.com/LGUG2Z/komorebi", rev = "f08aa555 clap = { version = "4", features = ["derive", "wrap_help"] } color-eyre = "0.6" +pastey = "0.2" schemars = "1.1" serde = { version = "1", features = ["derive"] } serde_json = { package = "serde_json_lenient", version = "0.2" } diff --git a/README.md b/README.md index 4439ddc5..73bf0fff 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,8 @@ 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 `Ring` that holds monitors, workspaces and containers, and the + (`backend`), the model of what it tiles (`monitor`, `workspace`, `container`, + `window`), 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. @@ -54,6 +55,11 @@ 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. +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 +area, and every window of a container is moved onto its tile. + ## Documentation `cargo doc --workspace --no-deps --open` builds the API documentation. diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 90ba1c37..4cc7e90e 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -5,9 +5,9 @@ compositor to put it there. Everything it needs from the compositor is behind on [`Backend`](../../komorebi/src/backend/mod.rs), so the window manager is written, and tested, without one. -This page describes that trait, who implements and calls it, and where each of its rules -is enforced. It grows with the code: each part of the daemon that is added has its place -here. +This page describes that trait, who implements and calls it, where each of its rules is +enforced, and the model of the desktop the window manager tiles. It grows with the code: +each part of the daemon that is added has its place here. ## Vocabulary @@ -15,6 +15,12 @@ here. compositor's `u32` id. - **Monitor**: a connected output, with its bounds and its work area (its bounds minus the panels). +- **Workspace**: the containers a monitor shows, in order, and the layout that tiles + them. A monitor has a ring of workspaces and shows one of them. +- **Container**: what a layout places. It gets one tile, and every window in it is put on + that tile. +- **Layout**: the arrangement (BSP, columns, rows, ...) that turns a work area and a + number of containers into one rectangle, a **tile**, for each container. - **Compositor**: the program that owns the screen and the windows. On KDE Plasma it is KWin. - **Backend**: the implementation of the [`Backend`](../../komorebi/src/backend/mod.rs) @@ -48,11 +54,39 @@ The desktop, as the window manager sees it, is two lists and a pointer: A command is one of: move and resize a window, focus it, raise it, minimize it or bring it back, close it, and put the pointer in the middle of a rectangle. +The window manager tiles a tree of four levels, each level a [`Ring`]: a list with one +element focused, so that "the focused workspace" or "the focused container" means +the same thing at every level. + +- A **monitor** ([`Monitor`]) is one of the backend's monitors: its bounds, its work area, + its padding, an optional work area offset, and its workspaces. It shows the focused one. +- A **workspace** ([`Workspace`]) has a layout, its padding, and its containers, in order. +- A **container** ([`Container`]) has its windows. A new window gets a container of its + own. A container can be locked, which keeps it at its index while others are inserted, + removed or swapped around it. +- A **window** ([`Window`]) is a `Copy` handle that carries only the compositor's id. + Everything else about the window, and every change to it, goes through the backend. + +Tiling a workspace ([`Workspace::update`]) is a function of this tree and a work area. The +monitor gives its focused workspace the work area, the padding to fall back to and the +offset ([`WorkspaceGlobals`]). The workspace takes the offset and its padding off the work +area, the layout gives one tile per container, in order, each shrunk by the container +padding, and every window of a container is asked to move onto its tile with `set_rect`. A +tile is clamped to the work area, so it cannot reach onto a neighboring monitor. + ## The parts - [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the process-wide handle ([`set_backend`], [`backend`], [`with_backend`]). - [`backend::fake`](../../komorebi/src/backend/fake.rs): the fake. +- [`ring`](../../komorebi/src/ring.rs): the [`Ring`], and the macro that gives every type + holding one the same accessors (`containers()`, `focused_container_mut()`, ...). +- [`monitor`](../../komorebi/src/monitor.rs), [`workspace`](../../komorebi/src/workspace.rs), + [`container`](../../komorebi/src/container.rs), [`window`](../../komorebi/src/window.rs): + the four levels of the tree. +- [`lockable_sequence`](../../komorebi/src/lockable_sequence.rs): inserting, removing and + swapping in a list where some elements are locked in place, which is how a workspace + changes its containers. 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 @@ -84,6 +118,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | The window manager asks for a backend that was never installed | runtime error: [`backend`] panics, naming [`set_backend`] and [`with_backend`] | `# Panics` on [`backend`] | none | | A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none | | A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error`, against the fake only | none | +| 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 | | Queries never block on the compositor | convention only | none | none | | Only the backend module reaches the compositor | convention only | none | none | @@ -97,3 +132,21 @@ breaks the first, and a module that talks to D-Bus directly breaks the second. tests. - [`komorebi/src/core`](../../komorebi/src/core/mod.rs): the vocabulary the rest is written in. +- [`komorebi/src/workspace.rs`](../../komorebi/src/workspace.rs): tiling, in + `Workspace::update`. +- [`komorebi/src/monitor.rs`](../../komorebi/src/monitor.rs): the work area, padding and + offset a monitor gives the workspace it shows. + +[`Backend`]: ../../komorebi/src/backend/mod.rs +[`WindowInfo`]: ../../komorebi/src/backend/mod.rs +[`MonitorInfo`]: ../../komorebi/src/backend/mod.rs +[`set_backend`]: ../../komorebi/src/backend/mod.rs +[`backend`]: ../../komorebi/src/backend/mod.rs +[`with_backend`]: ../../komorebi/src/backend/mod.rs +[`Ring`]: ../../komorebi/src/ring.rs +[`Monitor`]: ../../komorebi/src/monitor.rs +[`Workspace`]: ../../komorebi/src/workspace.rs +[`Workspace::update`]: ../../komorebi/src/workspace.rs +[`WorkspaceGlobals`]: ../../komorebi/src/workspace.rs +[`Container`]: ../../komorebi/src/container.rs +[`Window`]: ../../komorebi/src/window.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index c51507cf..d81199e7 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -12,7 +12,9 @@ komorebi has a Windows implementation, the original, and a macOS one. The Window the reference. I used it as the reference for what to adapt, and I prefer what KDE and Wayland do natively over a workaround that the other two platforms need. The events the window manager reacts to follow the Windows ones (a window is shown, destroyed, focused, -minimized, moved, resized), and a window is a small `Copy` handle, as there. +minimized, moved, resized), and a window is a small `Copy` handle, as there. The model the +window manager tiles is the one both platforms have: monitors, each with workspaces, each +with containers, each with windows. ## Why is everything the window manager needs behind one trait? diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index bc455c9c..5f4d2939 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -10,11 +10,14 @@ version = { path = "../version" } clap = { workspace = true } color-eyre = { workspace = true } +nanoid = "0.4" parking_lot = "0.12" +pastey = { workspace = true } schemars = { workspace = true, optional = true } serde = { workspace = true } serde_with = { version = "3", features = ["schemars_1"] } strum = { version = "0.28", features = ["derive"] } +tracing = { workspace = true } [dev-dependencies] serde_json = { workspace = true } diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs new file mode 100644 index 00000000..f7bf047f --- /dev/null +++ b/komorebi/src/container.rs @@ -0,0 +1,218 @@ +//! [`Container`], the windows that share one tile of a workspace's layout. +//! +//! A container is a ring of windows. The layout gives each container a tile, and every window of +//! the container is put on that tile. A new window gets a container of its own +//! ([`Workspace::new_container_for_window`](crate::workspace::Workspace::new_container_for_window)). +//! +//! A container can be locked ([`Lockable`]): a locked container keeps its index in the workspace +//! while others are inserted, removed or swapped around it. + +use crate::lockable_sequence::Lockable; +use crate::ring::Ring; +use crate::window::Window; +use color_eyre::eyre; +use nanoid::nanoid; +use serde::Deserialize; +use serde::Serialize; + +impl_ring_elements!(Container, Window); + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct Container { + pub id: String, + pub locked: bool, + pub windows: Ring, +} + +impl Default for Container { + fn default() -> Self { + Self { + id: nanoid!(), + locked: false, + windows: Default::default(), + } + } +} + +impl Lockable for Container { + fn locked(&self) -> bool { + self.locked + } + + fn set_locked(&mut self, locked: bool) -> &mut Self { + self.locked = locked; + self + } +} + +impl Container { + pub fn contains_window(&self, window_id: u32) -> bool { + for window in self.windows() { + if window.id == window_id { + return true; + } + } + + false + } + + pub fn idx_for_window(&self, window_id: u32) -> Option { + for (i, window) in self.windows().iter().enumerate() { + if window.id == window_id { + return Option::from(i); + } + } + + None + } + + pub fn remove_focused_window(&mut self) -> Option { + let focused_idx = self.focused_window_idx(); + self.remove_window_by_idx(focused_idx) + } + + pub fn add_window(&mut self, window: &Window) -> eyre::Result<()> { + self.windows_mut().push_back(*window); + self.focus_window(self.windows().len().saturating_sub(1)); + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn focus_window(&mut self, idx: usize) { + tracing::info!("focusing window"); + self.windows.focus(idx); + } + + pub fn remove_window_by_idx(&mut self, idx: usize) -> Option { + let window = self.windows_mut().remove(idx); + self.focus_window(idx.saturating_sub(1)); + window + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json; + + #[test] + fn test_contains_window() { + let mut container = Container::default(); + + for i in 0..3 { + container.add_window(&Window::from(i)).unwrap(); + } + + // Should return true for existing windows + assert!(container.contains_window(1)); + assert_eq!(container.idx_for_window(1), Some(1)); + + // Should return false since window 4 doesn't exist + assert!(!container.contains_window(4)); + assert_eq!(container.idx_for_window(4), None); + } + + #[test] + fn test_remove_window_by_idx() { + let mut container = Container::default(); + + for i in 0..3 { + container.add_window(&Window::from(i)).unwrap(); + } + + // Remove window 1 + container.remove_window_by_idx(1); + + // Should only have 2 windows left + assert_eq!(container.windows().len(), 2); + + // Should return false since window 1 was removed + assert!(!container.contains_window(1)); + } + + #[test] + fn test_remove_focused_window() { + let mut container = Container::default(); + + for i in 0..3 { + container.add_window(&Window::from(i)).unwrap(); + } + + // Should be focused on the last created window + assert_eq!(container.focused_window_idx(), 2); + + // Remove the focused window + container.remove_focused_window(); + + // Should be focused on the window before the removed one + assert_eq!(container.focused_window_idx(), 1); + + // Should only have 2 windows left + assert_eq!(container.windows().len(), 2); + } + + #[test] + fn test_add_window() { + let mut container = Container::default(); + + container.add_window(&Window::from(1)).unwrap(); + + assert_eq!(container.windows().len(), 1); + assert_eq!(container.focused_window_idx(), 0); + assert!(container.contains_window(1)); + } + + #[test] + fn test_focus_window() { + let mut container = Container::default(); + + for i in 0..3 { + container.add_window(&Window::from(i)).unwrap(); + } + + // Should focus on the last created window + assert_eq!(container.focused_window_idx(), 2); + + // focus on the window at index 1 + container.focus_window(1); + + // Should be focused on window 1 + assert_eq!(container.focused_window_idx(), 1); + + // focus on the window at index 0 + container.focus_window(0); + + // Should be focused on window 0 + assert_eq!(container.focused_window_idx(), 0); + } + + #[test] + fn test_idx_for_window() { + let mut container = Container::default(); + + for i in 0..3 { + container.add_window(&Window::from(i)).unwrap(); + } + + // Should return the index of the window + assert_eq!(container.idx_for_window(1), Some(1)); + + // Should return None since window 4 doesn't exist + assert_eq!(container.idx_for_window(4), None); + } + + #[test] + fn serializes_and_deserializes() { + let mut container = Container::default(); + container.set_locked(true); + + let serialized = serde_json::to_string(&container).expect("Should serialize"); + let deserialized: Container = + serde_json::from_str(&serialized).expect("Should deserialize"); + + assert!(deserialized.locked); + assert_eq!(deserialized.id, container.id); + } +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index fc7953b2..c8bf620f 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -1,9 +1,27 @@ //! The komorebi daemon's library: the vocabulary the window manager is written in and the data //! structures it is built from. +//! +//! The desktop is modeled as monitors ([`monitor::Monitor`]), each with a ring of workspaces +//! ([`workspace::Workspace`]), each with a ring of containers ([`container::Container`]), each with +//! a ring of windows ([`window::Window`]). A workspace tiles its containers by its layout, and a +//! window is moved by asking the [`backend`]. + +use std::sync::atomic::AtomicI32; #[macro_use] pub mod ring; pub mod backend; +pub mod container; pub mod core; pub mod lockable_sequence; +pub mod monitor; +pub mod window; +pub mod workspace; + +/// 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); +/// The padding, in pixels, around each tile, for a monitor that sets none of its own. The default +/// for this is 5. +pub static DEFAULT_CONTAINER_PADDING: AtomicI32 = AtomicI32::new(5); diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs new file mode 100644 index 00000000..e672748a --- /dev/null +++ b/komorebi/src/monitor.rs @@ -0,0 +1,416 @@ +//! [`Monitor`], a connected output and the ring of workspaces it can show. +//! +//! A monitor has the bounds and the work area the backend reports for it +//! ([`MonitorInfo`](crate::backend::MonitorInfo)), and shows one of its workspaces, the focused +//! one. Before the focused workspace is tiled it is given the monitor's work area, the monitor's +//! padding (or [`DEFAULT_CONTAINER_PADDING`] and [`DEFAULT_WORKSPACE_PADDING`]) and the work area +//! offset ([`WorkspaceGlobals`]). + +use crate::DEFAULT_CONTAINER_PADDING; +use crate::DEFAULT_WORKSPACE_PADDING; +use crate::container::Container; +use crate::core::Rect; +use crate::ring::Ring; +use crate::workspace::Workspace; +use crate::workspace::WorkspaceGlobals; +use color_eyre::eyre; +use color_eyre::eyre::OptionExt; +use serde::Deserialize; +use serde::Serialize; +use std::collections::VecDeque; +use std::sync::atomic::Ordering; + +impl_ring_elements!(Monitor, Workspace); + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct Monitor { + pub id: u32, + pub device: String, + pub serial_number_id: String, + pub workspaces: Ring, + pub size: Rect, + pub work_area_offset: Option, + pub work_area_size: Rect, + pub container_padding: Option, + pub workspace_padding: Option, +} + +impl Monitor { + #[allow(clippy::field_reassign_with_default)] + pub fn new( + id: u32, + size: Rect, + work_area_size: Rect, + device: &str, + serial_number_id: &str, + ) -> Self { + let mut workspaces = Ring::default(); + workspaces.elements_mut().push_back(Workspace::default()); + + Self { + id, + device: device.to_string(), + serial_number_id: serial_number_id.to_string(), + workspaces, + size, + work_area_offset: None, + work_area_size, + container_padding: None, + workspace_padding: None, + } + } + + /// Tiles the focused workspace in this monitor's work area, less `offset` if the monitor has + /// no offset of its own + #[tracing::instrument(skip_all)] + pub fn update_focused_workspace(&mut self, offset: Option) -> eyre::Result<()> { + let offset = if self.work_area_offset.is_some() { + self.work_area_offset + } else { + offset + }; + + let focused_workspace_idx = self.focused_workspace_idx(); + self.update_workspace_globals(focused_workspace_idx, offset); + self.focused_workspace_mut() + .ok_or_eyre("there is no workspace")? + .update()?; + + Ok(()) + } + + /// Updates the `globals` field of workspace with index `workspace_idx` + pub fn update_workspace_globals(&mut self, workspace_idx: usize, offset: Option) { + let container_padding = self + .container_padding + .or(Some(DEFAULT_CONTAINER_PADDING.load(Ordering::Relaxed))); + let workspace_padding = self + .workspace_padding + .or(Some(DEFAULT_WORKSPACE_PADDING.load(Ordering::Relaxed))); + let work_area = self.work_area_size; + let work_area_offset = self.work_area_offset.or(offset); + + if let Some(workspace) = self.workspaces_mut().get_mut(workspace_idx) { + workspace.globals = WorkspaceGlobals { + container_padding, + workspace_padding, + work_area, + work_area_offset, + } + } + } + + #[tracing::instrument(skip(self))] + pub fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("focusing workspace"); + + { + let workspaces = self.workspaces_mut(); + + if workspaces.get(idx).is_none() { + workspaces.resize(idx + 1, Workspace::default()); + } + self.workspaces.focus(idx); + } + + Ok(()) + } + + pub fn new_workspace_idx(&self) -> usize { + self.workspaces().len() + } + + pub fn remove_workspace_by_idx(&mut self, idx: usize) -> Option { + if idx < self.workspaces().len() { + return self.workspaces_mut().remove(idx); + } + + if idx == 0 { + self.workspaces_mut().push_back(Workspace::default()); + } else { + self.focus_workspace(idx.saturating_sub(1)).ok()?; + }; + + None + } + + pub fn add_container( + &mut self, + container: Container, + workspace_idx: Option, + ) -> eyre::Result<()> { + let workspace = if let Some(idx) = workspace_idx { + self.workspaces_mut() + .get_mut(idx) + .ok_or_eyre(format!("there is no workspace at index {}", idx))? + } else { + self.focused_workspace_mut() + .ok_or_eyre("there is no workspace")? + }; + + workspace.add_container_to_back(container); + + Ok(()) + } + + pub fn remove_workspaces(&mut self) -> VecDeque { + std::mem::take(self.workspaces_mut()) + } + + pub fn ensure_workspace_count(&mut self, ensure_count: usize) { + if self.workspaces().len() < ensure_count { + self.workspaces_mut() + .resize(ensure_count, Workspace::default()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend::fake::FakeBackend; + use crate::backend::with_backend; + use crate::window::Window; + use std::sync::Arc; + + #[test] + fn test_add_container() { + let mut m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + // Add container to the default workspace + m.add_container(Container::default(), Some(0)).unwrap(); + + // Should contain a container in the current focused workspace + let workspace = m.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 1); + } + + #[test] + fn test_remove_workspace_by_idx() { + let mut m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + let new_workspace_index = m.new_workspace_idx(); + assert_eq!(new_workspace_index, 1); + + // Create workspace 2 + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Create workspace 3 + m.focus_workspace(new_workspace_index + 1).unwrap(); + + // Should have 3 workspaces + assert_eq!(m.workspaces().len(), 3); + + // Remove workspace 1 + m.remove_workspace_by_idx(1); + + // Should have only 2 workspaces + assert_eq!(m.workspaces().len(), 2); + } + + #[test] + fn test_remove_workspaces() { + let mut m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + let new_workspace_index = m.new_workspace_idx(); + assert_eq!(new_workspace_index, 1); + + // Create workspace 2 + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Create workspace 3 + m.focus_workspace(new_workspace_index + 1).unwrap(); + + // Should have 3 workspaces + assert_eq!(m.workspaces().len(), 3); + + // Remove all workspaces + m.remove_workspaces(); + + // All workspaces should be removed + assert_eq!(m.workspaces().len(), 0); + } + + #[test] + fn test_remove_nonexistent_workspace() { + let mut m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + // Try to remove a workspace that doesn't exist + let removed_workspace = m.remove_workspace_by_idx(1); + + // Should return None since there is no workspace at index 1 + assert!(removed_workspace.is_none()); + } + + #[test] + fn test_focus_workspace() { + let mut m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + let new_workspace_index = m.new_workspace_idx(); + assert_eq!(new_workspace_index, 1); + + // Focus workspace 2 + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Should be focused on workspace 2 + assert_eq!(m.focused_workspace_idx(), 1); + } + + #[test] + fn test_new_workspace_idx() { + let m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + let new_workspace_index = m.new_workspace_idx(); + + // Should be the last workspace index: 1 + assert_eq!(new_workspace_index, 1); + } + + #[test] + fn test_ensure_workspace_count_workspace_contains_two_workspaces() { + let mut m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + // Create and focus another workspace + let new_workspace_index = m.new_workspace_idx(); + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces now + assert_eq!(m.workspaces().len(), 2, "Monitor should have 2 workspaces"); + + // Ensure the monitor has at least 5 workspaces + m.ensure_workspace_count(5); + + // Monitor should have 5 workspaces + assert_eq!(m.workspaces().len(), 5, "Monitor should have 5 workspaces"); + } + + #[test] + fn test_ensure_workspace_count_only_default_workspace() { + let mut m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + // Ensure the monitor has at least 5 workspaces + m.ensure_workspace_count(5); + + // Monitor should have 5 workspaces + assert_eq!(m.workspaces().len(), 5, "Monitor should have 5 workspaces"); + + // Try to call the ensure workspace count again to ensure it doesn't change + m.ensure_workspace_count(3); + assert_eq!(m.workspaces().len(), 5, "Monitor should have 5 workspaces"); + } + + fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect { + Rect { + left, + top, + right, + bottom, + } + } + + /// The fake's monitor, as a [`Monitor`], with one window tiled on its focused workspace + fn monitor_with_window(id: u32) -> (Arc, Monitor) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.open_window(id, "foot", "foot", "a terminal"); + + let mut m = Monitor::new( + 1, + rect(0, 0, 1920, 1080), + rect(0, 0, 1920, 1050), + "Virtual-0", + "Virtual-0", + ); + m.focused_workspace_mut() + .unwrap() + .new_container_for_window(&Window::from(id)) + .unwrap(); + + (fake, m) + } + + #[test] + fn the_focused_workspace_is_tiled_in_the_work_area_with_the_default_padding() -> eyre::Result<()> + { + let (fake, mut m) = monitor_with_window(501); + + with_backend(fake.clone(), || m.update_focused_workspace(None))?; + + // the work area leaves the panel alone; the default workspace padding and the default + // container padding are 5 each + assert_eq!(fake.rect_of(501), Some(rect(10, 10, 1900, 1030))); + Ok(()) + } + + #[test] + fn the_monitors_own_padding_and_offset_win_over_what_it_is_given() -> eyre::Result<()> { + let (fake, mut m) = monitor_with_window(511); + m.container_padding = Some(0); + m.workspace_padding = Some(0); + m.work_area_offset = Some(rect(100, 0, 100, 0)); + + with_backend(fake.clone(), || { + m.update_focused_workspace(Some(rect(0, 200, 0, 200))) + })?; + + assert_eq!(fake.rect_of(511), Some(rect(100, 0, 1820, 1050))); + Ok(()) + } +} diff --git a/komorebi/src/ring.rs b/komorebi/src/ring.rs index 0e16e2fb..cab51c2a 100644 --- a/komorebi/src/ring.rs +++ b/komorebi/src/ring.rs @@ -1,7 +1,8 @@ //! [`Ring`], a list of elements with one of them focused. //! //! Monitors, workspaces and containers each keep their children in a ring, so that "the focused -//! one" is the same thing everywhere. +//! one" is the same thing everywhere, and `impl_ring_elements!` gives each of them the same +//! accessors for it. use std::collections::VecDeque; @@ -75,10 +76,74 @@ impl Ring { } } +/// Gives a type that keeps its children in a [`Ring`] the accessors every such type has. +/// +/// `impl_ring_elements!(Workspace, Container)` reads the field `containers: Ring` and +/// gives `Workspace` the methods `containers()`, `containers_mut()`, `focused_container()`, +/// `focused_container_idx()` and `focused_container_mut()`. The field is named after the element +/// type in lower case with an `s` appended, and the methods after the field, so that "the focused +/// container" is spelled the same way on every type that has one. +macro_rules! impl_ring_elements { + ($name:ty, $element:ident) => { + pastey::paste! { + impl $name { + pub const fn [<$element:lower s>](&self) -> &std::collections::VecDeque<$element> { + self.[<$element:lower s>].elements() + } + + pub fn [<$element:lower s_mut>](&mut self) -> &mut std::collections::VecDeque<$element> { + self.[<$element:lower s>].elements_mut() + } + + #[allow(dead_code)] + pub fn [](&self) -> Option<&$element> { + self.[<$element:lower s>].focused() + } + + pub const fn [](&self) -> usize { + self.[<$element:lower s>].focused_idx() + } + + pub fn [](&mut self) -> Option<&mut $element> { + self.[<$element:lower s>].focused_mut() + } + } + } + }; +} + #[cfg(test)] mod tests { use super::*; + #[derive(Debug, PartialEq)] + struct Book(&'static str); + + struct Shelf { + books: Ring, + } + + impl_ring_elements!(Shelf, Book); + + #[test] + fn impl_ring_elements_names_the_accessors_after_the_element() { + let mut shelf = Shelf { + books: Ring::default(), + }; + shelf.books_mut().extend([Book("a"), Book("b")]); + shelf.books.focus(1); + + assert_eq!(shelf.books().len(), 2); + assert_eq!(shelf.focused_book(), Some(&Book("b"))); + assert_eq!(shelf.focused_book_idx(), 1); + + if let Some(book) = shelf.focused_book_mut() { + *book = Book("c"); + } + + assert_eq!(shelf.books()[1], Book("c")); + } + #[test] fn an_empty_ring_focuses_nothing() { let mut ring: Ring = Ring::default(); diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs new file mode 100644 index 00000000..5a213a9d --- /dev/null +++ b/komorebi/src/window.rs @@ -0,0 +1,304 @@ +//! [`Window`], the window manager's handle to a window on the desktop. +//! +//! A window is a `Copy` value that carries only the compositor's id for it. Everything else about +//! the window (its title, its class, where it is) is asked of the +//! [`Backend`](crate::backend::Backend) when it is needed, and everything done to it (a move, the +//! focus, a close) is a command to the backend. Nothing is cached, so a window that changed its +//! title, or closed, is seen as it is now. + +use crate::backend::backend; +use crate::core::Rect; +use color_eyre::eyre; +use color_eyre::eyre::OptionExt; +use serde::Deserialize; +use serde::Serialize; +use serde::Serializer; +use serde::ser::SerializeStruct; +use std::fmt::Display; +use std::fmt::Formatter; +use std::fmt::Write; +use std::path::PathBuf; + +/// A handle to a window on the desktop: just its id. +/// +/// It is `Copy`, events carry it by value, and everything else (title, class, geometry, ...) is +/// asked of the [`crate::backend::Backend`] when needed. The id is the compositor's +/// ([`WindowInfo::id`](crate::backend::WindowInfo::id)), and stays the same for the life of the +/// window. +#[derive(Debug, Default, Clone, Copy, Deserialize, PartialEq, Eq, Hash)] +pub struct Window { + pub id: u32, +} + +impl From for Window { + fn from(id: u32) -> Self { + Self { id } + } +} + +#[allow(clippy::module_name_repetitions)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct WindowDetails { + pub title: String, + pub exe: String, + pub class: String, + pub path: String, +} + +impl From<&Window> for WindowDetails { + fn from(value: &Window) -> Self { + Self::from(*value) + } +} + +impl From for WindowDetails { + fn from(value: Window) -> Self { + Self { + title: value.title().unwrap_or_default(), + exe: value.exe().unwrap_or_default(), + class: value.class().unwrap_or_default(), + path: value + .path() + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default(), + } + } +} + +impl Display for Window { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut display = format!("(window_id: {}", self.id); + + if let Some(info) = self.info() { + write!(display, ", process_id: {}", info.pid)?; + write!(display, ", title: {}", info.title)?; + write!(display, ", exe: {}", info.exe)?; + write!(display, ", class: {}", info.class)?; + } + + write!(display, ")")?; + + write!(f, "{display}") + } +} + +impl Serialize for Window { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut state = serializer.serialize_struct("Window", 3)?; + state.serialize_field("id", &self.id)?; + state.serialize_field("rect", &self.rect().unwrap_or_default())?; + state.serialize_field("details", &WindowDetails::from(*self))?; + state.end() + } +} + +#[cfg(feature = "schemars")] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +struct SerializedWindow { + id: u32, + title: String, + exe: String, + class: String, + path: String, + rect: Rect, +} + +#[cfg(feature = "schemars")] +impl schemars::JsonSchema for Window { + fn schema_name() -> std::borrow::Cow<'static, str> { + std::borrow::Cow::Borrowed("Window") + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + ::json_schema(generator) + } +} + +impl Window { + /// What the compositor knows about this window, including for a few moments after it closed + pub fn info(self) -> Option { + backend().window(self.id) + } + + /// Whether the window still exists + pub fn is_valid(self) -> bool { + backend().is_window(self.id) + } + + pub fn is_focused(self) -> bool { + backend().foreground_window() == Some(self.id) + } + + pub fn is_minimized(self) -> bool { + self.info().is_some_and(|i| i.minimized) + } + + pub fn title(self) -> Option { + self.info().map(|i| i.title) + } + + pub fn exe(self) -> Option { + self.info().map(|i| i.exe) + } + + /// The Wayland `app_id` (or X11 `WM_CLASS`) + pub fn class(self) -> Option { + self.info().map(|i| i.class) + } + + pub fn path(self) -> Option { + self.info().map(|i| PathBuf::from(i.path)) + } + + pub fn process_id(self) -> i32 { + self.info().map_or(0, |i| i.pid) + } + + /// The window's current frame geometry, as last reported by the compositor + pub fn rect(self) -> eyre::Result { + backend() + .window_rect(self.id) + .ok_or_eyre("the window does not exist") + } + + /// Asks the compositor to move and resize the window to `rect`; where the window ends up is + /// [`Window::rect`], since a client may refuse a size + pub fn set_position(self, rect: &Rect) -> eyre::Result<()> { + backend().set_rect(self.id, rect) + } + + pub fn focus(self, mouse_follows_focus: bool) -> eyre::Result<()> { + backend().focus(self.id, mouse_follows_focus) + } + + pub fn raise(self) -> eyre::Result<()> { + backend().raise(self.id) + } + + pub fn close(self) -> eyre::Result<()> { + backend().close(self.id) + } + + pub fn minimize(self) -> eyre::Result<()> { + backend().minimize(self.id) + } + + pub fn unminimize(self) -> eyre::Result<()> { + backend().unminimize(self.id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend::fake::Command; + use crate::backend::fake::FakeBackend; + use crate::backend::with_backend; + use std::sync::Arc; + + fn fake_with(id: u32) -> Arc { + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.open_window(id, "foot", "foot", "a terminal"); + fake + } + + #[test] + fn a_window_is_what_the_backend_says_it_is() -> eyre::Result<()> { + let fake = fake_with(201); + fake.set_foreground(Some(201)); + + with_backend(fake, || { + let window = Window::from(201); + + assert!(window.is_valid()); + assert!(window.is_focused()); + assert!(!window.is_minimized()); + assert_eq!(window.title().as_deref(), Some("a terminal")); + assert_eq!(window.exe().as_deref(), Some("foot")); + assert_eq!(window.class().as_deref(), Some("foot")); + assert_eq!(window.path(), Some(PathBuf::from("/usr/bin/foot"))); + assert_eq!(window.process_id(), 1201); + assert_eq!( + window.rect()?, + Rect { + left: 100, + top: 100, + right: 800, + bottom: 600, + } + ); + assert_eq!( + window.to_string(), + "(window_id: 201, process_id: 1201, title: a terminal, exe: foot, class: foot)" + ); + Ok(()) + }) + } + + #[test] + fn a_window_the_backend_does_not_know_has_no_details() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + + with_backend(fake, || { + let window = Window::from(202); + + assert!(!window.is_valid()); + assert_eq!(window.title(), None); + assert_eq!(window.process_id(), 0); + assert!(window.rect().is_err()); + assert_eq!(window.to_string(), "(window_id: 202)"); + }); + } + + #[test] + fn every_change_to_a_window_is_a_command_to_the_backend() -> eyre::Result<()> { + let fake = fake_with(203); + let tile = Rect { + left: 0, + top: 0, + right: 960, + bottom: 1050, + }; + + with_backend(fake.clone(), || { + let window = Window::from(203); + + window.set_position(&tile)?; + window.focus(false)?; + window.raise()?; + window.minimize()?; + window.unminimize()?; + window.close() + })?; + + assert_eq!( + fake.commands(), + [ + Command::SetRect(203, tile), + Command::Focus(203, false), + Command::Raise(203), + Command::Minimize(203), + Command::Unminimize(203), + Command::Close(203), + ] + ); + Ok(()) + } + + #[test] + fn a_window_serializes_with_what_the_backend_knows_about_it() -> eyre::Result<()> { + let fake = fake_with(204); + + let json = with_backend(fake, || serde_json::to_value(Window::from(204)))?; + + assert_eq!(json["id"], 204); + assert_eq!(json["rect"]["right"], 800); + assert_eq!(json["details"]["title"], "a terminal"); + assert_eq!(json["details"]["path"], "/usr/bin/foot"); + Ok(()) + } +} diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs new file mode 100644 index 00000000..5b1e4826 --- /dev/null +++ b/komorebi/src/workspace.rs @@ -0,0 +1,948 @@ +//! [`Workspace`], a ring of containers tiled by a layout. +//! +//! A workspace keeps its containers in order. [`Workspace::update`] asks the layout for one tile +//! per container in the work area it was given, less its padding, and puts every window of each +//! container on its tile with [`Window::set_position`]. The work area and the padding a workspace +//! falls back to come from the monitor it is on ([`WorkspaceGlobals`]). + +use crate::container::Container; +use crate::core::DefaultLayout; +use crate::core::Layout; +use crate::core::Rect; +use crate::lockable_sequence::LockableSequence; +use crate::ring::Ring; +use crate::window::Window; +use color_eyre::eyre; +use color_eyre::eyre::OptionExt; +use serde::Deserialize; +use serde::Serialize; +use std::collections::HashMap; +use std::num::NonZeroUsize; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct Workspace { + pub containers: Ring, + pub layout: Layout, + pub workspace_padding: Option, + pub container_padding: Option, + #[serde(skip)] + pub globals: WorkspaceGlobals, +} + +impl_ring_elements!(Workspace, Container); + +impl Default for Workspace { + fn default() -> Self { + Self { + containers: Default::default(), + workspace_padding: None, + container_padding: None, + layout: Layout::Default(DefaultLayout::BSP), + globals: Default::default(), + } + } +} + +#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq)] +/// The work area a monitor gives the workspace it shows, and the padding and the offset the +/// workspace falls back to when it sets none of its own +pub struct WorkspaceGlobals { + pub container_padding: Option, + pub workspace_padding: Option, + pub work_area: Rect, + pub work_area_offset: Option, +} + +impl Workspace { + #[tracing::instrument(skip(self))] + pub fn focus_container(&mut self, idx: usize) { + tracing::info!("focusing container"); + + self.containers.focus(idx); + } + + pub fn swap_containers(&mut self, i: usize, j: usize) { + self.containers.elements_mut().swap_respecting_locks(i, j); + self.focus_container(j); + } + + pub fn container_idx_for_window(&self, window_id: u32) -> Option { + let mut idx = None; + for (i, x) in self.containers().iter().enumerate() { + if x.contains_window(window_id) { + idx = Option::from(i); + } + } + + idx + } + + pub fn focus_container_by_window(&mut self, window_id: u32) -> eyre::Result<()> { + let container_idx = self + .container_idx_for_window(window_id) + .ok_or_eyre("there is no container/window")?; + + let container = self + .containers_mut() + .get_mut(container_idx) + .ok_or_eyre("there is no container")?; + + let window_idx = container + .idx_for_window(window_id) + .ok_or_eyre("there is no window")?; + + container.focus_window(window_idx); + + self.focus_container(container_idx); + + Ok(()) + } + + /// Puts the window in a container of its own, after the focused container (at the start of an + /// empty workspace), and focuses that container + pub fn new_container_for_window(&mut self, window: &Window) -> eyre::Result<()> { + let next_idx = if self.containers().is_empty() { + 0 + } else { + self.focused_container_idx() + 1 + }; + + let mut container = Container::default(); + container.add_window(window)?; + + self.insert_container_at_idx(next_idx, container); + + Ok(()) + } + + // this fn respects locked container indexes - we should use it for pretty much everything + // except monocle and maximize toggles + pub fn insert_container_at_idx(&mut self, idx: usize, container: Container) -> usize { + let insertion_idx = self + .containers_mut() + .insert_respecting_locks(idx, container); + + self.focus_container(insertion_idx); + + insertion_idx + } + + pub fn prune_duplicate_windows(&mut self) -> eyre::Result<()> { + let mut tracker = HashMap::new(); + let mut to_prune_from_containers = vec![]; + + for container in self.containers() { + for window in container.windows() { + let entry = tracker.entry(window.id).or_insert(0); + *entry += 1; + } + } + + for (window_id, count) in &tracker { + if *count > 1 { + to_prune_from_containers.push(*window_id); + } + } + + for id in to_prune_from_containers { + self.remove_window(id)?; + tracker.remove(&id); + } + + Ok(()) + } + + pub fn remove_window(&mut self, window_id: u32) -> eyre::Result { + let container_idx = self + .container_idx_for_window(window_id) + .ok_or_eyre("there is no window")?; + + let container = self + .containers_mut() + .get_mut(container_idx) + .ok_or_eyre("there is no container")?; + + let window_idx = container + .windows() + .iter() + .position(|window| window.id == window_id) + .ok_or_eyre("there is no window")?; + + let window = container + .remove_window_by_idx(window_idx) + .ok_or_eyre("there is no window")?; + + if container.windows().is_empty() { + self.remove_container_by_idx(container_idx); + self.focus_previous_container(); + } + + Ok(window) + } + + // this fn respects locked container indexes - we should use it for pretty much everything + // except monocle and maximize toggles + pub fn remove_container_by_idx(&mut self, idx: usize) -> Option { + self.containers_mut().remove_respecting_locks(idx) + } + + pub fn focus_previous_container(&mut self) { + let focused_idx = self.focused_container_idx(); + self.focus_container(focused_idx.saturating_sub(1)); + } + + pub fn is_empty(&self) -> bool { + self.containers().is_empty() + } + + pub fn contains_window(&self, window_id: u32) -> bool { + for container in self.containers() { + if container.contains_window(window_id) { + return true; + } + } + + false + } + + pub fn remove_focused_container(&mut self) -> Option { + let focused_idx = self.focused_container_idx(); + let container = self.remove_container_by_idx(focused_idx); + self.focus_previous_container(); + + container + } + + pub fn remove_container(&mut self, idx: usize) -> Option { + let container = self.remove_container_by_idx(idx); + self.focus_previous_container(); + + container + } + + pub fn add_container_to_back(&mut self, container: Container) { + self.containers_mut().push_back(container); + self.focus_last_container(); + } + + pub fn add_container_to_front(&mut self, container: Container) { + self.containers_mut().push_front(container); + self.focus_first_container(); + } + + fn focus_last_container(&mut self) { + self.focus_container(self.containers().len().saturating_sub(1)); + } + + fn focus_first_container(&mut self) { + self.focus_container(0); + } +} + +impl Workspace { + /// Tiles the workspace: asks the layout for a tile per container in the work area, less the + /// offset and the workspace padding, and puts every window of each container on its tile. + /// + /// Containers that have no windows left are dropped first, and so is a window that is in more + /// than one container. A tile is clamped to the work area, so it cannot bleed onto a + /// neighboring monitor. + pub fn update(&mut self) -> eyre::Result<()> { + // make sure we are never holding on to empty containers + self.prune_duplicate_windows()?; + let focused_container_idx = self.focused_container_idx(); + self.containers_mut().retain(|c| !c.windows().is_empty()); + + // make sure we are never focused on a no longer existent final empty container + if focused_container_idx >= self.containers().len() { + self.focus_container(focused_container_idx.saturating_sub(1)); + } + + let container_padding = self + .container_padding + .or(self.globals.container_padding) + .unwrap_or_default(); + let workspace_padding = self + .workspace_padding + .or(self.globals.workspace_padding) + .unwrap_or_default(); + let work_area = self.globals.work_area; + let work_area_offset = self.globals.work_area_offset; + + let mut adjusted_work_area = work_area_offset.map_or_else( + || work_area, + |offset| { + let mut with_offset = work_area; + with_offset.left += offset.left; + with_offset.top += offset.top; + with_offset.right -= offset.right; + with_offset.bottom -= offset.bottom; + + with_offset + }, + ); + + adjusted_work_area.add_padding(workspace_padding); + + // the backend batches the commands this produces and sends them together + let result = (|| -> eyre::Result<()> { + if !self.containers().is_empty() { + let mut layouts = self.layout.as_boxed_arrangement().calculate( + &adjusted_work_area, + NonZeroUsize::new(self.containers().len()).ok_or_eyre( + "there must be at least one container to calculate a workspace layout", + )?, + Some(container_padding), + None, + &[], + self.focused_container_idx(), + None, + &[], + ); + + let containers = self.containers_mut(); + + for (i, container) in containers.iter_mut().enumerate() { + if let Some(layout) = layouts.get_mut(i) { + // Every tile is clamped to the work area so it cannot bleed onto an + // adjacent monitor. + + // horizontal + if layout.left < adjusted_work_area.left { + layout.right -= adjusted_work_area.left - layout.left; + layout.left = adjusted_work_area.left; + } + let max_right_edge = adjusted_work_area.left + adjusted_work_area.right; + let current_right_edge = layout.left + layout.right; + if current_right_edge > max_right_edge { + layout.right = max_right_edge - layout.left; + } + + // vertical + if layout.top < adjusted_work_area.top { + layout.bottom -= adjusted_work_area.top - layout.top; + layout.top = adjusted_work_area.top; + } + let max_bottom_edge = adjusted_work_area.top + adjusted_work_area.bottom; + let current_bottom_edge = layout.top + layout.bottom; + if current_bottom_edge > max_bottom_edge { + layout.bottom = max_bottom_edge - layout.top; + } + + for window in container.windows_mut() { + if let Err(error) = window.set_position(layout) { + tracing::warn!("failed to set window position: {error}") + } + } + } + } + } + Ok(()) + })(); + + result?; + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend::fake::FakeBackend; + use crate::backend::with_backend; + use crate::container::Container; + use crate::window::Window; + use std::collections::HashMap; + use std::sync::Arc; + + #[test] + fn test_locked_containers_with_new_window() { + let mut ws = Workspace::default(); + + let mut state = HashMap::new(); + + // add 4 containers + for i in 0..4 { + let mut container = Container::default(); + if i == 3 { + container.locked = true; // set index 3 locked + } + state.insert(i, container.id.to_string()); + ws.add_container_to_back(container); + } + assert_eq!(ws.containers().len(), 4); + + // focus container at index 2 + ws.focus_container(2); + + // simulate a new window being launched on this workspace + ws.new_container_for_window(&Window::from(123)).unwrap(); + + // new length should be 5, with the focus on the new window at index 4 + assert_eq!(ws.containers().len(), 5); + assert_eq!(ws.focused_container_idx(), 4); + assert_eq!( + ws.focused_container().unwrap().focused_window().unwrap().id, + 123 + ); + + // when inserting a new container at index 0, index 3's container should not change + ws.focus_container(0); + ws.new_container_for_window(&Window::from(234)).unwrap(); + assert_eq!( + ws.containers()[3].id.to_string(), + state.get(&3).unwrap().to_string() + ); + } + + #[test] + fn test_locked_containers_remove_window() { + let mut ws = Workspace::default(); + + // add 4 containers + for i in 0..4 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + if i == 1 { + container.locked = true; + } + ws.add_container_to_back(container); + } + assert_eq!(ws.containers().len(), 4); + + ws.remove_window(0).unwrap(); + assert_eq!(ws.containers()[0].focused_window().unwrap().id, 2); + // index 1 should still be the same + assert_eq!(ws.containers()[1].focused_window().unwrap().id, 1); + assert_eq!(ws.containers()[2].focused_window().unwrap().id, 3); + } + + #[test] + fn test_contains_window() { + // Create default workspace + let mut workspace = Workspace::default(); + + // Add a window to the container + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(0)); + + // Add container + workspace.add_container_to_back(container); + + // Should be true + assert!(workspace.contains_window(0)); + + // Should be false + assert!(!workspace.is_empty()) + } + + #[test] + fn test_add_container_to_back() { + let mut workspace = Workspace::default(); + + { + // Container with 3 windows + let mut container = Container::default(); + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + workspace.add_container_to_back(container); + } + + { + // Container with 1 window + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + } + // Should have 2 containers + assert_eq!(workspace.containers().len(), 2); + + // Get focused container. Should be the index of the last container added + let container = workspace.focused_container_mut().unwrap(); + + // Should be focused on the container with 1 window + assert_eq!(container.windows().len(), 1); + } + + #[test] + fn test_add_container_to_front() { + let mut workspace = Workspace::default(); + + { + // Container with 1 window + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_front(container); + } + + { + // Container with 3 windows + let mut container = Container::default(); + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + workspace.add_container_to_front(container); + } + // Should have 2 containers + assert_eq!(workspace.containers().len(), 2); + + // Get focused container. Should be the index of the last container added + let container = workspace.focused_container_mut().unwrap(); + + // Should be focused on the container with 3 windows + assert_eq!(container.windows().len(), 3); + } + + #[test] + fn test_remove_non_existent_window() { + let mut workspace = Workspace::default(); + + { + // Add a container with one window + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + } + + // Attempt to remove a non-existent window + let result = workspace.remove_window(2); + + // Should return an error + assert!( + result.is_err(), + "Expected an error when removing a non-existent window" + ); + + // Get focused container. Should be the index of the last container added + let container = workspace.focused_container_mut().unwrap(); + + // Should still have 1 window + assert_eq!(container.windows().len(), 1); + } + + #[test] + fn test_remove_focused_container() { + let mut workspace = Workspace::default(); + + { + // Container with 1 window + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + } + + { + // Container with 1 window + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + } + // Should have 2 containers + assert_eq!(workspace.containers().len(), 2); + + // Should be focused on the container at index 1 + assert_eq!(workspace.focused_container_idx(), 1); + + // Store the container at index 1 before removal + let container_to_remove = workspace.containers().get(1).cloned(); + workspace.remove_focused_container(); + + // Should only have 1 container + assert_eq!(workspace.containers().len(), 1); + + // Should be focused on the container at index 0 + assert_eq!(workspace.focused_container_idx(), 0); + + // Ensure the container at index 1 before removal is no longer present + assert!(container_to_remove.is_some()); + assert!( + !workspace + .containers() + .contains(&container_to_remove.unwrap()) + ); + } + + #[test] + fn test_insert_container_at_idx() { + let mut workspace = Workspace::default(); + + for i in 0..4 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + workspace.add_container_to_back(container); + } + + // Should have 4 containers + assert_eq!(workspace.containers().len(), 4); + + // Should be focused on the last container + assert_eq!(workspace.focused_container_idx(), 3); + + // Insert a container at index 4 + workspace.insert_container_at_idx(4, Container::default()); + + // Should have 5 containers + assert_eq!(workspace.containers().len(), 5); + + // Should be focused on the newly inserted container + assert_eq!(workspace.focused_container_idx(), 4); + } + + #[test] + fn test_remove_container_by_idx() { + let mut workspace = Workspace::default(); + + for i in 0..3 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + workspace.add_container_to_back(container); + } + + // Should have 3 containers + assert_eq!(workspace.containers().len(), 3); + + // Should be focused on the last container + assert_eq!(workspace.focused_container_idx(), 2); + + // Store the container at index 1 before removal + let container_to_remove = workspace.containers().get(1).cloned(); + + // Remove the container at index 1 + workspace.remove_container_by_idx(1); + + // Should have 2 containers + assert_eq!(workspace.containers().len(), 2); + + // Ensure the container at index 1 before removal is no longer present + assert!(container_to_remove.is_some()); + assert!( + !workspace + .containers() + .contains(&container_to_remove.unwrap()) + ); + } + + #[test] + fn test_remove_container() { + let mut workspace = Workspace::default(); + + for i in 0..3 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + workspace.add_container_to_back(container); + } + + // Should have 3 containers + assert_eq!(workspace.containers().len(), 3); + + // Should be focused on the last container + assert_eq!(workspace.focused_container_idx(), 2); + + // Store the container at index 2 before removal + let container_to_remove = workspace.containers().get(2).cloned(); + + // Remove the container at index 2 + workspace.remove_container(2); + + // Should be focused on the previous container which is index 1 + assert_eq!(workspace.focused_container_idx(), 1); + + // Should have 2 containers + assert_eq!(workspace.containers().len(), 2); + + // Ensure the container at index 1 before removal is no longer present + assert!(container_to_remove.is_some()); + assert!( + !workspace + .containers() + .contains(&container_to_remove.unwrap()) + ); + } + + #[test] + fn test_focus_container() { + let mut workspace = Workspace::default(); + + for i in 0..3 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + workspace.add_container_to_back(container); + } + + // Should have 3 containers + assert_eq!(workspace.containers().len(), 3); + + // Should be focused on the last container + assert_eq!(workspace.focused_container_idx(), 2); + + // Focus on container 1 + workspace.focus_container(1); + assert_eq!(workspace.focused_container_idx(), 1); + + // Focus on container 0 + workspace.focus_container(0); + assert_eq!(workspace.focused_container_idx(), 0); + + // Focus on container 2 + workspace.focus_container(2); + assert_eq!(workspace.focused_container_idx(), 2); + } + + #[test] + fn test_focus_previous_container() { + let mut workspace = Workspace::default(); + + for i in 0..3 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + workspace.add_container_to_back(container); + } + + // Should have 3 containers + assert_eq!(workspace.containers().len(), 3); + + // Should be focused on the last container + assert_eq!(workspace.focused_container_idx(), 2); + + // Focus on the previous container + workspace.focus_previous_container(); + + // Should be focused on container 1 + assert_eq!(workspace.focused_container_idx(), 1); + } + + #[test] + fn test_focus_last_container() { + let mut workspace = Workspace::default(); + + for i in 0..3 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + workspace.add_container_to_back(container); + } + + // Should have 3 containers + assert_eq!(workspace.containers().len(), 3); + + // Change focus to the first container for the test + workspace.focus_container(0); + assert_eq!(workspace.focused_container_idx(), 0); + + // Focus on the last container + workspace.focus_last_container(); + + // Should be focused on container 1 + assert_eq!(workspace.focused_container_idx(), 2); + } + + #[test] + fn test_focus_first_container() { + let mut workspace = Workspace::default(); + + for i in 0..3 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + workspace.add_container_to_back(container); + } + + // Should have 3 containers + assert_eq!(workspace.containers().len(), 3); + + // Should be focused on the last container + assert_eq!(workspace.focused_container_idx(), 2); + + // Focus on the first container + workspace.focus_first_container(); + + // Should be focused on container 1 + assert_eq!(workspace.focused_container_idx(), 0); + } + + #[test] + fn test_swap_containers() { + let mut workspace = Workspace::default(); + + { + let mut container = Container::default(); + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + workspace.add_container_to_back(container); + } + + { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + } + + // Should have 2 containers + assert_eq!(workspace.containers().len(), 2); + + { + // Should be focused on container 1 + assert_eq!(workspace.focused_container_idx(), 1); + + // Should have 1 window + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 1); + } + + // Swap containers 0 and 1 + workspace.swap_containers(0, 1); + + { + // Should be focused on container 0 + assert_eq!(workspace.focused_container_idx(), 1); + + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 3); + } + } + + #[test] + fn test_new_container_for_window() { + let mut workspace = Workspace::default(); + + { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + } + + // Add new window to container + workspace + .new_container_for_window(&Window::from(2)) + .unwrap(); + + // Container 0 should have 1 window + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 1); + + // Should return true that window 2 exists + assert!(workspace.contains_window(2)); + } + + #[test] + fn test_remove_window() { + let mut workspace = Workspace::default(); + + { + // Container with 1 window + let mut container = Container::default(); + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + workspace.add_container_to_back(container); + } + + // Remove window 1 + workspace.remove_window(1).ok(); + + // Should have 2 windows + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 2); + + // Check that window 1 is removed + assert!(!workspace.contains_window(1)); + } + + #[test] + fn test_focus_container_by_window() { + let mut workspace = Workspace::default(); + + { + // Container with 3 windows + let mut container = Container::default(); + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + workspace.add_container_to_back(container); + } + + { + // Container with 1 window + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(4)); + workspace.add_container_to_back(container); + } + + // Focus container by window + workspace.focus_container_by_window(1).unwrap(); + + // Should be focused on workspace 0 + assert_eq!(workspace.focused_container_idx(), 0); + + // Should be focused on window 1 and hwnd should be 1 + let focused_container = workspace.focused_container_mut().unwrap(); + assert_eq!(focused_container.focused_window().unwrap().id, 1); + assert_eq!(focused_container.focused_window_idx(), 1); + } + + fn tile(left: i32, top: i32, right: i32, bottom: i32) -> Rect { + Rect { + left, + top, + right, + bottom, + } + } + + /// A workspace on the fake's 1920x1080 monitor, whose work area is 1920x1050, with a container + /// for each of `ids` + fn workspace_with(ids: &[u32]) -> (Arc, Workspace) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let mut workspace = Workspace::default(); + workspace.globals.work_area = tile(0, 0, 1920, 1050); + + for id in ids { + fake.open_window(*id, "foot", "foot", &format!("terminal {id}")); + workspace + .new_container_for_window(&Window::from(*id)) + .unwrap(); + } + + (fake, workspace) + } + + #[test] + fn update_puts_each_window_on_its_tile() -> eyre::Result<()> { + let (fake, mut workspace) = workspace_with(&[401, 402]); + + with_backend(fake.clone(), || workspace.update())?; + + assert_eq!(fake.rect_of(401), Some(tile(0, 0, 960, 1050))); + assert_eq!(fake.rect_of(402), Some(tile(960, 0, 960, 1050))); + Ok(()) + } + + #[test] + fn update_leaves_the_padding_and_the_offset_free() -> eyre::Result<()> { + let (fake, mut workspace) = workspace_with(&[411]); + workspace.workspace_padding = Some(10); + workspace.container_padding = Some(5); + workspace.globals.work_area_offset = Some(tile(0, 40, 0, 40)); + + with_backend(fake.clone(), || workspace.update())?; + + // the offset moves the top edge down by 40, the workspace padding takes 10 off every edge, + // and the container padding 5 more + assert_eq!(fake.rect_of(411), Some(tile(15, 55, 1890, 980))); + Ok(()) + } + + #[test] + fn update_drops_a_container_that_has_no_windows_left() -> eyre::Result<()> { + let (fake, mut workspace) = workspace_with(&[421]); + workspace.add_container_to_back(Container::default()); + + with_backend(fake.clone(), || workspace.update())?; + + assert_eq!(workspace.containers().len(), 1); + assert_eq!(workspace.focused_container_idx(), 0); + assert_eq!(fake.rect_of(421), Some(tile(0, 0, 1920, 1050))); + Ok(()) + } +} From 02231d232c18fab36a9d5ab43ee9e56336c3f1c3 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 12:09:52 -0700 Subject: [PATCH 010/255] feat(wm): tile what the backend reports With the model in place, the window manager can do its job: load the desktop from the backend, tile it, and keep it tiled as the compositor reports what happens to windows. The events are the Windows implementation's, each about one window and carrying it: a window is shown, destroyed, given the focus, minimized or restored. A new window gets a container of its own after the focused one, a closed one leaves whichever workspace has it, a window the user minimizes is out of the layout until it is restored, and every event ends with the workspace in front tiled again. At startup every monitor is loaded, and every open window that is normal, alive and not minimized goes on the monitor its middle is on. An index from each managed window to its monitor and workspace is rebuilt around every event, so that the first event komorebi sees can be the close of a window it picked up at startup. Whether a window is managed is, for now, only whether the compositor calls it a normal window and it is alive; the rules that ignore, manage or float applications come later. When a window closes, komorebi leaves the choice of the next focus to KWin unless KWin focuses nothing, so the two do not fight. The daemon runs this against a backend chosen on the command line. --fake-backend, an in-memory desktop with one monitor, is the only one, and without it komorebi exits with a usage error instead of pretending to manage a desktop it cannot reach. --- Cargo.lock | 129 +++++++++++ Cargo.toml | 1 + README.md | 18 +- docs/dev/ARCHITECTURE.md | 66 +++++- docs/dev/DESIGN.md | 8 + komorebi/Cargo.toml | 2 + komorebi/src/desktop.rs | 216 ++++++++++++++++++ komorebi/src/lib.rs | 17 +- komorebi/src/main.rs | 129 ++++++++++- komorebi/src/process_event.rs | 160 ++++++++++++++ komorebi/src/window.rs | 37 ++++ komorebi/src/window_manager.rs | 315 +++++++++++++++++++++++++++ komorebi/src/window_manager_event.rs | 101 +++++++++ komorebi/src/workspace.rs | 22 ++ komorebi/tests/no_backend.rs | 19 ++ komorebi/tests/wm_events.rs | 242 ++++++++++++++++++++ 16 files changed, 1469 insertions(+), 13 deletions(-) create mode 100644 komorebi/src/desktop.rs create mode 100644 komorebi/src/process_event.rs create mode 100644 komorebi/src/window_manager.rs create mode 100644 komorebi/src/window_manager_event.rs create mode 100644 komorebi/tests/no_backend.rs create mode 100644 komorebi/tests/wm_events.rs diff --git a/Cargo.lock b/Cargo.lock index 3eaaca44..b5a228de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,15 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "android_system_properties" version = "0.1.6" @@ -115,6 +124,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + [[package]] name = "bs58" version = "0.5.1" @@ -148,6 +166,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chrono" version = "0.4.45" @@ -261,6 +285,17 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "ctrlc" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162" +dependencies = [ + "dispatch2", + "nix", + "windows-sys", +] + [[package]] name = "darling" version = "0.24.1" @@ -335,6 +370,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -745,6 +792,7 @@ version = "0.1.0" dependencies = [ "clap", "color-eyre", + "ctrlc", "komorebi-layouts", "nanoid", "parking_lot", @@ -755,6 +803,7 @@ dependencies = [ "serde_with", "strum", "tracing", + "tracing-subscriber", "version", ] @@ -851,6 +900,15 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + [[package]] name = "memchr" version = "2.8.3" @@ -875,6 +933,27 @@ dependencies = [ "rand", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -899,6 +978,21 @@ dependencies = [ "libc", ] +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + [[package]] name = "object" version = "0.40.0" @@ -1095,6 +1189,23 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "rustc-demangle" version = "0.1.28" @@ -1516,15 +1627,33 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + [[package]] name = "tracing-subscriber" version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", "sharded-slab", + "smallvec", "thread_local", + "tracing", "tracing-core", + "tracing-log", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 9421cf18..6bd3f573 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ serde = { version = "1", features = ["derive"] } serde_json = { package = "serde_json_lenient", version = "0.2" } shadow-rs = "1" tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } [workspace.metadata.crane] name = "komorebi-workspace" diff --git a/README.md b/README.md index 73bf0fff..4b613c76 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,13 @@ moving and the drawing. ```sh nix develop cargo run --bin komorebi --locked -- --version +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. + `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 use. With [direnv](https://direnv.net), the [`.envrc`](.envrc) does it on @@ -25,8 +30,11 @@ without a checkout of the toolchain. the vocabulary the window manager is written in (`core`), the `Backend` trait through which it reaches a compositor and the in-memory desktop the tests use (`backend`), the model of what it tiles (`monitor`, `workspace`, `container`, - `window`), the `Ring` that holds monitors, workspaces and containers, and the - lists in which some elements are locked in place. + `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. - [`version`](version): the version string every binary reports. The layouts, which turn a work area and a number of containers into a rectangle @@ -58,7 +66,11 @@ describes the trait and where each of its rules is enforced. 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 -area, and every window of a container is moved onto its tile. +area, and every window of a container is moved onto its tile. At startup the +window manager loads the monitors and the windows that are open from the +backend and tiles them; after that it changes the model when the compositor +reports that a window was shown, closed, focused, minimized or restored, and +tiles the workspace in front again. ## Documentation diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 4cc7e90e..6eee4f58 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -6,8 +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, and the model of the desktop the window manager tiles. 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, 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 @@ -21,6 +22,8 @@ each part of the daemon that is added has its place here. that tile. - **Layout**: the arrangement (BSP, columns, rows, ...) that turns a work area and a number of containers into one rectangle, a **tile**, for each container. +- **Event**: what the compositor reports about a window: it was shown, destroyed, given + the focus, minimized or restored ([`WindowManagerEvent`]). - **Compositor**: the program that owns the screen and the windows. On KDE Plasma it is KWin. - **Backend**: the implementation of the [`Backend`](../../komorebi/src/backend/mod.rs) @@ -74,6 +77,13 @@ area, the layout gives one tile per container, in order, each shrunk by the cont padding, and every window of a container is asked to move onto its tile with `set_rect`. A tile is clamped to the work area, so it cannot reach onto a neighboring monitor. +The [`WindowManager`] keeps the monitors, the windows the user minimized (they are in no +workspace until they are restored), and an index from each window it manages to the +monitor and workspace that have it. It is loaded from the backend at startup: every +monitor, and every open window that is normal, alive and not minimized, on the focused +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 parts - [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the @@ -87,6 +97,17 @@ tile is clamped to the work area, so it cannot reach onto a neighboring monitor. - [`lockable_sequence`](../../komorebi/src/lockable_sequence.rs): inserting, removing and swapping in a list where some elements are locked in place, which is how a workspace changes its containers. +- [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the + operations on it (tile the workspace in front, tile every monitor, take a minimized + window out). +- [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from + the backend. +- [`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. 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 @@ -119,12 +140,42 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none | | A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error`, against the fake only | none | | 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 | | 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. +## 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. +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 + already has the window, or the index has it on another monitor or workspace, the event + creates nothing. +4. [`Workspace::new_container_for_window`] puts the window in a new container after the + focused one, inserted through `LockableSequence` so that a locked container keeps its + index, and focuses the new container. +5. [`WindowManager::update_focused_workspace`] asks the focused [`Monitor`] to give its + focused workspace the work area, the padding and the offset ([`WorkspaceGlobals`]), + and calls [`Workspace::update`]. +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. +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. + ## Where to look in the code - [`komorebi/src/backend/mod.rs`](../../komorebi/src/backend/mod.rs): the trait. @@ -136,6 +187,10 @@ breaks the first, and a module that talks to D-Bus directly breaks the second. `Workspace::update`. - [`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. +- [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager + driven end to end against the fake. [`Backend`]: ../../komorebi/src/backend/mod.rs [`WindowInfo`]: ../../komorebi/src/backend/mod.rs @@ -150,3 +205,10 @@ breaks the first, and a module that talks to D-Bus directly breaks the second. [`WorkspaceGlobals`]: ../../komorebi/src/workspace.rs [`Container`]: ../../komorebi/src/container.rs [`Window`]: ../../komorebi/src/window.rs +[`Window::should_manage`]: ../../komorebi/src/window.rs +[`Window::set_position`]: ../../komorebi/src/window.rs +[`Workspace::new_container_for_window`]: ../../komorebi/src/workspace.rs +[`WindowManager`]: ../../komorebi/src/window_manager.rs +[`WindowManager::process_event`]: ../../komorebi/src/process_event.rs +[`WindowManager::update_focused_workspace`]: ../../komorebi/src/window_manager.rs +[`WindowManagerEvent`]: ../../komorebi/src/window_manager_event.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index d81199e7..7b268893 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -50,3 +50,11 @@ window ended up. A backend keeps a table that the compositor's events update, so is a lookup. The trade-off is that the table can be a moment behind the compositor, which is why a command returns when it has been accepted and not when the client has acted, and why the frame a window really has is read back afterwards. + +## Why does komorebi not pick the next window to focus when one closes? + +Because the compositor already has. When a window is destroyed, KWin activates the window +it considers next and reports that as a focus change, which komorebi follows. If komorebi +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. diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 5f4d2939..ff229a13 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -10,6 +10,7 @@ version = { path = "../version" } clap = { workspace = true } color-eyre = { workspace = true } +ctrlc = { version = "3", features = ["termination"] } nanoid = "0.4" parking_lot = "0.12" pastey = { workspace = true } @@ -18,6 +19,7 @@ serde = { workspace = true } serde_with = { version = "3", features = ["schemars_1"] } strum = { version = "0.28", features = ["derive"] } tracing = { workspace = true } +tracing-subscriber = { workspace = true } [dev-dependencies] serde_json = { workspace = true } diff --git a/komorebi/src/desktop.rs b/komorebi/src/desktop.rs new file mode 100644 index 00000000..e3bd966f --- /dev/null +++ b/komorebi/src/desktop.rs @@ -0,0 +1,216 @@ +//! Loads what the backend reports about the desktop (its monitors, and the windows that are +//! already open) into the window manager. +//! +//! [`WindowManager::init`] calls [`load_monitor_information`] and then +//! [`load_workspace_information`], so that starting komorebi tiles what is on screen. Both read +//! the backend installed for the calling thread ([`crate::backend::backend`]). +//! +//! # Example +//! +//! ```rust +//! use std::sync::Arc; +//! +//! use komorebi::backend::fake::FakeBackend; +//! use komorebi::backend::with_backend; +//! use komorebi::desktop::load_monitor_information; +//! use komorebi::desktop::load_workspace_information; +//! use komorebi::window_manager::WindowManager; +//! +//! let fake = Arc::new(FakeBackend::with_one_monitor()); +//! fake.open_window(1, "foot", "foot", "a terminal"); +//! +//! let mut wm = WindowManager::new()?; +//! with_backend(fake, || { +//! load_monitor_information(&mut wm)?; +//! load_workspace_information(&mut wm) +//! })?; +//! +//! assert_eq!(wm.monitors().len(), 1); +//! assert!(wm.focused_workspace()?.contains_window(1)); +//! # Ok::<(), color_eyre::eyre::Report>(()) +//! ``` + +#![deny(missing_docs)] + +use crate::backend::backend; +use crate::container::Container; +use crate::core::Rect; +use crate::monitor::Monitor; +use crate::window::Window; +use crate::window_manager::WindowManager; +use color_eyre::eyre; + +fn contains_point(area: &Rect, x: i32, y: i32) -> bool { + x >= area.left && x < area.left + area.right && y >= area.top && y < area.top + area.bottom +} + +/// Returns every connected monitor, as the window manager models it, in the backend's order. +/// +/// Each [`Monitor`] has the backend's id, bounds and work area, the output's name as its device, +/// the backend's identity as its serial number id, and one empty workspace. +/// +/// # Errors +/// +/// When the backend cannot report its monitors +/// ([`Backend::monitors`](crate::backend::Backend::monitors)). +/// +/// # Example +/// +/// ```rust +/// use std::sync::Arc; +/// +/// use komorebi::backend::fake::FakeBackend; +/// use komorebi::backend::with_backend; +/// use komorebi::desktop::latest_monitor_information; +/// +/// let fake = Arc::new(FakeBackend::with_one_monitor()); +/// +/// let monitors = with_backend(fake, latest_monitor_information)?; +/// +/// assert_eq!(monitors.len(), 1); +/// assert_eq!(monitors[0].device, "Virtual-0"); +/// assert_eq!(monitors[0].work_area_size.bottom, 1050); +/// assert_eq!(monitors[0].workspaces().len(), 1); +/// # Ok::<(), color_eyre::eyre::Report>(()) +/// ``` +pub fn latest_monitor_information() -> eyre::Result> { + Ok(backend() + .monitors()? + .into_iter() + .map(|m| Monitor::new(m.id, m.size, m.work_area, &m.name, &m.serial_number_id)) + .collect()) +} + +/// Adds the monitors the window manager does not have yet, after the ones it has, in the +/// backend's order. +/// +/// A monitor is known when the window manager has one with the same serial number id, so +/// loading twice adds nothing the second time, and a known monitor keeps its workspaces. +/// +/// # Errors +/// +/// When the backend cannot report its monitors +/// ([`Backend::monitors`](crate::backend::Backend::monitors)). +/// +/// # Example +/// +/// ```rust +/// use std::sync::Arc; +/// +/// use komorebi::backend::fake::FakeBackend; +/// use komorebi::backend::with_backend; +/// use komorebi::desktop::load_monitor_information; +/// use komorebi::window_manager::WindowManager; +/// +/// let fake = Arc::new(FakeBackend::with_one_monitor()); +/// let mut wm = WindowManager::new()?; +/// +/// with_backend(fake, || { +/// load_monitor_information(&mut wm)?; +/// load_monitor_information(&mut wm) +/// })?; +/// +/// assert_eq!(wm.monitors().len(), 1); +/// # Ok::<(), color_eyre::eyre::Report>(()) +/// ``` +#[tracing::instrument(skip_all)] +pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { + let all_devices = latest_monitor_information()?; + + let monitors = &mut wm.monitors; + + 'read: for device in all_devices { + for monitor in monitors.elements() { + if device.serial_number_id.eq(&monitor.serial_number_id) { + continue 'read; + } + } + + monitors.elements_mut().push_back(device); + } + + Ok(()) +} + +/// Puts the windows that are already open into containers on the focused workspace of the +/// monitor they are on, so that starting komorebi tiles what is on screen. +/// +/// A window is on the monitor whose bounds contain its middle. A window that is minimized, that +/// komorebi does not manage ([`Window::should_manage`]), or that is on no monitor is left alone. +/// Nothing is moved: tiling is [`WindowManager::retile_all`]'s job. +/// +/// # Errors +/// +/// This never returns an error: a window that cannot be placed is skipped. +/// +/// # Example +/// +/// ```rust +/// use std::sync::Arc; +/// +/// use komorebi::backend::fake::FakeBackend; +/// use komorebi::backend::with_backend; +/// use komorebi::desktop::load_monitor_information; +/// use komorebi::desktop::load_workspace_information; +/// use komorebi::window_manager::WindowManager; +/// +/// let fake = Arc::new(FakeBackend::with_one_monitor()); +/// fake.open_window(1, "foot", "foot", "a terminal"); +/// fake.open_window(2, "foot", "foot", "a dialog"); +/// fake.set_normal(2, false); +/// +/// let mut wm = WindowManager::new()?; +/// with_backend(fake, || { +/// load_monitor_information(&mut wm)?; +/// load_workspace_information(&mut wm) +/// })?; +/// +/// let workspace = wm.focused_workspace()?; +/// assert!(workspace.contains_window(1)); +/// assert!(!workspace.contains_window(2)); +/// # Ok::<(), color_eyre::eyre::Report>(()) +/// ``` +#[tracing::instrument(skip_all)] +pub fn load_workspace_information(wm: &mut WindowManager) -> eyre::Result<()> { + let mut valid_window_count = 0; + + for info in backend().windows() { + if info.minimized { + continue; + } + + let window = Window::from(info.id); + if !window.should_manage() { + continue; + } + + let (x, y) = ( + info.rect.left + info.rect.right / 2, + info.rect.top + info.rect.bottom / 2, + ); + + let Some(monitor_idx) = wm + .monitors() + .iter() + .position(|m| contains_point(&m.size, x, y)) + else { + continue; + }; + + let Some(monitor) = wm.monitors_mut().get_mut(monitor_idx) else { + continue; + }; + let workspace_idx = monitor.focused_workspace_idx(); + + if let Some(workspace) = monitor.workspaces_mut().get_mut(workspace_idx) { + let mut container = Container::default(); + container.windows_mut().push_back(window); + workspace.containers_mut().push_back(container); + valid_window_count += 1; + } + } + + tracing::info!("{valid_window_count} valid windows identified"); + + Ok(()) +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index c8bf620f..6d9a7be6 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -1,11 +1,16 @@ -//! The komorebi daemon's library: the vocabulary the window manager is written in and the data -//! structures it is built from. +//! The komorebi daemon's library: the vocabulary the window manager is written in, the data +//! structures it is built from, and the window manager. //! //! The desktop is modeled as monitors ([`monitor::Monitor`]), each with a ring of workspaces //! ([`workspace::Workspace`]), each with a ring of containers ([`container::Container`]), each with //! a ring of windows ([`window::Window`]). A workspace tiles its containers by its layout, and a //! window is moved by asking the [`backend`]. +//! +//! 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`]). +use color_eyre::eyre; use std::sync::atomic::AtomicI32; #[macro_use] @@ -14,11 +19,19 @@ pub mod ring; pub mod backend; pub mod container; pub mod core; +pub mod desktop; 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 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; + /// 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 6fe29ec1..39eb1c3f 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -1,15 +1,132 @@ //! The komorebi daemon: a tiling window manager for KDE Plasma. //! -//! The daemon owns the layout of every window and asks KWin, the window -//! manager of Plasma, to put each one where the layout says. +//! 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`. +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::window_manager::WindowManager; +use serde::Deserialize; +use std::sync::Arc; +use tracing_subscriber::EnvFilter; + +fn setup(log_level: LogLevel) -> eyre::Result<()> { + if std::env::var("RUST_LIB_BACKTRACE").is_err() { + unsafe { + std::env::set_var("RUST_LIB_BACKTRACE", "1"); + } + } + + color_eyre::install()?; + + if std::env::var("RUST_LOG").is_err() { + unsafe { + std::env::set_var( + "RUST_LOG", + match log_level { + LogLevel::Error => "komorebi=error", + LogLevel::Warn => "komorebi=warn", + LogLevel::Info => "komorebi=info", + LogLevel::Debug => "komorebi=debug", + LogLevel::Trace => "komorebi=trace", + }, + ); + } + } + + tracing::subscriber::set_global_default( + tracing_subscriber::fmt::Subscriber::builder() + .with_env_filter(EnvFilter::from_default_env()) + .finish(), + )?; + + // https://github.com/tokio-rs/tracing/blob/master/examples/examples/panic_hook.rs + // Set a panic hook that records the panic as a `tracing` event at the + // `ERROR` verbosity level. + std::panic::set_hook(Box::new(|panic| { + panic.location().map_or_else( + || { + tracing::error!(message = %panic); + }, + |location| { + tracing::error!( + message = %panic, + panic.file = location.file(), + panic.line = location.line(), + panic.column = location.column(), + ); + }, + ); + })); + + Ok(()) +} + +#[derive(Default, Deserialize, ValueEnum, Clone)] +#[serde(rename_all = "snake_case")] +enum LogLevel { + Error, + Warn, + #[default] + Info, + Debug, + Trace, +} /// A tiling window manager for KDE Plasma. #[derive(Parser)] #[clap(author, about, version = version::LONG_VERSION)] -struct Opts {} - -fn main() { - Opts::parse(); +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)] + fake_backend: bool, +} + +fn main() -> eyre::Result<()> { + let opts: Opts = Opts::parse(); + setup(opts.log_level)?; + + if opts.fake_backend { + 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(); + } + + let mut wm = WindowManager::new()?; + wm.init()?; + wm.retile_all()?; + + let (quit_sender, quit_receiver) = std::sync::mpsc::channel(); + ctrlc::set_handler(move || { + let _ = quit_sender.send(()); + }) + .expect("could not set ctrl-c handler"); + + // this thread only waits to be told to stop + let _ = quit_receiver.recv(); + tracing::info!("stop signal received"); + + backend::backend().shutdown(); + + std::process::exit(130); } diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs new file mode 100644 index 00000000..d14e3059 --- /dev/null +++ b/komorebi/src/process_event.rs @@ -0,0 +1,160 @@ +//! How the window manager answers what the compositor reports: [`WindowManager::process_event`]. +//! +//! An event about a window komorebi does not manage ([`Window::should_manage`]) changes nothing. +//! Otherwise: +//! +//! - **Show**: the window gets a container of its own after the focused one, and the workspace is +//! tiled again. The first window on an empty workspace is given the focus. +//! - **Destroy**: the window is taken out of whichever workspace has it, and if that is the one in +//! front it is tiled again. +//! - **FocusChange**: the workspace is tiled again and the container of the window that has the +//! focus becomes the focused container. +//! - **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. +//! +//! [`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 tracing::instrument; + +/// 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. +fn should_refocus_after_destroy(foreground: Option) -> bool { + foreground.is_none() +} + +impl WindowManager { + /// Handle an event from the compositor, and log how long it took + pub fn process_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> { + let started = std::time::Instant::now(); + let result = self.handle_event(event); + tracing::debug!("handled {event} in {:?}", started.elapsed()); + result + } + + #[instrument(skip_all)] + fn handle_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> { + let Some(window) = event.window() else { + return Ok(()); + }; + let window_id = window.id; + + // A destroyed window can no longer be asked whether it should be managed, so a removal is + // let through without asking + let is_removal = matches!(event, WindowManagerEvent::Destroy(_, _)); + + let should_manage = is_removal || window.should_manage(); + + if !should_manage { + tracing::debug!("ignoring event as window should not be managed: {window}"); + return Ok(()); + } + + tracing::info!( + "processing event: {event} for window {window_id} with notification {}", + event.notification(), + ); + + // events are read against what is in the containers now, not against what was there when the + // last one finished + self.update_known_window_ids(); + + match event { + WindowManagerEvent::FocusChange(_, _) => { + let mut is_on_current_workspace = false; + + // don't want to trigger the full workspace updates when there are no managed + // containers + if !self.focused_workspace()?.containers().is_empty() { + self.update_focused_workspace(self.mouse_follows_focus, false)?; + } + + let workspace = self.focused_workspace_mut()?; + if workspace.contains_window(window_id) { + is_on_current_workspace = true; + } + + if is_on_current_workspace { + workspace.focus_container_by_window(window_id)?; + } + } + WindowManagerEvent::Show(_, _) => { + let mut create = true; + + if self.focused_workspace()?.contains_window(window_id) { + tracing::debug!("ignoring show event for window already on workspace"); + + // ignore bogus show events + create = false; + } + + if let Some((m_idx, w_idx)) = self.known_window_ids.get(&window_id) + && let Ok(focused_workspace_idx) = self.focused_workspace_idx() + && (*m_idx != self.focused_monitor_idx() || *w_idx != focused_workspace_idx) + { + tracing::debug!( + "ignoring show event for window already associated with another workspace" + ); + + create = false; + } + + if create { + let workspace = self.focused_workspace_mut()?; + workspace.new_container_for_window(&window)?; + self.update_focused_workspace(false, false)?; + + if self.focused_workspace()?.containers().len() == 1 { + // If after adding this window the workspace only contains 1 window, it + // was previously empty, so give this window the focus + window.focus(self.mouse_follows_focus)?; + } + } + } + WindowManagerEvent::Destroy(_, _) => { + // the window may be on any workspace, not only the one in front + let location = self.known_window_ids.get(&window_id).cloned(); + + if let Some((m_idx, w_idx)) = location { + let focused = m_idx == self.focused_monitor_idx() + && Some(w_idx) == self.focused_workspace_idx().ok(); + + if let Some(workspace) = self + .monitors_mut() + .get_mut(m_idx) + .and_then(|m| m.workspaces_mut().get_mut(w_idx)) + { + let _ = workspace.remove_window(window_id); + } + + if focused { + let refocus = should_refocus_after_destroy(backend().foreground_window()); + self.update_focused_workspace(refocus, refocus)?; + } + } + + self.minimized_windows.remove(&window_id); + } + WindowManagerEvent::Minimize(_, _) => { + self.extract_minimized_window(window_id)?; + self.update_focused_workspace(false, false)?; + } + WindowManagerEvent::Restore(_, _) => match self.minimized_windows.remove(&window_id) { + None => {} + Some(window) => { + let workspace = self.focused_workspace_mut()?; + workspace.new_container_for_window(&window)?; + self.update_focused_workspace(false, false)?; + } + }, + } + + self.update_known_window_ids(); + + Ok(()) + } +} diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 5a213a9d..838e3230 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -190,6 +190,26 @@ impl Window { pub fn unminimize(self) -> eyre::Result<()> { backend().unminimize(self.id) } + + /// Whether the window is one komorebi should tile: a window that is still alive and that the + /// compositor considers a normal application window, as opposed to a dialog, a splash screen, + /// a utility window or a dock ([`WindowInfo::normal`](crate::backend::WindowInfo::normal)). + /// + /// A window the compositor has no record of is not managed. Windows that are minimized when + /// komorebi starts are not picked up either + /// ([`load_workspace_information`](crate::desktop::load_workspace_information)). + pub fn should_manage(&self) -> bool { + let Some(info) = self.info() else { + return false; + }; + + if !info.alive { + return false; + } + + // dialogs, splash screens, utility windows, docks and the like are not for tiling + info.normal + } } #[cfg(test)] @@ -289,6 +309,23 @@ mod tests { Ok(()) } + #[test] + fn only_a_normal_window_that_is_alive_is_managed() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.open_window(205, "foot", "foot", "a terminal"); + fake.open_window(206, "foot", "foot", "a dialog"); + fake.set_normal(206, false); + fake.open_window(207, "foot", "foot", "closed"); + fake.close_window_now(207); + + with_backend(fake, || { + assert!(Window::from(205).should_manage()); + assert!(!Window::from(206).should_manage()); + assert!(!Window::from(207).should_manage()); + assert!(!Window::from(208).should_manage()); + }); + } + #[test] fn a_window_serializes_with_what_the_backend_knows_about_it() -> eyre::Result<()> { let fake = fake_with(204); diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs new file mode 100644 index 00000000..8b9fc80f --- /dev/null +++ b/komorebi/src/window_manager.rs @@ -0,0 +1,315 @@ +//! [`WindowManager`], everything komorebi tiles, and the operations on it. +//! +//! The window manager keeps the monitors it loaded from the backend +//! ([`WindowManager::init`]), the windows the user minimized, and an index of which monitor and +//! workspace each window it manages is on. It changes when an event comes in +//! ([`WindowManager::process_event`]), and every change ends with the focused workspace tiled +//! again ([`WindowManager::update_focused_workspace`]). + +use crate::LibraryError; +use crate::container::Container; +use crate::core::Rect; +use crate::desktop; +use crate::monitor::Monitor; +use crate::ring::Ring; +use crate::window::Window; +use crate::workspace::Workspace; +use color_eyre::eyre; +use color_eyre::eyre::OptionExt; +use std::collections::HashMap; + +#[derive(Debug)] +pub struct WindowManager { + pub monitors: Ring, + pub mouse_follows_focus: bool, + pub work_area_offset: Option, + pub minimized_windows: HashMap, + /// Maps each known window id to the (monitor, workspace) index pair managing it + pub known_window_ids: HashMap, +} + +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 { + Ok(Self { + monitors: Ring::default(), + mouse_follows_focus: true, + work_area_offset: None, + minimized_windows: HashMap::new(), + known_window_ids: Default::default(), + }) + } + + /// Loads the monitors and the windows that are already open from the backend + /// ([`desktop`]) + #[tracing::instrument(skip(self))] + pub fn init(&mut self) -> Result<(), LibraryError> { + tracing::info!("initializing"); + desktop::load_monitor_information(self)?; + desktop::load_workspace_information(self)?; + // the windows that were open already are in containers now; an event about one of them + // (the first thing to happen may be that it closes) has to find it + self.update_known_window_ids(); + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn update_focused_workspace( + &mut self, + follow_focus: bool, + trigger_focus: bool, + ) -> eyre::Result<()> { + let offset = self.work_area_offset; + let mouse_follows_focus = self.mouse_follows_focus; + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .update_focused_workspace(offset)?; + + if follow_focus + && trigger_focus + && let Ok(window) = self.focused_window_mut() + { + window.focus(mouse_follows_focus)?; + } + + Ok(()) + } + + pub fn focused_workspace_idx(&self) -> eyre::Result { + Ok(self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx()) + } + + pub fn focused_workspace(&self) -> eyre::Result<&Workspace> { + self.focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace() + .ok_or_eyre("there is no workspace") + } + + pub fn focused_workspace_mut(&mut self) -> eyre::Result<&mut Workspace> { + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .focused_workspace_mut() + .ok_or_eyre("there is no workspace") + } + + pub fn focused_container(&self) -> eyre::Result<&Container> { + self.focused_workspace()? + .focused_container() + .ok_or_eyre("there is no container") + } + + pub fn focused_container_idx(&self) -> eyre::Result { + Ok(self.focused_workspace()?.focused_container_idx()) + } + + pub fn focused_container_mut(&mut self) -> eyre::Result<&mut Container> { + self.focused_workspace_mut()? + .focused_container_mut() + .ok_or_eyre("there is no container") + } + + pub fn focused_window(&self) -> eyre::Result<&Window> { + self.focused_container()? + .focused_window() + .ok_or_eyre("there is no window") + } + + fn focused_window_mut(&mut self) -> eyre::Result<&mut Window> { + self.focused_container_mut()? + .focused_window_mut() + .ok_or_eyre("there is no window") + } + + /// Takes a window the user minimized out of the focused workspace, and keeps it until it is + /// restored + pub fn extract_minimized_window(&mut self, window_id: u32) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + let window = workspace.remove_window(window_id)?; + self.minimized_windows.insert(window_id, window); + + Ok(()) + } + + /// Drop every window that no longer exists from the focused workspace and retile + pub fn reap_invalid_windows(&mut self) -> eyre::Result<()> { + let reaped_count = self.focused_workspace_mut()?.reap_invalid_windows()?; + + if reaped_count > 0 { + tracing::debug!("reaped {reaped_count} invalid window(s)"); + } + + self.update_focused_workspace(false, false) + } + + /// Tiles the focused workspace of every monitor + #[tracing::instrument(skip(self))] + pub fn retile_all(&mut self) -> eyre::Result<()> { + let offset = self.work_area_offset; + + for monitor in self.monitors_mut() { + let offset = if monitor.work_area_offset.is_some() { + monitor.work_area_offset + } else { + offset + }; + + let focused_workspace_idx = monitor.focused_workspace_idx(); + monitor.update_workspace_globals(focused_workspace_idx, offset); + + let workspace = monitor + .focused_workspace_mut() + .ok_or_eyre("there is no workspace")?; + + workspace.update()?; + } + + Ok(()) + } + + pub fn update_known_window_ids(&mut self) { + tracing::trace!("updating list of known window_ids"); + let mut known_window_ids = HashMap::new(); + for (m_idx, monitor) in self.monitors().iter().enumerate() { + for (w_idx, workspace) in monitor.workspaces().iter().enumerate() { + for container in workspace.containers() { + for window in container.windows() { + known_window_ids.insert(window.id, (m_idx, w_idx)); + } + } + } + } + + if self.known_window_ids != known_window_ids { + // Store new window_ids + self.known_window_ids = known_window_ids; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend::fake::FakeBackend; + use crate::backend::with_backend; + use std::sync::Arc; + + fn setup_window_manager() -> WindowManager { + // Create a new WindowManager instance + let wm = WindowManager::new(); + + // Window Manager should be created successfully + assert!(wm.is_ok()); + + wm.unwrap() + } + + #[test] + fn test_create_window_manager() { + let _wm = setup_window_manager(); + } + + fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect { + Rect { + left, + top, + right, + bottom, + } + } + + /// The fake's 1920x1080 monitor and a second one to its right, with the windows `ids` open on + /// the first and `id + 1` on the second for each of them + fn two_monitors(ids: &[u32]) -> Arc { + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.add_monitor( + 2, + "Virtual-1", + rect(1920, 0, 1920, 1080), + rect(1920, 0, 1920, 1080), + ); + + for id in ids { + fake.open_window(*id, "foot", "foot", "left"); + fake.open_window(id + 1, "foot", "foot", "right"); + fake.move_window_by_user(id + 1, rect(2000, 100, 800, 600)); + } + + fake + } + + #[test] + fn init_puts_each_open_window_on_the_monitor_it_is_on() -> eyre::Result<()> { + let fake = two_monitors(&[601]); + let mut wm = setup_window_manager(); + + with_backend(fake, || wm.init())?; + + assert_eq!(wm.monitors().len(), 2); + assert_eq!(wm.known_window_ids.get(&601), Some(&(0, 0))); + assert_eq!(wm.known_window_ids.get(&602), Some(&(1, 0))); + assert_eq!(wm.focused_workspace_idx()?, 0); + assert_eq!(wm.focused_container_idx()?, 0); + assert_eq!(wm.focused_container()?.windows().len(), 1); + assert_eq!(wm.focused_window()?.id, 601); + Ok(()) + } + + #[test] + fn retile_all_tiles_the_focused_workspace_of_every_monitor() -> eyre::Result<()> { + let fake = two_monitors(&[611]); + let mut wm = setup_window_manager(); + + with_backend(fake.clone(), || { + wm.init()?; + wm.retile_all() + })?; + + // the default workspace and container padding are 5 each, and the second monitor has no + // panel + assert_eq!(fake.rect_of(611), Some(rect(10, 10, 1900, 1030))); + assert_eq!(fake.rect_of(612), Some(rect(1930, 10, 1900, 1060))); + Ok(()) + } + + #[test] + fn reap_invalid_windows_drops_a_closed_window_and_retiles() -> eyre::Result<()> { + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.open_window(621, "foot", "foot", "stays"); + fake.open_window(622, "foot", "foot", "closes"); + let mut wm = setup_window_manager(); + + with_backend(fake.clone(), || { + wm.init()?; + fake.close_window_now(622); + wm.reap_invalid_windows() + })?; + + assert!(!wm.focused_workspace()?.contains_window(622)); + assert_eq!(fake.rect_of(621), Some(rect(10, 10, 1900, 1030))); + Ok(()) + } + + #[test] + fn a_minimized_window_is_kept_out_of_the_workspace() -> eyre::Result<()> { + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.open_window(631, "foot", "foot", "minimized"); + let mut wm = setup_window_manager(); + + with_backend(fake, || { + wm.init()?; + wm.extract_minimized_window(631) + })?; + + assert!(wm.focused_workspace()?.is_empty()); + assert_eq!(wm.minimized_windows.get(&631), Some(&Window::from(631))); + Ok(()) + } +} diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs new file mode 100644 index 00000000..2abd946f --- /dev/null +++ b/komorebi/src/window_manager_event.rs @@ -0,0 +1,101 @@ +//! [`WindowManagerEvent`], an event the compositor reported about a window, in the form the +//! window manager handles it +//! ([`WindowManager::process_event`](crate::window_manager::WindowManager::process_event)). +//! +//! An event is about one window and carries it, and the compositor signal it came from +//! ([`SystemNotification`]), which is only for logging. + +use crate::window::Window; +use serde::Deserialize; +use serde::Serialize; +use strum::Display; + +/// The compositor signal a [`WindowManagerEvent`] came from +#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, PartialEq, Eq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(tag = "type", content = "content")] +pub enum SystemNotification { + KWin(KWinNotification), +} + +/// The signals of the KWin script API an event comes from +#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, PartialEq, Eq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum KWinNotification { + /// `workspace.windowAdded` + WindowAdded, + /// `workspace.windowRemoved` + WindowRemoved, + /// `workspace.windowActivated` + WindowActivated, + /// `window.minimizedChanged` to true + WindowMinimized, + /// `window.minimizedChanged` to false + WindowRestored, +} + +/// Window events: each carries the window it is about. +#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(tag = "type", content = "content")] +pub enum WindowManagerEvent { + FocusChange(SystemNotification, Window), + Show(SystemNotification, Window), + Destroy(SystemNotification, Window), + Minimize(SystemNotification, Window), + Restore(SystemNotification, Window), +} + +impl WindowManagerEvent { + /// The window this event is about, if it is about one + pub fn window(&self) -> Option { + Some(match self { + WindowManagerEvent::FocusChange(_, window) + | WindowManagerEvent::Show(_, window) + | WindowManagerEvent::Destroy(_, window) + | WindowManagerEvent::Minimize(_, window) + | WindowManagerEvent::Restore(_, window) => *window, + }) + } + + pub fn window_id(&self) -> Option { + self.window().map(|w| w.id) + } + + pub fn process_id(&self) -> Option { + self.window().map(|w| w.process_id()) + } + + /// The notification that caused this event, for logging + pub fn notification(&self) -> String { + match self { + WindowManagerEvent::FocusChange(n, _) + | WindowManagerEvent::Show(n, _) + | WindowManagerEvent::Destroy(n, _) + | WindowManagerEvent::Minimize(n, _) + | WindowManagerEvent::Restore(n, _) => match n { + SystemNotification::KWin(k) => k.to_string(), + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_event_names_its_window_and_the_signal_it_came_from() { + let event = WindowManagerEvent::Minimize( + SystemNotification::KWin(KWinNotification::WindowMinimized), + Window::from(301), + ); + + assert_eq!(event.window(), Some(Window::from(301))); + assert_eq!(event.window_id(), Some(301)); + // the crate's unit tests get a permissive fake, which gives a window the pid id + 1000 + assert_eq!(event.process_id(), Some(1301)); + assert_eq!(event.notification(), "WindowMinimized"); + assert_eq!(event.to_string(), "Minimize"); + } +} diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 5b1e4826..6af1e023 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -153,6 +153,28 @@ impl Workspace { Ok(()) } + /// Remove every window that no longer exists + #[tracing::instrument(skip(self))] + pub fn reap_invalid_windows(&mut self) -> eyre::Result { + let mut invalid_window_ids = vec![]; + + for container in self.containers() { + for window in container.windows() { + if !window.is_valid() { + invalid_window_ids.push(window.id); + } + } + } + + for window_id in &invalid_window_ids { + let _ = self.remove_window(*window_id); + } + + tracing::debug!("reaping invalid windows {invalid_window_ids:?}"); + + Ok(invalid_window_ids.len()) + } + pub fn remove_window(&mut self, window_id: u32) -> eyre::Result { let container_idx = self .container_idx_for_window(window_id) diff --git a/komorebi/tests/no_backend.rs b/komorebi/tests/no_backend.rs new file mode 100644 index 00000000..438541e6 --- /dev/null +++ b/komorebi/tests/no_backend.rs @@ -0,0 +1,19 @@ +//! `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/wm_events.rs b/komorebi/tests/wm_events.rs new file mode 100644 index 00000000..c982346f --- /dev/null +++ b/komorebi/tests/wm_events.rs @@ -0,0 +1,242 @@ +//! The window manager driven end to end against an in-memory desktop: compositor events go in, +//! and what comes out is the geometry of the windows and the commands sent to the backend. +//! +//! Window ids are unique per test (10_001 and up), because tests in one binary share the process +//! and anything process-wide in it. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::Rect; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +fn removed(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Destroy( + SystemNotification::KWin(KWinNotification::WindowRemoved), + Window::from(id), + ) +} + +fn minimized(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Minimize( + SystemNotification::KWin(KWinNotification::WindowMinimized), + Window::from(id), + ) +} + +fn restored(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Restore( + SystemNotification::KWin(KWinNotification::WindowRestored), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel) +fn desktop() -> (Arc, WindowManager) { + desktop_on(FakeBackend::with_one_monitor()) +} + +fn desktop_on(fake: FakeBackend) -> (Arc, WindowManager) { + let fake = Arc::new(fake); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new().unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +fn open(fake: &FakeBackend, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); +} + +fn work_area() -> Rect { + Rect { + left: 0, + top: 0, + right: 1920, + bottom: 1050, + } +} + +fn inside(rect: &Rect, area: &Rect) -> bool { + rect.left >= area.left + && rect.top >= area.top + && rect.left + rect.right <= area.left + area.right + && rect.top + rect.bottom <= area.top + area.bottom +} + +fn overlap(a: &Rect, b: &Rect) -> bool { + a.left < b.left + b.right + && b.left < a.left + a.right + && a.top < b.top + b.bottom + && b.top < a.top + a.bottom +} + +#[test] +fn a_new_window_is_tiled_into_the_work_area() { + let (fake, mut wm) = desktop(); + open(&fake, 10_001); + + with_backend(fake.clone(), || wm.process_event(added(10_001))).unwrap(); + + let rect = fake.rect_of(10_001).unwrap(); + assert!( + inside(&rect, &work_area()), + "{rect:?} is outside the work area" + ); + assert!( + rect.right > 1800 && rect.bottom > 1000, + "{rect:?} does not fill the work area" + ); + assert!(wm.focused_workspace().unwrap().contains_window(10_001)); +} + +#[test] +fn two_windows_split_the_work_area_without_overlapping() { + let (fake, mut wm) = desktop(); + open(&fake, 10_011); + open(&fake, 10_012); + + with_backend(fake.clone(), || { + wm.process_event(added(10_011))?; + wm.process_event(added(10_012)) + }) + .unwrap(); + + let (a, b) = (fake.rect_of(10_011).unwrap(), fake.rect_of(10_012).unwrap()); + assert!(inside(&a, &work_area()) && inside(&b, &work_area())); + assert!(!overlap(&a, &b), "{a:?} overlaps {b:?}"); + assert!( + a.right < 1000 && b.right < 1000, + "neither should be full width: {a:?} {b:?}" + ); +} + +#[test] +fn closing_a_window_gives_its_space_to_the_other() { + let (fake, mut wm) = desktop(); + open(&fake, 10_021); + open(&fake, 10_022); + + with_backend(fake.clone(), || { + wm.process_event(added(10_021))?; + wm.process_event(added(10_022))?; + fake.close_window_now(10_022); + wm.process_event(removed(10_022)) + }) + .unwrap(); + + assert!(!wm.focused_workspace().unwrap().contains_window(10_022)); + let rect = fake.rect_of(10_021).unwrap(); + assert!( + rect.right > 1800, + "the survivor should fill the work area: {rect:?}" + ); +} + +#[test] +fn dialogs_and_other_non_normal_windows_are_left_alone() { + let (fake, mut wm) = desktop(); + open(&fake, 10_041); + fake.set_normal(10_041, false); + fake.clear_commands(); + + with_backend(fake.clone(), || wm.process_event(added(10_041))).unwrap(); + + assert!(!wm.focused_workspace().unwrap().contains_window(10_041)); + assert!( + fake.commands().is_empty(), + "nothing should have been asked of it" + ); +} + +#[test] +fn a_minimize_by_the_user_unmanages_the_window_until_it_is_restored() { + let (fake, mut wm) = desktop(); + open(&fake, 10_071); + open(&fake, 10_072); + + with_backend(fake.clone(), || { + wm.process_event(added(10_071))?; + wm.process_event(added(10_072))?; + wm.process_event(minimized(10_072)) + }) + .unwrap(); + + assert!(!wm.focused_workspace().unwrap().contains_window(10_072)); + assert!(wm.minimized_windows.contains_key(&10_072)); + assert!(fake.rect_of(10_071).unwrap().right > 1800); + + with_backend(fake.clone(), || wm.process_event(restored(10_072))).unwrap(); + + assert!(wm.focused_workspace().unwrap().contains_window(10_072)); + assert!(!wm.minimized_windows.contains_key(&10_072)); +} + +#[test] +fn the_window_given_the_focus_is_in_the_focused_container() { + let (fake, mut wm) = desktop(); + open(&fake, 10_601); + open(&fake, 10_602); + + with_backend(fake.clone(), || { + wm.process_event(added(10_601))?; + wm.process_event(added(10_602))?; + // the user clicks the first window + fake.set_foreground(Some(10_601)); + wm.process_event(activated(10_601)) + }) + .unwrap(); + + assert_eq!(wm.focused_container_idx().unwrap(), 0); + assert_eq!(wm.focused_window().unwrap().id, 10_601); +} + +#[test] +fn a_window_that_was_open_before_komorebi_started_is_removed_when_it_closes() { + // the first event komorebi sees may be the close of a window it picked up at startup + let fake = FakeBackend::with_one_monitor(); + fake.open_window(10_301, "foot", "foot", "terminal 10301"); + fake.open_window(10_302, "foot", "foot", "terminal 10302"); + let (fake, mut wm) = desktop_on(fake); + + with_backend(fake.clone(), || { + fake.close_window_now(10_301); + wm.process_event(removed(10_301)) + }) + .unwrap(); + + let remaining: Vec = wm + .focused_workspace() + .unwrap() + .containers() + .iter() + .flat_map(|c| c.windows().iter().map(|w| w.id)) + .collect(); + assert_eq!( + remaining, + [10_302], + "a closed window is still in a container" + ); +} From 15ec3c127490031e5872be09721e6510e6af72cd Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 12:38:17 -0700 Subject: [PATCH 011/255] feat(kwin): read the desktop through a script in KWin KWin has no protocol that lets another process read or set the geometry of a window, but its scripting API has both, and a signal for every change the window manager follows. So the KWin backend is in two parts: bridge.js, a script the daemon loads into KWin, which reports what KWin sees and holds no window manager logic, and a D-Bus service in the daemon, org.komorebi.Bridge, which the script calls with every event as a JSON string. Every decision about what an event means is made by the table in kwin::state, which is pure and is unit-tested with the JSON the script sends: which windows may be managed, the ids komorebi gives KWin's windows, and the Show, Destroy, FocusChange, Minimize and Restore events of the window manager. Events reach the window manager in the order KWin raised them: the Event interface handles its calls inline (zbus reordered them otherwise), and one channel and one thread, window_manager_event_listener and listen_for_events, carry them on. Commands go to the script as the answer to a Poll call that the script always has open and the daemon holds until it has something to send: in the spikes this was as fast as any other channel, and it makes one call every 10 seconds when nothing happens. Here the only command is the cursor query. Every command of the Backend trait is refused with "the KWin backend only reads the desktop", so the daemon follows KWin and moves nothing. The bridge is JavaScript that KWin runs as it is, and it gets types and tests without a JavaScript build chain. tsc checks it as strict TypeScript through JSDoc types of every message, against kwin-api.d.ts, a declaration of the part of KWin's scripting API it uses, in which every property is read-only and callDBus takes one string. bridge.test.js runs it under node --test against a fake KWin in a node:vm context. The messages of a session are JSON fixtures that both sides' tests read: the bridge's tests check that it sends those events, and the table's and the backend's tests read the same events and commands, so a message cannot change on one side alone. just check-js and the flake's komorebi-bridge-js check run both, with nodejs and typescript from nixpkgs; there is no package.json. The daemon now connects to KWin by default, and --fake-backend is hidden. The VM suite vm-kwin-events starts it against a headless KWin and checks, from its debug log, that the script loads and reports what was open, that KWin's signals arrive as events and in order, and that stopping the daemon unloads the script. docs/dev/PLATFORM.md starts with what komorebi needs from Plasma. zbus 5's zvariant, zbus_names and zvariant_derive are flagged unmaintained, since their code moved into zbus 6; deny.toml ignores the three advisories. --- CONTRIBUTING.md | 20 +- Cargo.lock | 469 ++++++++++ Cargo.toml | 3 + README.md | 49 +- deny.toml | 12 +- docs/dev/ARCHITECTURE.md | 131 ++- docs/dev/DESIGN.md | 75 ++ docs/dev/PLATFORM.md | 200 +++++ docs/dev/vm-tests.md | 19 +- flake.nix | 40 +- justfile | 8 +- komorebi/Cargo.toml | 10 +- komorebi/src/desktop.rs | 9 +- komorebi/src/kwin/bridge.js | 319 +++++++ komorebi/src/kwin/bridge.test.js | 389 ++++++++ komorebi/src/kwin/fixtures/commands.json | 3 + komorebi/src/kwin/fixtures/events.json | 46 + komorebi/src/kwin/kwin-api.d.ts | 125 +++ komorebi/src/kwin/mod.rs | 549 ++++++++++++ komorebi/src/kwin/state.rs | 833 ++++++++++++++++++ komorebi/src/kwin/tsconfig.json | 22 + komorebi/src/lib.rs | 24 +- komorebi/src/main.rs | 70 +- komorebi/src/process_event.rs | 34 + komorebi/src/window_manager.rs | 16 +- komorebi/src/window_manager_event.rs | 2 +- komorebi/src/window_manager_event_listener.rs | 35 + komorebi/tests/no_backend.rs | 19 - komorebi/tests/no_kwin.rs | 43 + komorebi/tests/wm_events.rs | 3 +- nix/tests/vm/default.nix | 10 +- nix/tests/vm/lib/komorebi_vm/__init__.py | 8 +- nix/tests/vm/lib/komorebi_vm/daemon.py | 38 + nix/tests/vm/lib/komorebi_vm/kde.py | 44 + nix/tests/vm/lib/tests/test_daemon.py | 28 + nix/tests/vm/lib/tests/test_kde.py | 51 ++ nix/tests/vm/nodes/headless.nix | 30 +- nix/tests/vm/suites/kwin-events/default.nix | 5 + nix/tests/vm/suites/kwin-events/test.py | 119 +++ 39 files changed, 3815 insertions(+), 95 deletions(-) create mode 100644 docs/dev/PLATFORM.md create mode 100644 komorebi/src/kwin/bridge.js create mode 100644 komorebi/src/kwin/bridge.test.js create mode 100644 komorebi/src/kwin/fixtures/commands.json create mode 100644 komorebi/src/kwin/fixtures/events.json create mode 100644 komorebi/src/kwin/kwin-api.d.ts create mode 100644 komorebi/src/kwin/mod.rs create mode 100644 komorebi/src/kwin/state.rs create mode 100644 komorebi/src/kwin/tsconfig.json create mode 100644 komorebi/src/window_manager_event_listener.rs delete mode 100644 komorebi/tests/no_backend.rs create mode 100644 komorebi/tests/no_kwin.rs create mode 100644 nix/tests/vm/lib/komorebi_vm/daemon.py create mode 100644 nix/tests/vm/lib/tests/test_daemon.py create mode 100644 nix/tests/vm/suites/kwin-events/default.nix create mode 100644 nix/tests/vm/suites/kwin-events/test.py 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() From b463191d00828f5422272a438e4054001404a7ae Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 13:05:00 -0700 Subject: [PATCH 012/255] feat(kwin): move and focus windows through a held call With the commands of the Backend trait carried out, the daemon tiles a real KWin. A command looks up the UUID KWin knows the window by, is queued as JSON for the bridge, and returns; the held Poll call is answered with the queue, one millisecond after the first command, so that a retile reaches KWin as one batch. The bridge sets the frame, activates, raises, minimizes, restores or closes the window, and reports what it could not do. set_rect records the frame it asked for in the table, so the window manager sees it at once, and the geometry event that follows says what the client made of it. A KWin script cannot move the pointer, so the pointer follows the focus through KWin's own "Move Mouse to Focus" action, invoked over kglobalaccel once KWin reports the window active. The commands are typed in bridge.js, and the declarations of KWin's API let the bridge set a window's frame, its minimized state and the active window, raise and close it, and nothing else. The session the tests of both sides share grows a second batch: the backend's tests check that set_rect, focus, raise, minimize, unminimize and close send it, and the bridge's tests answer the bridge with it and check what KWin is asked to do, down to the command for a window that has closed, which comes back as failed. The bridge's tests also cover findWindow's fallback to KWin's list, a frame set as a plain object, and a command KWin throws on. Three VM suites check it against a real KWin. vm-core-e2e (from the spike's m2-e2e, the sections that need no komorebic) compares what the daemon asked for, read from its debug log, with what KWin has, read with kdotool: three windows inside the screen, not overlapping, sharing it, the same focused window on both sides, and the same again after a minimize, a restore and a close. vm-client-geometry (slow) has eight real clients answer the frames komorebi asks for: Qt programs and xterm take them exactly, foot sizes itself to whole cells, GTK 4 programs and Firefox keep to their minimum sizes. vm-latency (slow) times retiles from a recording of the session bus: on HVF, from the daemon's answer to the last frame KWin reports, p50 17.3 ms, p95 27.7 ms. vm-kwin-events no longer checks that nothing moves. The VM library gives session commands the test user's home and data directories rather than root's, which a GTK client was refused. The bridge's second request for a position after a resize, which matters for windows off the screen, comes with the scrolling layout. --- README.md | 7 +- docs/dev/ARCHITECTURE.md | 37 +++-- docs/dev/DESIGN.md | 10 ++ docs/dev/PLATFORM.md | 51 +++++- docs/dev/vm-tests.md | 15 +- komorebi/src/kwin/bridge.js | 58 ++++++- komorebi/src/kwin/bridge.test.js | 79 +++++++++- komorebi/src/kwin/fixtures/commands.json | 23 ++- komorebi/src/kwin/fixtures/events.json | 19 ++- komorebi/src/kwin/kwin-api.d.ts | 10 +- komorebi/src/kwin/mod.rs | 146 ++++++++++++++---- komorebi/src/kwin/state.rs | 53 ++++++- nix/tests/vm/default.nix | 3 +- nix/tests/vm/lib/komorebi_vm/__init__.py | 8 +- nix/tests/vm/lib/komorebi_vm/daemon.py | 29 +++- nix/tests/vm/lib/komorebi_vm/kde.py | 50 +++++- nix/tests/vm/lib/komorebi_vm/latency.py | 133 ++++++++++++++++ nix/tests/vm/lib/tests/test_daemon.py | 26 +++- nix/tests/vm/lib/tests/test_kde.py | 57 +++++++ nix/tests/vm/lib/tests/test_latency.py | 91 +++++++++++ nix/tests/vm/nodes/headless.nix | 2 + .../vm/suites/client-geometry/default.nix | 23 +++ nix/tests/vm/suites/client-geometry/test.py | 101 ++++++++++++ nix/tests/vm/suites/core-e2e/default.nix | 5 + nix/tests/vm/suites/core-e2e/test.py | 142 +++++++++++++++++ nix/tests/vm/suites/kwin-events/test.py | 14 +- nix/tests/vm/suites/latency/default.nix | 10 ++ nix/tests/vm/suites/latency/test.py | 83 ++++++++++ 28 files changed, 1197 insertions(+), 88 deletions(-) create mode 100644 nix/tests/vm/lib/komorebi_vm/latency.py create mode 100644 nix/tests/vm/lib/tests/test_latency.py create mode 100644 nix/tests/vm/suites/client-geometry/default.nix create mode 100644 nix/tests/vm/suites/client-geometry/test.py create mode 100644 nix/tests/vm/suites/core-e2e/default.nix create mode 100644 nix/tests/vm/suites/core-e2e/test.py create mode 100644 nix/tests/vm/suites/latency/default.nix create mode 100644 nix/tests/vm/suites/latency/test.py diff --git a/README.md b/README.md index 7f5cc72b..b4cc9fe0 100644 --- a/README.md +++ b/README.md @@ -16,10 +16,9 @@ cargo run --bin komorebi --locked -- --fake-backend ``` 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; +monitors and the windows that are open, tiles them, and tiles the windows again +whenever one opens, closes, takes the focus, is minimized or comes back, until +it is stopped with Ctrl-C. 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 diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index b81921ac..d82a0aac 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -127,9 +127,17 @@ The path of an event: a KWin signal, the bridge's handler, `Event(json)` on the 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. +A command goes the other way. The backend looks up the UUID KWin knows the window by, +queues a JSON command for the bridge, and returns. The held `Poll` call is answered with the +queue, as one batch: the daemon waits a millisecond after the first command for the rest, so +that a retile of every window of a workspace reaches KWin at once. The bridge carries the +commands out in order and reports the ones it could not carry out (a window that closed in +the meantime) as a `failed` event, which is logged. `set_rect` also records the frame it +asked for in the table, so that the window manager sees it straight away; the `geometry` +event that follows says what the client made of it. The pointer cannot be moved from a +script: when it follows the focus, the backend invokes KWin's "Move Mouse to Focus" shortcut, +which centers it on the window KWin has focused. 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 @@ -184,7 +192,8 @@ the fake. The window manager is its only caller, through [`backend`]. The contra it. The frame a window ends up with is what `window_rect` says afterwards, because a client may refuse a size. - A command about a window that does not exist, or is no longer alive, is an error. It - never panics. + never panics. The KWin backend knows a closed window for a minute after it closed, and + sends its commands to the bridge, which reports that it could not carry them out. - `shutdown`, `is_window`, `window_rect` and `monitor_from_point` have defaults, written in terms of the queries. An implementor should not need to override them, except `shutdown` when it created something in the compositor that has to be given up. @@ -197,7 +206,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A backend can be shared between threads | type system: `Backend: Send + Sync + 'static` | `compile_fail,E0277` on [`Backend`] | none | | The window manager asks for a backend that was never installed | runtime error: [`backend`] panics, naming [`set_backend`] and [`with_backend`] | `# Panics` on [`backend`] | none | | A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none | -| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error`, against the fake only | none | +| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none | | 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 | @@ -207,10 +216,12 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | 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 | +| Every window is where komorebi asked for it, within the size its client keeps to | VM test | `vm-core-e2e`, `vm-client-geometry` | a client may refuse a size: the frame is what `window_rect` says | +| A retile reaches KWin as one batch | framework path: the answer to `Poll` waits a millisecond after the first command for the others | `vm-latency` | none | +| The window manager sees a frame it asked for at once | framework path: the KWin backend's `set_rect` records it in the table before KWin answers | `a_requested_rect_is_visible_at_once_and_replaced_by_the_real_one` | 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 | +| What the backend sends is what the bridge carries out | tests: the commands of [`fixtures`] are what the backend's tests check it sends and what the bridge's tests answer it with, checking what KWin is asked to do for each | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a command for a window KWin no longer has is given back, and the rest are carried out` | none | | Everything the bridge sends over D-Bus is one string | type checker: [`kwin-api.d.ts`] gives `callDBus` one string argument | `tsc`, `every call goes to the daemon's names, with one JSON string` | none | | The bridge uses nothing a KWin script does not have | type checker: the library is ECMAScript 2016 alone, and KWin's API is what [`kwin-api.d.ts`] declares | `tsc` | a declaration KWin does not match: the VM tests run the bridge in KWin | | Queries never block on the compositor | convention only | none | the KWin backend's `cursor_pos` waits up to 250 ms | @@ -245,10 +256,12 @@ 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. The KWin backend refuses, and the window stays where - KWin put it. + what `window_rect` says afterwards. The KWin backend queues a `geo` command for the + bridge, the bridge sets the window's frame, the client draws at the size it accepts, and + KWin reports the frame it ended up with as a `geometry` event, which updates the table. 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. + `focus`, and the pointer follows it (on KWin, through its "Move Mouse to Focus" + shortcut). 8. The index is rebuilt again, so the next event finds the window. ## Where to look in the code @@ -273,7 +286,9 @@ A window is shown, and ends up on a tile: [`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. + events of a real KWin, through the daemon. +- [`nix/tests/vm/suites/core-e2e`](../../nix/tests/vm/suites/core-e2e/test.py): the daemon + tiling a real KWin, checked against what KWin has. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager driven end to end against the fake. diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index b99fe405..eb01257c 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -133,3 +133,13 @@ number as a 32-bit integer, and a call whose arguments do not match the method's 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. + +## Why does the pointer follow the focus through a KWin shortcut? + +Because a KWin script cannot move the pointer, and KWin can. Its "Move Mouse to Focus" action +puts the pointer in the middle of the window that has the focus, and it can be invoked over +D-Bus, through `kglobalaccel`: in the spikes it moved the pointer from the middle of the screen +to the middle of the focused window, for two different windows. The backend asks for it once +KWin reports the window it focused as active, so the action finds the right one. The cost is +that the pointer can go to the middle of the focused window and nowhere else, which is what +komorebi asks for. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index c3dbbd69..12fbcb6c 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -68,9 +68,11 @@ the windows and outputs it finds, and from then on every window that opens, clos 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. +Every command of the window manager (move and resize, focus, raise, minimize, bring back or +close a window) is queued for the bridge, which gets the queue as the answer to its held call +and carries the commands out in KWin, in order. The script API cannot move the pointer, so +when the pointer follows the focus komorebi invokes KWin's own "Move Mouse to Focus" shortcut, +which puts the pointer in the middle of the window KWin has focused. #### What komorebi leaves behind @@ -84,7 +86,9 @@ it or the session ends. `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. +pixels can be tested against it. Started with `--no-global-shortcuts`, as the VM tests start +it, KWin does not own `org.kde.kglobalaccel`, and the pointer does not follow the focus; the +daemon logs that at debug level and carries on. ### No KWin @@ -118,6 +122,7 @@ What komorebi calls: |---|---|---|---|---| | `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 | +| `org.kde.kglobalaccel` | `/component/kwin` | `org.kde.kglobalaccel.Component` | `invokeShortcut(s)`, with `MoveMouseToFocus` | when the pointer follows the focus | ## Files and directories @@ -184,6 +189,44 @@ TypeScript are needed only for those checks: in the session the bridge needs KWi logging category is enabled (`QT_LOGGING_RULES="kwin_scripting.debug=true"`, as the VM tests do). +## How clients answer a frame + +KWin applies a frame komorebi asks for at once, and then the client decides what size it +draws at; the frame KWin reports afterwards (a `geometry` event) is the one the client +chose. Measured at time of writing (2026-10-27) in a headless KWin with eight clients, by the +VM test `vm-client-geometry`, and by the spikes before it with more sizes and at a scale of +1.25: + +| Client | Answer | In `vm-client-geometry` | +|---|---|---| +| Konsole, Kate, Dolphin (Qt, KDE) | exactly the frame asked for, also below the minimum size they report (spikes) | Kate asked for 948x527, has 948x527 | +| `xterm` on XWayland | exactly the frame asked for | asked for 229x259, has 229x259 | +| `foot` | sizes itself down to whole cells of its font | asked for 1905x2140, has 1902x2129 | +| GTK 4 Text Editor | exactly the frame asked for, down to its minimum of 360x200 | asked for 469x528, has 469x528 | +| GTK 4 Calculator | never below its minimum of 360x616 | asked for 469x259, has 469x616 | +| Firefox | never below its minimum width of 500 and height of 120 | asked for 230x259, has 500x259 | + +Every client keeps the position it is asked for, also one partly off the screen. A fractional +scale of 1.25 gives the same answers as 1.0: every whole logical frame comes back as it was +asked for. komorebi does not ask again when a client keeps to a size of its own: the window +manager reads the frame the window has from the table, and a window larger than its tile +covers part of its neighbor's. + +## How long a retile takes + +Measured by the VM test `vm-latency` at time of writing (2026-10-27), in a headless KWin 6.8.1 +under HVF on an Apple silicon Mac, with ten `foot` windows on a 3840x2160 output: twenty +retiles (a window minimized and brought back, ten times over), each of which moved 5.5 windows +on average. From the daemon's answer to `Poll` to the last frame KWin reported for the windows +the batch moved, the client's answer included: + +| p50 | p95 | max | +|---|---|---| +| 17.3 ms | 27.7 ms | 31.4 ms | + +The spikes measured the channel alone, with twenty windows in each batch, at 16, 19 and 20 ms +([DESIGN.md](DESIGN.md#why-do-commands-go-to-the-bridge-as-the-answer-to-a-held-call)). + ## Rendering in virtual machines and over RDP At time of writing (2026-10-27): diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index df220bad..cce66e77 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -36,7 +36,8 @@ JSON, which is what CI reads. A suite has two files: - `default.nix` sets `tier` (`"fast"` or `"slow"`), `kind` (the node it runs on) - and `timeoutMinutes`. + and `timeoutMinutes`, and may set `node`, a NixOS module that adds to the node + for this suite alone (more memory, the clients it starts). - `test.py` is the test, a Python script for the NixOS test driver. It is prefixed with `SCALE = `, how many times slower than KVM the machine is. @@ -96,14 +97,20 @@ the run. 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. + user would, and `wid_by_class` finds a window by its app id or X11 class. + `Kde.headless(..., xwayland=True)` gives the session XWayland, for X11 + clients. - `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. + in order, `daemon.window_ids(log)` maps a window's title to the daemon's id + for it, and `daemon.requests(log)` returns the frame the daemon last asked KWin + for, for each window. +- `monitor_bridge(path)` records the bridge's traffic on the session bus with + `dbus-monitor`, and `latency.rounds` times each batch of commands in it, from + the daemon's answer to the last frame KWin reports for the windows it moved. Poll for what the test needs with `wait_for`. A fixed sleep is too long on KVM and too short on TCG. diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index 4d88e548..37a64286 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -62,11 +62,19 @@ */ /** - * 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. + * What the daemon sends: the answer to `Poll` is a list of batches, each a list of commands. A + * window command names the window by its `id`: `geo` sets its frame, `min` minimizes it (`v`) or + * brings it back, and `activate`, `raise` and `close` do what they say. A cursor query is + * numbered by `token` so that its answer can be matched. * * @typedef {{ op: "cursor", token: number }} CursorQuery - * @typedef {CursorQuery} Command + * @typedef {{ op: "geo", id: string, x: number, y: number, w: number, h: number }} SetFrame + * @typedef {{ op: "min", id: string, v: boolean }} SetMinimized + * @typedef {{ op: "activate", id: string }} Activate + * @typedef {{ op: "raise", id: string }} Raise + * @typedef {{ op: "close", id: string }} Close + * @typedef {SetFrame | SetMinimized | Activate | Raise | Close} WindowCommand + * @typedef {CursorQuery | WindowCommand} Command * @typedef {{ batch: number, cmds: Command[] }} Batch */ @@ -185,6 +193,23 @@ function cursor() { return { x: Math.round(p.x), y: Math.round(p.y) }; } +/** + * @param {string} id + * @returns {KWinWindow | null} + */ +function findWindow(id) { + if (known[id]) { + return known[id]; + } + var l = workspace.windowList(); + for (var i = 0; i < l.length; i++) { + if (wid(l[i]) === id) { + return l[i]; + } + } + return null; +} + // ---- hooks --------------------------------------------------------------------------------- /** @@ -259,7 +284,32 @@ function applyOne(c) { emit("cursor", { token: c.token, x: p.x, y: p.y }); return true; } - return false; + + var w = findWindow(c.id); + if (!w) { + return false; + } + switch (c.op) { + case "geo": + // a plain object converts to QRectF; there is no `Qt` global in kwin scripts + w.frameGeometry = { x: c.x, y: c.y, width: c.w, height: c.h }; + break; + case "min": + w.minimized = !!c.v; + break; + case "activate": + workspace.activeWindow = w; + break; + case "raise": + workspace.raiseWindow(w); + break; + case "close": + w.closeWindow(); + break; + default: + return false; + } + return true; } /** @param {Batch} batch */ diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index fbec1d93..8bbe61b8 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -57,7 +57,8 @@ function geometry(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. +// Setting `minimized` or `frameGeometry` raises the signal KWin raises, and `closeWindow` closes it +// once it is in a KWin. function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100), ...rest }) { const w = { internalId: { toString: () => id }, @@ -76,6 +77,7 @@ function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100 desktops: [], frameGeometryChanged: new Signal(), minimizedChanged: new Signal(), + closeWindow: () => assert.fail("a window that is in no KWin was closed"), ...rest, }; let state = { minimized, frameGeometry }; @@ -115,9 +117,10 @@ const DP1 = { function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y: 0 } } = {}) { const calls = []; const printed = []; + const raised = []; const timers = []; const clock = { now: 1000 }; - const open = windows.slice(); + const open = []; let activeWindow = active; const workspace = { @@ -130,6 +133,7 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y return output.placementArea; }, currentDesktopForScreen: (output) => ({ id: `desktop of ${output.name}` }), + raiseWindow: (w) => raised.push(w), windowAdded: new Signal(), windowRemoved: new Signal(), windowActivated: new Signal(), @@ -155,6 +159,13 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y } } + // a window KWin has: it can close + function adopt(w) { + open.push(w); + w.closeWindow = () => k.close(w); + } + windows.forEach(adopt); + const context = vm.createContext({ workspace, KWin: { PlacementArea: 7 }, @@ -173,6 +184,7 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y workspace, calls, printed, + raised, timers, clock, // what the bridge has sent with `Event`, oldest first @@ -182,7 +194,7 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y 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); + adopt(w); if (focus) { workspace.activeWindow = w; } @@ -245,14 +257,24 @@ test("what the bridge sends for a session is what the daemon's tests read", () = // 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; + const [cursorQuery, windowCommands] = 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); + // the editor is tiled, focused, raised, minimized and brought back, the dialog closed, and the + // terminal, which has closed, is asked for a frame + assert.equal(k.events().at(-1).seq, windowCommands.after_seq); + k.answer([windowCommands.batch]); + assert.deepStrictEqual(k.events(), events); + assert.deepStrictEqual(editor.frameGeometry, geometry(0, 0, 960, 1050)); + assert.equal(k.workspace.activeWindow, editor); + assert.deepStrictEqual(k.raised, [editor]); + assert.equal(editor.minimized, false); + assert.deepStrictEqual(k.workspace.windowList(), [editor]); }); test("a window KWin activates before announcing it is announced first, and once", () => { @@ -387,3 +409,52 @@ test("a command the bridge does not know is given back as failed", () => { { type: "failed", batch: 4, cmds: [{ op: "teleport" }], seq: 3 }, ]); }); + +test("a frame is set as a plain object, and the frame KWin gives comes back as an event", () => { + const w = window({ id: "{w}", frameGeometry: geometry(0, 0, 100, 100) }); + const k = kwin({ windows: [w] }); + + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: 10, y: 20, w: 300, h: 400 }] }]); + + assert.deepStrictEqual(w.frameGeometry, geometry(10, 20, 300, 400)); + assert.deepStrictEqual(k.events().slice(1), [ + { type: "geometry", id: "{w}", geo: { x: 10, y: 20, w: 300, h: 400 }, seq: 2 }, + ]); +}); + +test("a window the bridge has not seen is found in KWin's list", () => { + const k = kwin(); + const unseen = window({ id: "{unseen}" }); + // in KWin's list, without a windowAdded + k.workspace.windowList = () => [unseen]; + + k.answer([{ batch: 1, cmds: [{ op: "min", id: "{unseen}", v: true }] }]); + + assert.equal(unseen.minimized, true); + assert.equal(k.events().length, 1, "and nothing failed"); +}); + +test("a command for a window KWin no longer has is given back, and the rest are carried out", () => { + const w = window({ id: "{w}" }); + const k = kwin({ windows: [w] }); + const gone = { op: "activate", id: "{gone}" }; + + k.answer([{ batch: 3, cmds: [gone, { op: "raise", id: "{w}" }] }]); + + assert.deepStrictEqual(k.raised, [w]); + assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 3, cmds: [gone], seq: 2 }); +}); + +test("a command KWin throws on is printed and given back as failed", () => { + const w = window({ id: "{w}" }); + const k = kwin({ windows: [w] }); + w.closeWindow = () => { + throw new Error("the window is being destroyed"); + }; + const close = { op: "close", id: "{w}" }; + + k.answer([{ batch: 5, cmds: [close] }]); + + assert.match(k.printed[0], /^komorebi bridge: Error: the window is being destroyed in /); + assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 5, cmds: [close], seq: 2 }); +}); diff --git a/komorebi/src/kwin/fixtures/commands.json b/komorebi/src/kwin/fixtures/commands.json index b32c21cd..62bafbd0 100644 --- a/komorebi/src/kwin/fixtures/commands.json +++ b/komorebi/src/kwin/fixtures/commands.json @@ -1,3 +1,24 @@ [ - {"after_seq": 7, "batch": {"batch": 1, "cmds": [{"op": "cursor", "token": 1}]}} + {"after_seq": 7, "batch": {"batch": 1, "cmds": [{"op": "cursor", "token": 1}]}}, + { + "after_seq": 9, + "batch": { + "batch": 2, + "cmds": [ + { + "op": "geo", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "x": 0, "y": 0, "w": 960, "h": 1050 + }, + {"op": "activate", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}"}, + {"op": "raise", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}"}, + {"op": "min", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": true}, + {"op": "min", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": false}, + {"op": "close", "id": "{c4b8a2f0-0000-4000-8000-00000000000c}"}, + { + "op": "geo", "id": "{7f3d9e21-0000-4000-8000-00000000000b}", + "x": 960, "y": 0, "w": 960, "h": 1050 + } + ] + } + } ] diff --git a/komorebi/src/kwin/fixtures/events.json b/komorebi/src/kwin/fixtures/events.json index 411c0b76..994abb5b 100644 --- a/komorebi/src/kwin/fixtures/events.json +++ b/komorebi/src/kwin/fixtures/events.json @@ -42,5 +42,22 @@ "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}"} + {"type": "removed", "seq": 9, "id": "{7f3d9e21-0000-4000-8000-00000000000b}"}, + { + "type": "geometry", "seq": 10, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "geo": {"x": 0, "y": 0, "w": 960, "h": 1050} + }, + {"type": "activated", "seq": 11, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}"}, + {"type": "minimized", "seq": 12, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": true}, + {"type": "minimized", "seq": 13, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": false}, + {"type": "removed", "seq": 14, "id": "{c4b8a2f0-0000-4000-8000-00000000000c}"}, + { + "type": "failed", "seq": 15, "batch": 2, + "cmds": [ + { + "op": "geo", "id": "{7f3d9e21-0000-4000-8000-00000000000b}", "x": 960, "y": 0, + "w": 960, "h": 1050 + } + ] + } ] diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts index d177a4c6..85c01a50 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -71,25 +71,29 @@ interface KWinWindow { readonly skipTaskbar: boolean; readonly skipPager: boolean; readonly skipSwitcher: boolean; - readonly minimized: boolean; + minimized: boolean; readonly fullScreen: boolean; /** `KWin::MaximizeMode`: 0 restored, 1 vertically, 2 horizontally, 3 both ways. */ readonly maximizeMode: number; - readonly frameGeometry: QRectF; + /** Set to a plain `{x, y, width, height}`: a script has no `Qt` global to make a `QRectF`. */ + frameGeometry: QRectF; readonly minSize: QSizeF; readonly desktops: VirtualDesktop[]; readonly frameGeometryChanged: Signal<[oldGeometry: QRectF]>; readonly minimizedChanged: Signal; + closeWindow(): void; } /** The global `workspace` (`KWin::ScriptingWorkspace`). */ interface Workspace { readonly screens: Output[]; - readonly activeWindow: KWinWindow | null; + /** Setting it activates the window. */ + activeWindow: KWinWindow | null; readonly cursorPos: QPointF; windowList(): KWinWindow[]; clientArea(option: number, output: Output, desktop: VirtualDesktop): QRectF; currentDesktopForScreen(output: Output): VirtualDesktop; + raiseWindow(window: KWinWindow): void; readonly windowAdded: Signal<[window: KWinWindow]>; readonly windowRemoved: Signal<[window: KWinWindow]>; /** `null` when no window has the focus. */ diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index 9a26b732..24125ff7 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -23,9 +23,9 @@ //! 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. +//! The backend answers every query from the [`state::Table`], turns what KWin reports into the +//! window events of [`crate::window_manager_event`], and queues every command of [`Backend`] for +//! the script, which carries it out in KWin. //! //! `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. @@ -201,14 +201,23 @@ impl Poll { } } -/// The desktop of a running KWin, read through the script komorebi loads into it. +/// The desktop of a running KWin, read and changed 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. +/// A command ([`Backend::set_rect`], [`Backend::focus`] and the rest) is queued for the script and +/// returns: the script gets the queue as the answer to its held `Poll` call, and carries the +/// commands out in order. Commands queued within a millisecond of each other go out as one batch, +/// so a retile reaches KWin at once. A command is an error when the table does not know the +/// window; a command for a window that has just closed is sent, and the script reports that it +/// could not carry it out, which is logged. +/// +/// The script cannot move the pointer, so the pointer follows the focus through KWin's own "Move +/// Mouse to Focus" action, over `kglobalaccel`: it lands in the middle of the window KWin has +/// focused, whatever rectangle [`Backend::center_cursor_in`] is given. A KWin without global +/// shortcuts leaves the pointer where it is. /// /// It is made by [`connect`]. pub struct KWinBackend { @@ -384,9 +393,37 @@ async fn load_script(connection: &Connection) -> eyre::Result<()> { 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") +/// KWin's own "Move Mouse to Focus" action: the scripting API cannot move the pointer +async fn move_mouse_to_focus(shared: &Shared) -> eyre::Result<()> { + let connection = shared.connection().await?; + let component = Proxy::new( + &connection, + "org.kde.kglobalaccel", + "/component/kwin", + "org.kde.kglobalaccel.Component", + ) + .await?; + component + .call_method("invokeShortcut", &("MoveMouseToFocus",)) + .await?; + Ok(()) +} + +fn command_rect(uuid: &str, rect: &Rect) -> Value { + json!({ "op": "geo", "id": uuid, "x": rect.left, "y": rect.top, "w": rect.right, "h": rect.bottom }) +} + +impl KWinBackend { + fn command(&self, id: u32, build: impl FnOnce(&str) -> Value) -> eyre::Result<()> { + let uuid = self + .shared + .table + .lock() + .uuid(id) + .ok_or_eyre("there is no such window")?; + self.shared.push(build(&uuid)); + Ok(()) + } } impl Backend for KWinBackend { @@ -424,32 +461,62 @@ impl Backend for KWinBackend { answer.or_else(|| self.shared.table.lock().cursor()) } - fn set_rect(&self, _id: u32, _rect: &Rect) -> eyre::Result<()> { - read_only() + fn set_rect(&self, id: u32, rect: &Rect) -> eyre::Result<()> { + tracing::debug!("asking for window {id} to be at {rect:?}"); + self.command(id, |uuid| command_rect(uuid, rect))?; + self.shared.table.lock().note_requested_rect(id, *rect); + Ok(()) } - fn focus(&self, _id: u32, _mouse_follows_focus: bool) -> eyre::Result<()> { - read_only() + fn focus(&self, id: u32, mouse_follows_focus: bool) -> eyre::Result<()> { + self.command(id, |uuid| json!({ "op": "activate", "id": uuid }))?; + + if mouse_follows_focus { + // the pointer can only follow once the window really is the active one + let shared = self.shared.clone(); + self.shared.handle.spawn(async move { + for _ in 0..60 { + if shared.table.lock().foreground() == Some(id) { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + + if let Err(error) = move_mouse_to_focus(&shared).await { + tracing::debug!("could not move the mouse to the focused window: {error}"); + } + }); + } + + Ok(()) } - fn raise(&self, _id: u32) -> eyre::Result<()> { - read_only() + fn raise(&self, id: u32) -> eyre::Result<()> { + self.command(id, |uuid| json!({ "op": "raise", "id": uuid })) } - fn minimize(&self, _id: u32) -> eyre::Result<()> { - read_only() + fn minimize(&self, id: u32) -> eyre::Result<()> { + self.command(id, |uuid| json!({ "op": "min", "id": uuid, "v": true })) } - fn unminimize(&self, _id: u32) -> eyre::Result<()> { - read_only() + fn unminimize(&self, id: u32) -> eyre::Result<()> { + self.command(id, |uuid| json!({ "op": "min", "id": uuid, "v": false })) } - fn close(&self, _id: u32) -> eyre::Result<()> { - read_only() + fn close(&self, id: u32) -> eyre::Result<()> { + self.command(id, |uuid| json!({ "op": "close", "id": uuid })) } fn center_cursor_in(&self, _rect: &Rect) -> eyre::Result<()> { - read_only() + // KWin can center the pointer on the active window and nothing else; the WM calls this + // right after focusing the window in question + let shared = self.shared.clone(); + self.shared.handle.spawn(async move { + if let Err(error) = move_mouse_to_focus(&shared).await { + tracing::debug!("could not move the mouse to the focused window: {error}"); + } + }); + Ok(()) } fn shutdown(&self) { @@ -520,10 +587,29 @@ mod tests { 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))); - }]; + let asks: [fn(&KWinBackend); 2] = [ + |backend| { + // nothing answers the query here, so the pointer is where the snapshot had it + assert_eq!(backend.cursor_pos(), Some((481, 525))); + }, + |backend| { + let left = |left| Rect { + left, + top: 0, + right: 960, + bottom: 1050, + }; + // the editor is 1, the terminal 2 and the dialog 3 + backend.set_rect(1, &left(0)).unwrap(); + backend.focus(1, false).unwrap(); + backend.raise(1).unwrap(); + backend.minimize(1).unwrap(); + backend.unminimize(1).unwrap(); + backend.close(3).unwrap(); + // the terminal has closed, and the table still knows it: the bridge gives it back + backend.set_rect(2, &left(960)).unwrap(); + }, + ]; assert_eq!(asks.len(), commands.len()); let mut handled = 0; @@ -540,6 +626,14 @@ mod tests { } } + #[test] + fn a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing() { + let (runtime, backend) = offline(); + + assert!(backend.focus(7, false).is_err()); + assert_eq!(next_poll(&runtime, &backend), json!([])); + } + #[test] fn a_poll_with_nothing_to_send_is_answered_with_nothing_once_its_hold_is_over() { let (runtime, backend) = offline(); diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index 4c40b559..97c13b34 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -201,12 +201,26 @@ impl Table { self.cursor } + /// Returns the UUID KWin knows the window by, which is how a command for the script names + /// it, or `None` if the table does not know the window. + pub fn uuid(&self, id: u32) -> Option { + self.windows.get(&id).map(|e| e.uuid.clone()) + } + /// 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 } + /// Records the frame komorebi has just asked KWin to give a window, so that the window manager + /// sees it at once. The `geometry` event that says what the client did replaces it. + pub fn note_requested_rect(&mut self, id: u32, rect: Rect) { + if let Some(entry) = self.windows.get_mut(&id) { + entry.info.rect = rect; + } + } + // ---- events ---------------------------------------------------------------------------- fn id_for(&mut self, uuid: &str) -> u32 { @@ -597,16 +611,24 @@ mod tests { "geometry -> ", "cursor -> Cursor 1 at 1200,701", "removed -> Destroy 2", + // the window manager's commands, and the terminal's, which had closed + "geometry -> ", + "activated -> FocusChange 1", + "minimized -> Minimize 1", + "minimized -> Restore 1", + "removed -> ", + "failed -> ", ] ); - // the editor of the snapshot is left, and its dialog, which komorebi does not manage + // the editor of the snapshot is left; its dialog, which komorebi does not manage, closed 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!(windows[0].rect.right, 960, "the frame komorebi asked for"); + assert_eq!(t.window(3).map(|w| w.alive), 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.foreground(), Some(1)); assert_eq!(t.cursor(), Some((1200, 701))); let monitor = &t.monitors()[0]; @@ -830,4 +852,29 @@ mod tests { )); assert_eq!(t.cursor(), Some((300, 400))); } + + #[test] + fn a_requested_rect_is_visible_at_once_and_replaced_by_the_real_one() { + let mut t = table(vec![win("a", &["d1"])]); + t.note_requested_rect( + 1, + Rect { + left: 0, + top: 0, + right: 960, + bottom: 1050, + }, + ); + assert_eq!(t.window(1).unwrap().rect.right, 960); + + t.handle( + &json!({ "type": "geometry", "id": "a", "geo": {"x":0,"y":0,"w":956,"h":1048} }), + Instant::now(), + ); + assert_eq!( + t.window(1).unwrap().rect.right, + 956, + "the client rounded it to its cell grid" + ); + } } diff --git a/nix/tests/vm/default.nix b/nix/tests/vm/default.nix index 99e4a62c..b530d40d 100644 --- a/nix/tests/vm/default.nix +++ b/nix/tests/vm/default.nix @@ -84,7 +84,8 @@ let node.specialArgs.komorebi = komorebiFor guestSystem; nodes.machine = { - imports = [ (./nodes + "/${suite.kind}.nix") ]; + # a suite's `node`, if it has one, adds to the node of its kind + imports = [ (./nodes + "/${suite.kind}.nix") ] ++ lib.optional (suite ? node) suite.node; }; testScript = '' diff --git a/nix/tests/vm/lib/komorebi_vm/__init__.py b/nix/tests/vm/lib/komorebi_vm/__init__.py index d6f4722e..90b8e7ef 100644 --- a/nix/tests/vm/lib/komorebi_vm/__init__.py +++ b/nix/tests/vm/lib/komorebi_vm/__init__.py @@ -7,16 +7,18 @@ A suite imports what it needs from here: 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. + handles and the frames it asks for. +* [`latency`](komorebi_vm.latency) times the daemon's commands from a recording + of the session bus. 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 import daemon, latency from komorebi_vm.checks import Checks from komorebi_vm.kde import Kde, Rect from komorebi_vm.machine import Machine -__all__ = ["Checks", "Kde", "Machine", "Rect", "daemon"] +__all__ = ["Checks", "Kde", "Machine", "Rect", "daemon", "latency"] diff --git a/nix/tests/vm/lib/komorebi_vm/daemon.py b/nix/tests/vm/lib/komorebi_vm/daemon.py index 035f3027..abd7957b 100644 --- a/nix/tests/vm/lib/komorebi_vm/daemon.py +++ b/nix/tests/vm/lib/komorebi_vm/daemon.py @@ -2,15 +2,22 @@ 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. +`--log-level debug`: every event it handles is an info line, every focus +change KWin reports names the window by the daemon's id and its title, and +every frame the daemon asks KWin for is a debug line. """ import re from dataclasses import dataclass +from komorebi_vm.kde import Rect + _EVENT = re.compile(r"processing event: (\w+) for window (\d+) with notification (\w+)") _ACTIVATED = re.compile(r"KWin activated window (\d+) \((.*)\)$", re.MULTILINE) +_REQUEST = re.compile( + r"asking for window (\d+) to be at " + r"Rect \{ left: (-?\d+), top: (-?\d+), right: (-?\d+), bottom: (-?\d+) \}" +) @dataclass(frozen=True) @@ -36,3 +43,21 @@ def window_ids(log: str) -> dict[str, int]: A title that two windows had is the later one's. """ return {title: int(window) for window, title in _ACTIVATED.findall(log)} + + +def requests(log: str) -> dict[int, Rect]: + """Returns the frame the daemon last asked KWin for, for each window, by the daemon's id.""" + return { + int(window): Rect(int(x), int(y), int(w), int(h)) + for window, x, y, w, h in _REQUEST.findall(log) + } + + +def asked(log: str, title: str) -> Rect | None: + """Returns the frame the daemon last asked KWin for, for the window with this title. + + `None` if KWin never gave the window the focus (which is how its title reaches the log), or + the daemon never asked for a frame for it. + """ + window = window_ids(log).get(title) + return requests(log).get(window) if window is not None else None diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index ea70c92f..db583dbe 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -63,6 +63,7 @@ class Kde: self.scale = scale self._bus = bus self._wayland_display = wayland_display + self._x_display: str | None = None @classmethod def headless( @@ -72,20 +73,33 @@ class Kde: *, size: tuple[int, int] = (1920, 1080), outputs: int = 1, + xwayland: bool = False, scale: float = 1.0, user: str = "komorebi", uid: int = 1000, ) -> "Kde": - """Starts `kwin_wayland --virtual` with `outputs` outputs of `size`, and waits for it.""" + """Starts `kwin_wayland --virtual` with `outputs` outputs of `size`, and waits for it. + + With `xwayland`, KWin also runs XWayland, for X11 clients. It starts it when the first + one connects and does not say where, so the session takes the first X11 socket of the + machine: one session at a time can have XWayland. + """ kde = cls(machine, name, user=user, uid=uid, scale=scale) machine.succeed(f"loginctl show-user {user} >/dev/null") width, height = size args = f"--width {width} --height {height} --output-count {outputs}" + if xwayland: + args += " --xwayland" kde.as_user(f"echo KWIN_ARGS={shlex.quote(args)} > {kde.runtime}/kwin-virtual-{name}.env") kde.systemctl("start", f"session-bus@{name}.service", f"kwin-virtual@{name}.service") if not kde.wait_for(lambda: kde.has_name("org.kde.KWin"), timeout=60): log = machine.execute(f"journalctl _UID={uid} --no-pager -n 40")[1] raise AssertionError(f"KWin did not come up:\n{log}") + if xwayland: + socket = "ls /tmp/.X11-unix | grep -E '^X[0-9]+$' | sort | head -n 1" + if not kde.wait_for(lambda: machine.execute(socket)[1].strip() != "", timeout=10): + raise AssertionError("KWin did not open an X11 socket") + kde._x_display = ":" + machine.execute(socket)[1].strip()[1:] return kde @classmethod @@ -139,6 +153,7 @@ class Kde: @property def env(self) -> str: """The `VAR=value` words that put a command inside this session.""" + profile = f"/etc/profiles/per-user/{self.user}" pairs = { "XDG_RUNTIME_DIR": self.runtime, "DBUS_SESSION_BUS_ADDRESS": self._bus @@ -149,7 +164,13 @@ class Kde: "XDG_SESSION_TYPE": "wayland", "QT_QPA_PLATFORM": "wayland", "GDK_BACKEND": "wayland", + # the user's, not those of root's shell, which a client would search and be refused + "HOME": f"/home/{self.user}", + "XDG_DATA_DIRS": f"{profile}/share:/run/current-system/sw/share", + "XDG_CONFIG_DIRS": f"/etc/xdg:{profile}/etc/xdg:/run/current-system/sw/etc/xdg", } + if self._x_display is not None: + pairs["DISPLAY"] = self._x_display return " ".join(f"{key}={shlex.quote(value)}" for key, value in pairs.items()) def as_user(self, command: str) -> str: @@ -164,9 +185,12 @@ class Kde: """Runs `command` inside the session, and fails the test unless it succeeds.""" return self.machine.succeed(self._wrap(command)) - def spawn(self, command: str) -> None: - """Starts `command` in the background inside the session, as a client of KWin.""" - self.sh(f"setsid nohup {command} >/dev/null 2>&1 < /dev/null &") + def spawn(self, command: str, log: str = "/dev/null") -> None: + """Starts `command` in the background inside the session, as a client of KWin. + + Its output goes to the file `log`, or nowhere. + """ + self.sh(f"setsid nohup {command} > {shlex.quote(log)} 2>&1 < /dev/null &") def systemctl(self, *args: str) -> str: """Runs `systemctl --user` as the test user.""" @@ -202,6 +226,15 @@ class Kde: """The daemon's log since it was last started, or the empty string before that.""" return self.machine.execute(f"cat {self.runtime}/komorebi-{self.name}.log")[1] + def monitor_bridge(self, path: str) -> None: + """Starts recording the bridge's traffic on the session bus to `path`, in the background. + + `dbus-monitor` records every call to the daemon's `org.komorebi.Bridge` interface and every + reply on the bus, which [`latency.rounds`](komorebi_vm.latency.rounds) reads. + """ + rules = "\"type='method_call',interface='org.komorebi.Bridge'\" \"type='method_return'\"" + self.sh(f"setsid nohup dbus-monitor --session {rules} > {path} 2>&1 < /dev/null &") + 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( @@ -235,6 +268,15 @@ class Kde: pattern = shlex.quote(f"^{title}$") return self.run(f"kdotool search --name {pattern} | head -1")[1].strip() + def wid_by_class(self, app: str) -> str: + """The id of the first window whose class is exactly `app`, or the empty string. + + The class is the Wayland app id (`org.kde.konsole`), or the X11 class of a client + on XWayland (`XTerm`). + """ + pattern = shlex.quote(f"^{app}$") + return self.run(f"kdotool search --class {pattern} | head -1")[1].strip() + def rect(self, wid: str) -> Rect: """The position and size KWin reports for the window.""" out = self.sh(f"kdotool getwindowgeometry {shlex.quote(wid)}") diff --git a/nix/tests/vm/lib/komorebi_vm/latency.py b/nix/tests/vm/lib/komorebi_vm/latency.py new file mode 100644 index 00000000..61ae57b6 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/latency.py @@ -0,0 +1,133 @@ +"""How long the commands of the daemon take to reach the windows of KWin. + +[`Kde.monitor_bridge`](komorebi_vm.kde.Kde.monitor_bridge) records the bridge's +traffic on the session bus with `dbus-monitor`: every `Event` call the script +makes, with its JSON, and every reply on the bus, among them the daemon's answers +to `Poll`, which carry the commands. Each line `dbus-monitor` prints for a message +has the time the bus delivered it to the monitor. + +A **round** starts when the daemon answers `Poll` with a batch that asks for a +window to be somewhere it was not asked to be before, and ends with the last +`geometry` event KWin reports for one of those windows before the next such batch +(or within a cut-off). Its duration is how long the windows took to be where the +daemon put them, the client's answer included. +""" + +import json +import math +import re +from dataclasses import dataclass +from typing import Any + +from komorebi_vm.kde import Rect + +_HEADER = re.compile(r"^(method call|method return|signal|error) time=(\d+\.\d+) (.*)$") +_STRING = ' string "' + + +@dataclass(frozen=True) +class Message: + """One D-Bus message, as `dbus-monitor` printed it.""" + + kind: str + """`method call`, `method return`, `signal` or `error`.""" + time: float + """When the bus delivered it, in seconds since the epoch.""" + member: str + """The method or signal, or the empty string for a reply.""" + body: str + """The first string argument, or the empty string.""" + + +@dataclass(frozen=True) +class Round: + """The windows of one batch of commands, from the batch to the last frame KWin reported.""" + + sent: float + """When the daemon's answer to `Poll` was delivered.""" + windows: int + """How many windows the batch moved.""" + seconds: float | None + """How long until the last of them reported its frame, or `None` if one never did.""" + + +def messages(text: str) -> list[Message]: + """Parses what `dbus-monitor` printed, in its default format.""" + out: list[Message] = [] + header: re.Match[str] | None = None + body = "" + + def flush() -> None: + if header is not None: + fields = header.group(3) + member = re.search(r"member=(\S+)", fields) + out.append( + Message(header.group(1), float(header.group(2)), member[1] if member else "", body) + ) + + for line in text.splitlines(): + if match := _HEADER.match(line): + flush() + header, body = match, "" + elif header is not None and not body and line.startswith(_STRING) and line.endswith('"'): + body = line[len(_STRING) : -1] + flush() + return out + + +def _json(text: str) -> Any: + try: + return json.loads(text) + except ValueError: + return None + + +def rounds(text: str, cut_off: float = 2.0) -> list[Round]: + """Returns every round in what `dbus-monitor` printed, in order. + + A batch that asks every window for the frame it was last asked for moves + nothing, and is not a round. A round ends at the next round, or `cut_off` + seconds after it started, whichever comes first. + """ + batches: list[tuple[float, dict[str, Rect]]] = [] + frames: list[tuple[float, str]] = [] + for message in messages(text): + value = _json(message.body) + if message.kind == "method return" and isinstance(value, list): + geo = { + command["id"]: Rect(command["x"], command["y"], command["w"], command["h"]) + for batch in value + if isinstance(batch, dict) + for command in batch.get("cmds", []) + if command.get("op") == "geo" + } + if geo: + batches.append((message.time, geo)) + elif message.member == "Event" and isinstance(value, dict): + if value.get("type") == "geometry": + frames.append((message.time, value["id"])) + + asked: dict[str, Rect] = {} + moving: list[tuple[float, set[str]]] = [] + for sent, geo in batches: + moved = {uuid for uuid, rect in geo.items() if asked.get(uuid) != rect} + asked.update(geo) + if moved: + moving.append((sent, moved)) + + out = [] + for i, (sent, moved) in enumerate(moving): + end = sent + cut_off + if i + 1 < len(moving): + end = min(end, moving[i + 1][0]) + last = {uuid: t for t, uuid in frames if sent < t <= end and uuid in moved} + seconds = max(last.values()) - sent if len(last) == len(moved) else None + out.append(Round(sent, len(moved), seconds)) + return out + + +def percentile(values: list[float], fraction: float) -> float: + """The value below which `fraction` of the values are (nearest rank).""" + ordered = sorted(values) + rank = min(len(ordered), max(1, math.ceil(fraction * len(ordered)))) + return ordered[rank - 1] diff --git a/nix/tests/vm/lib/tests/test_daemon.py b/nix/tests/vm/lib/tests/test_daemon.py index 9b915e99..c6f0c6cc 100644 --- a/nix/tests/vm/lib/tests/test_daemon.py +++ b/nix/tests/vm/lib/tests/test_daemon.py @@ -1,4 +1,4 @@ -from komorebi_vm import daemon +from komorebi_vm import Rect, daemon from komorebi_vm.daemon import Event LOG = """\ @@ -26,3 +26,27 @@ def test_window_ids_are_found_by_title_also_one_with_parentheses() -> None: def test_an_empty_log_has_nothing_in_it() -> None: assert daemon.events("") == [] assert daemon.window_ids("") == {} + + +def test_requests_are_the_last_frame_asked_for_each_window() -> None: + log = ( + "DEBUG komorebi::kwin: asking for window 2 to be at " + "Rect { left: 10, top: 10, right: 1900, bottom: 1060 }\n" + "DEBUG komorebi::kwin: asking for window 3 to be at " + "Rect { left: -5, top: 0, right: 940, bottom: 1060 }\n" + "DEBUG komorebi::kwin: asking for window 2 to be at " + "Rect { left: 10, top: 10, right: 940, bottom: 1060 }\n" + ) + + assert daemon.requests(log) == {2: Rect(10, 10, 940, 1060), 3: Rect(-5, 0, 940, 1060)} + + +def test_asked_finds_the_frame_by_the_title_of_the_window() -> None: + log = LOG + ( + "DEBUG komorebi::kwin: asking for window 2 to be at " + "Rect { left: 10, top: 10, right: 940, bottom: 1060 }\n" + ) + + assert daemon.asked(log, "alpha") == Rect(10, 10, 940, 1060) + assert daemon.asked(log, "a (b) c") is None + assert daemon.asked(log, "nobody") is None diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index 0794f1a8..5fb407d0 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -186,3 +186,60 @@ def test_window_actions_go_through_kdotool_inside_the_session(machine: FakeMachi "kdotool windowclose '{a}'", ] assert all("WAYLAND_DISPLAY=wayland-main" in command for command in machine.commands) + + +def test_wid_by_class_searches_the_class(machine: FakeMachine) -> None: + machine.reply("kdotool search --class", output="{x}\n") + + assert Kde(machine, "main").wid_by_class("XTerm") == "{x}" + assert inner(machine.commands[0]) == "kdotool search --class '^XTerm$' | head -1" + + +def test_headless_with_xwayland_starts_it_and_puts_the_x11_display_in_the_session( + machine: FakeMachine, +) -> None: + machine.reply("busctl", status=0) + machine.reply("/tmp/.X11-unix", output="X1\n") + + kde = Kde.headless(machine, "main", xwayland=True) + + scripts = [inner(command) for command in machine.commands if " sh -c " in command] + assert any("--output-count 1 --xwayland'" in script for script in scripts) + assert "DISPLAY=:1" in kde.env.split() + assert not any(word.startswith("DISPLAY=") for word in Kde(machine, "other").env.split()) + + +def test_monitor_bridge_records_the_calls_to_the_bridge_and_the_replies( + machine: FakeMachine, +) -> None: + Kde(machine, "main").monitor_bridge("/tmp/bus.log") + + (script,) = [inner(command) for command in machine.commands] + assert script.startswith("setsid nohup dbus-monitor --session ") + assert "\"type='method_call',interface='org.komorebi.Bridge'\"" in script + assert "\"type='method_return'\"" in script + assert script.endswith("> /tmp/bus.log 2>&1 < /dev/null &") + + +def test_spawn_sends_the_output_of_the_client_where_it_is_asked(machine: FakeMachine) -> None: + kde = Kde(machine, "main") + + kde.spawn("foot") + kde.spawn("xterm -T x", log="/tmp/x.log") + + assert [inner(command) for command in machine.commands] == [ + "setsid nohup foot > /dev/null 2>&1 < /dev/null &", + "setsid nohup xterm -T x > /tmp/x.log 2>&1 < /dev/null &", + ] + + +def test_a_session_has_the_users_data_and_config_directories_not_roots( + machine: FakeMachine, +) -> None: + words = Kde(machine, "main").env.split() + + assert "HOME=/home/komorebi" in words + assert ( + "XDG_DATA_DIRS=/etc/profiles/per-user/komorebi/share:/run/current-system/sw/share" in words + ) + assert not any("/root" in word for word in words) diff --git a/nix/tests/vm/lib/tests/test_latency.py b/nix/tests/vm/lib/tests/test_latency.py new file mode 100644 index 00000000..07560e41 --- /dev/null +++ b/nix/tests/vm/lib/tests/test_latency.py @@ -0,0 +1,91 @@ +import json + +import pytest + +from komorebi_vm import latency +from komorebi_vm.latency import Message, Round + + +def call(time: float, body: dict[str, object]) -> str: + return ( + f"method call time={time:.6f} sender=:1.5 -> destination=org.komorebi.Bridge serial=1" + " path=/org/komorebi/Bridge; interface=org.komorebi.Bridge; member=Event\n" + f' string "{json.dumps(body)}"\n' + ) + + +def answer(time: float, cmds: list[dict[str, object]]) -> str: + batches = [{"batch": 1, "cmds": cmds}] + return ( + f"method return time={time:.6f} sender=:1.3 -> destination=:1.5 serial=9 reply_serial=2\n" + f' string "{json.dumps(batches)}"\n' + ) + + +def geo(uuid: str, x: int) -> dict[str, object]: + return {"op": "geo", "id": uuid, "x": x, "y": 0, "w": 100, "h": 100} + + +def frame(time: float, uuid: str) -> str: + return call(time, {"type": "geometry", "id": uuid, "geo": {"x": 0, "y": 0, "w": 9, "h": 9}}) + + +def test_messages_are_parsed_with_their_time_member_and_string() -> None: + text = call(1.5, {"type": "added"}) + ( + "method return time=2.000000 sender=:1.1 -> destination=:1.2 serial=3 reply_serial=1\n" + " boolean true\n" + ) + + assert latency.messages(text) == [ + Message("method call", 1.5, "Event", '{"type": "added"}'), + Message("method return", 2.0, "", ""), + ] + + +def test_a_round_lasts_until_the_last_window_it_moved_reports_its_frame() -> None: + text = ( + answer(10.0, [geo("a", 0), geo("b", 100)]) + + frame(10.004, "a") + + frame(10.010, "b") + + frame(10.016, "a") + ) + + (only,) = latency.rounds(text) + assert (only.sent, only.windows) == (10.0, 2) + assert only.seconds == pytest.approx(0.016) + + +def test_asking_again_for_the_same_frames_is_not_a_round() -> None: + text = ( + answer(10.0, [geo("a", 0)]) + + frame(10.01, "a") + + answer(11.0, [geo("a", 0), {"op": "activate", "id": "a"}]) + + answer(12.0, [geo("a", 50)]) + + frame(12.02, "a") + ) + + rounds = latency.rounds(text) + assert [r.sent for r in rounds] == [10.0, 12.0] + assert (rounds[1].sent, rounds[1].windows) == (12.0, 1) + assert rounds[1].seconds == pytest.approx(0.02) + + +def test_a_window_that_never_reports_leaves_its_round_unsettled() -> None: + text = answer(10.0, [geo("a", 0)]) + frame(13.0, "a") + + assert latency.rounds(text) == [Round(10.0, 1, None)] + + +def test_a_round_ends_where_the_next_one_starts() -> None: + text = answer(10.0, [geo("a", 0)]) + answer(10.5, [geo("a", 9)]) + frame(10.6, "a") + + assert [r.seconds for r in latency.rounds(text)] == [None, pytest.approx(0.1)] + + +def test_percentile_is_the_nearest_rank() -> None: + values = [float(n) for n in range(1, 21)] + + assert latency.percentile(values, 0.5) == 10.0 + assert latency.percentile(values, 0.95) == 19.0 + assert latency.percentile(values, 1.0) == 20.0 + assert latency.percentile([3.0], 0.5) == 3.0 diff --git a/nix/tests/vm/nodes/headless.nix b/nix/tests/vm/nodes/headless.nix index ad6f8ec0..638c6d15 100644 --- a/nix/tests/vm/nodes/headless.nix +++ b/nix/tests/vm/nodes/headless.nix @@ -52,6 +52,8 @@ description = "A headless KWin for the test session %i"; requires = [ "session-bus@%i.service" ]; after = [ "session-bus@%i.service" ]; + # KWin looks for Xwayland on its PATH, when it is started with --xwayland + path = [ pkgs.xwayland ]; environment = { DBUS_SESSION_BUS_ADDRESS = "unix:path=%t/session-%i.bus"; XDG_SESSION_TYPE = "wayland"; diff --git a/nix/tests/vm/suites/client-geometry/default.nix b/nix/tests/vm/suites/client-geometry/default.nix new file mode 100644 index 00000000..40a0c7d0 --- /dev/null +++ b/nix/tests/vm/suites/client-geometry/default.nix @@ -0,0 +1,23 @@ +{ + tier = "slow"; + kind = "headless"; + timeoutMinutes = 20; + node = + { pkgs, ... }: + { + # eight clients, Firefox among them + virtualisation = { + memorySize = 6144; + cores = 4; + }; + environment.systemPackages = with pkgs; [ + firefox + gnome-calculator + gnome-text-editor + kdePackages.dolphin + kdePackages.kate + kdePackages.konsole + xterm + ]; + }; +} diff --git a/nix/tests/vm/suites/client-geometry/test.py b/nix/tests/vm/suites/client-geometry/test.py new file mode 100644 index 00000000..6055401e --- /dev/null +++ b/nix/tests/vm/suites/client-geometry/test.py @@ -0,0 +1,101 @@ +# How real clients answer the frame komorebi asks for. KWin carries out a request at once; the +# client then decides the size it draws at, and that is the frame KWin reports. What only real +# clients can tell, and what the fake desktop of the Rust tests cannot know: Qt and KDE programs +# and X11 programs on XWayland take the frame exactly, also below the minimum size they report; +# foot sizes itself down to whole cells of its font; GTK 4 programs and Firefox never go below +# their minimum size. Every client keeps the position komorebi asked for. The output is large +# enough that some tiles are bigger and some smaller than the clients' minimums. +from komorebi_vm import Checks, Kde, Rect, daemon + +W, H = 3840, 2160 +CELL = 24 + +EXACT = ["org.kde.konsole", "org.kde.kate", "org.kde.dolphin", "XTerm"] +WHOLE_CELLS = ["foot"] +NOT_BELOW_MINIMUM = ["org.gnome.TextEditor", "org.gnome.Calculator", "firefox"] + +CLIENTS = { + "foot": "foot -T foot-term sleep 3000", + "org.kde.konsole": "konsole --separate", + "org.kde.dolphin": "dolphin --new-window /tmp", + "org.kde.kate": "kate --new", + "org.gnome.TextEditor": "gnome-text-editor --new-window", + "org.gnome.Calculator": "gnome-calculator", + "XTerm": "xterm -T xterm-x11", + "firefox": "firefox --no-remote --profile /tmp/firefox-profile about:blank", +} + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(W, H), xwayland=True, scale=SCALE) +kde.as_user("mkdir -p /tmp/firefox-profile") +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 kde.komorebi_log(), timeout=30), +) + +for app, command in CLIENTS.items(): + kde.spawn(command, log=f"/tmp/{app}.log") + up = kde.wait_for(lambda app=app: kde.wid_by_class(app) != "", timeout=120) + if not checks.check(f"{app} has a window", up): + print(machine.execute(f"cat /tmp/{app}.log")[1]) + + +def shown() -> int: + return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show") + + +checks.check("the daemon tiles all eight", kde.wait_for(lambda: shown() >= 8, timeout=60)) + + +def show(r: Rect | None) -> str: + return "-" if r is None else f"{r.x},{r.y} {r.w}x{r.h}" + + +def snapshot() -> dict[str, Rect]: + return {app: kde.rect(kde.wid_by_class(app)) for app in CLIENTS} + + +# the clients answer in their own time; the frames are final once they stop changing +before: dict[str, Rect] = {} + + +def still() -> bool: + global before + now = snapshot() + unchanged = now == before + before = now + return unchanged + + +kde.wait_for(still, timeout=60, interval=3) +requests = list(daemon.requests(kde.komorebi_log()).values()) + +print(f" {'client':<22} {'asked':<22} {'has':<22}") +for app, have in snapshot().items(): + asked = [r for r in requests if (r.x, r.y) == (have.x, have.y)] + want = asked[0] if asked else None + print(f" {app:<22} {show(want):<22} {show(have):<22}") + if not checks.check(f"{app} is where komorebi put it", want is not None): + continue + assert want is not None + if app in EXACT: + checks.check(f"{app} takes the size it is asked for", (have.w, have.h) == (want.w, want.h)) + elif app in WHOLE_CELLS: + checks.check( + f"{app} sizes itself down to whole cells", + 0 <= want.w - have.w < CELL and 0 <= want.h - have.h < CELL, + ) + elif app in NOT_BELOW_MINIMUM: + checks.check( + f"{app} is never smaller than it is asked to be", + have.w >= want.w and have.h >= want.h, + ) + +kde.stop_komorebi() +kde.stop() +checks.finish() diff --git a/nix/tests/vm/suites/core-e2e/default.nix b/nix/tests/vm/suites/core-e2e/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/core-e2e/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/core-e2e/test.py b/nix/tests/vm/suites/core-e2e/test.py new file mode 100644 index 00000000..e711fe49 --- /dev/null +++ b/nix/tests/vm/suites/core-e2e/test.py @@ -0,0 +1,142 @@ +# komorebi tiles a real KWin. What only a real KWin can tell: that the commands the daemon queues +# reach KWin through the held call and that KWin carries them out, so that each window is where +# the daemon asked for it (`komorebi/tests/wm_events.rs` checks the window manager's side against +# the fake), and that the daemon and KWin agree on which window has the focus. A window manager +# that agrees with itself proves nothing, so what the daemon believes is read from its debug log +# and what KWin has through kdotool. +from komorebi_vm import Checks, Kde, Rect, daemon + +W, H = 1920, 1080 +# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for +CELL = 24 + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) + + +def daemon_log() -> str: + return kde.komorebi_log() + + +def inside(r: Rect) -> bool: + return r.x >= 0 and r.y >= 0 and r.x + r.w <= W and r.y + r.h <= H + + +def asked(title: str) -> Rect | None: + return daemon.asked(daemon_log(), title) + + +def where_asked(title: str) -> bool: + """KWin has the window where the daemon asked: the same place, and the size up to a cell.""" + want, wid = asked(title), kde.wid(title) + if want is None or wid == "": + return False + have = kde.rect(wid) + return ( + (have.x, have.y) == (want.x, want.y) + and 0 <= want.w - have.w < CELL + and 0 <= want.h - have.h < CELL + ) + + +def focus_agrees() -> bool: + """The window KWin has focused is the one the daemon last handled a focus change for.""" + log = daemon_log() + focus_changes = [e.window for e in daemon.events(log) if e.kind == "FocusChange"] + active = kde.active() + if not focus_changes or active == "": + return False + return daemon.window_ids(log).get(kde.title(active)) == focus_changes[-1] + + +def report(titles: list[str]) -> None: + for title in titles: + print(f" {title}: asked {asked(title)}, has {kde.rect(kde.wid(title))}") + + +print("== 1. start") +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()) + +print("== 2. three windows are tiled") +titles = ["win1", "win2", "win3"] +for title in titles: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30) + kde.wait_for(lambda title=title: title in daemon.window_ids(daemon_log()), timeout=10) +settled = kde.wait_for(lambda: all(where_asked(t) for t in titles), timeout=20) +report(titles) +checks.check("every window is where the daemon asked for it", settled) +rects = [kde.rect(kde.wid(t)) for t in titles] +for title, rect in zip(titles, rects, strict=True): + checks.check(f"{title} is inside the screen", inside(rect)) +checks.check("win1 and win2 do not overlap", not rects[0].overlaps(rects[1])) +checks.check("win1 and win3 do not overlap", not rects[0].overlaps(rects[2])) +checks.check("win2 and win3 do not overlap", not rects[1].overlaps(rects[2])) +checks.check("the windows share the screen: none is full width", all(r.w < W - 20 for r in rects)) +checks.check("KWin and the daemon agree on the focused window", kde.wait_for(focus_agrees)) + +print("== 3. the focus moves by hand") +kde.activate(kde.wid("win1")) +checks.check("KWin focused win1", kde.wait_for(lambda: kde.title(kde.active()) == "win1")) +checks.check("... and the daemon followed", kde.wait_for(focus_agrees)) + +print("== 4. minimize and restore") +kde.minimize(kde.wid("win2")) +two = ["win1", "win3"] +checks.check( + "the other two windows take the screen", + kde.wait_for( + lambda: ( + all(where_asked(t) for t in two) + and all(kde.rect(kde.wid(t)).w > W // 2 - 40 for t in two) + ), + timeout=20, + ), +) +report(two) +kde.activate(kde.wid("win2")) +checks.check( + "restored, the three windows are tiled again", + kde.wait_for( + lambda: ( + all(where_asked(t) for t in titles) + and all(kde.rect(kde.wid(t)).w < W - 20 for t in titles) + ), + timeout=20, + ), +) +report(titles) + +print("== 5. close") +kde.close(kde.wid("win3")) +checks.check("KWin closed win3", kde.wait_for(lambda: kde.wid("win3") == "", timeout=10)) +checks.check( + "the two that are left share the screen again", + kde.wait_for( + lambda: ( + all(where_asked(t) for t in ["win1", "win2"]) + and not kde.rect(kde.wid("win1")).overlaps(kde.rect(kde.wid("win2"))) + ), + timeout=20, + ), +) +report(["win1", "win2"]) +checks.check("KWin carried out every command", "the bridge could not do" not in daemon_log()) + +print("== 6. stop") +kde.stop_komorebi() +checks.check("the daemon exited", not kde.komorebi_running()) +checks.check("the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded())) +checks.check("the windows stay", kde.wid("win1") != "" and kde.wid("win2") != "") + +kde.stop() +checks.finish() diff --git a/nix/tests/vm/suites/kwin-events/test.py b/nix/tests/vm/suites/kwin-events/test.py index 975dc891..df38a6d3 100644 --- a/nix/tests/vm/suites/kwin-events/test.py +++ b/nix/tests/vm/suites/kwin-events/test.py @@ -1,8 +1,8 @@ # 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. +# raised them (KWin activates a new window before it announces it), 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 @@ -28,7 +28,6 @@ checks.check( 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( @@ -98,15 +97,6 @@ checks.check( 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()) diff --git a/nix/tests/vm/suites/latency/default.nix b/nix/tests/vm/suites/latency/default.nix new file mode 100644 index 00000000..a4ba7be3 --- /dev/null +++ b/nix/tests/vm/suites/latency/default.nix @@ -0,0 +1,10 @@ +{ + tier = "slow"; + kind = "headless"; + timeoutMinutes = 15; + node = + { pkgs, ... }: + { + environment.systemPackages = [ pkgs.dbus ]; + }; +} diff --git a/nix/tests/vm/suites/latency/test.py b/nix/tests/vm/suites/latency/test.py new file mode 100644 index 00000000..91b46830 --- /dev/null +++ b/nix/tests/vm/suites/latency/test.py @@ -0,0 +1,83 @@ +# How long a retile takes to reach the windows of a real KWin, measured on the session bus: from +# the moment the daemon answers the bridge's held call with a batch of new frames, to the last +# frame KWin reports for one of the windows it moved, the client's answer included. Every number +# here comes from KWin and real clients; the Rust tests cannot measure it. The output is large, so +# that ten windows in komorebi's default layout all have room. +from komorebi_vm import Checks, Kde, daemon, latency + +W, H = 3840, 2160 +WINDOWS = 10 +ROUNDS = 10 +BUS_LOG = "/tmp/komorebi-bus.log" + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) +kde.start_komorebi() +checks.check( + "the daemon loaded its script into KWin", + kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30), +) +kde.monitor_bridge(BUS_LOG) + +titles = [f"w{n}" for n in range(1, WINDOWS + 1)] +for title in titles: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30) + + +def shown() -> int: + return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show") + + +checks.check(f"the daemon tiles all {WINDOWS}", kde.wait_for(lambda: shown() >= WINDOWS)) + + +def measured() -> list[latency.Round]: + return latency.rounds(machine.succeed(f"cat {BUS_LOG}")) + + +def settled_after(count: int) -> bool: + """A round after the first `count` is over: its windows all reported, and then 0.3 s passed.""" + done = measured() + if len(done) <= count or done[-1].seconds is None: + return False + now = float(machine.succeed("date +%s.%N")) + return now - (done[-1].sent + done[-1].seconds) > 0.3 + + +kde.wait_for(lambda: settled_after(0), timeout=10) +start = len(measured()) + +# each round takes one window out of the layout and puts it back: two retiles +for title in titles[:ROUNDS]: + wid = kde.wid(title) + count = len(measured()) + kde.minimize(wid) + kde.wait_for(lambda count=count: settled_after(count), timeout=10) + count = len(measured()) + kde.activate(wid) + kde.wait_for(lambda count=count: settled_after(count), timeout=10) + +# the rounds before `start` tiled the windows as they opened +rounds = measured()[start:] +settled = [r.seconds * 1000 for r in rounds if r.seconds is not None] +moved = sum(r.windows for r in rounds) / max(1, len(rounds)) +print(f" {len(rounds)} retiles, {moved:.1f} windows moved by each on average, scale {SCALE}") +if settled: + p50, p95 = latency.percentile(settled, 0.5), latency.percentile(settled, 0.95) + print(f" from the batch to the last frame: p50 {p50:.1f} ms, p95 {p95:.1f} ms,") + print(f" max {max(settled):.1f} ms, min {min(settled):.1f} ms") +checks.check(f"{2 * ROUNDS} retiles were measured", len(rounds) == 2 * ROUNDS) +checks.check("every window of every retile reported its frame", len(settled) == len(rounds)) +checks.check( + "a retile reaches the windows within 100 ms (times the machine's scale), at p95", + bool(settled) and latency.percentile(settled, 0.95) <= 100 * SCALE, +) + +kde.stop_komorebi() +kde.stop() +checks.finish() From 4386003e30b8f0c6a35c467ce73dbda25b573acd Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 14:17:51 -0700 Subject: [PATCH 013/255] feat(kwin): survive KWin restarting KWin can go away under a running daemon while the session bus stays: it crashed, or kwin_wayland --replace took its place. Its windows go with it, and so does the bridge, which would have reported them closing; in the spikes the old windows vanished without a single removed event. What the daemon does see is the bus, so the thread that serves the connection watches NameOwnerChanged for org.kde.KWin. When the name loses its owner, Table::compositor_lost marks every window closed and returns a Destroy for each, so the window manager takes them out of its layout, and their ids are not given out again. When the name has an owner again, the daemon loads the bridge into the new KWin, trying for up to 15 seconds while KWin is not ready for it, and the bridge reports the new desktop in a snapshot. zbus does not end a held call when its caller leaves the bus, so the Poll of the old bridge is still waiting when the new bridge calls, and it was woken first: it took the commands for the new KWin and answered them to nobody. vm-kwin-restart lost the tile of a window opened in the third KWin that way in one run of three, and a recording of the bus showed the batch going to the old bridge. A Poll held since before KWin last left the bus is answered with nothing and passes its wake-up on to the next call, which a unit test holds. The VM suite vm-kwin-restart (from the spike's spike7-resync) restarts the headless KWin twice under a running daemon, through Kde.restart_kwin in the VM library, and checks that the daemon sees KWin go, takes the old windows out of its layout, loads the bridge into the new KWin, and tiles the windows that open there. --- Cargo.lock | 13 ++ README.md | 2 +- docs/dev/ARCHITECTURE.md | 15 +++ docs/dev/DESIGN.md | 12 ++ docs/dev/PLATFORM.md | 17 ++- docs/dev/vm-tests.md | 2 + komorebi/Cargo.toml | 1 + komorebi/src/kwin/mod.rs | 114 ++++++++++++++-- komorebi/src/kwin/state.rs | 47 ++++++- nix/tests/vm/lib/komorebi_vm/kde.py | 11 ++ nix/tests/vm/lib/tests/test_kde.py | 22 ++++ nix/tests/vm/suites/kwin-restart/default.nix | 5 + nix/tests/vm/suites/kwin-restart/test.py | 131 +++++++++++++++++++ 13 files changed, 380 insertions(+), 12 deletions(-) create mode 100644 nix/tests/vm/suites/kwin-restart/default.nix create mode 100644 nix/tests/vm/suites/kwin-restart/test.py diff --git a/Cargo.lock b/Cargo.lock index 8f57b407..1474f253 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -601,6 +601,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "futures-task" version = "0.3.34" @@ -614,6 +625,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-macro", "futures-task", "pin-project-lite", "slab", @@ -949,6 +961,7 @@ dependencies = [ "crossbeam-channel", "ctrlc", "dirs", + "futures-util", "komorebi-layouts", "lazy_static", "nanoid", diff --git a/README.md b/README.md index b4cc9fe0..ae7bceef 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ 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. +manager. If KWin restarts, the daemon loads the bridge into the new one. 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 diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index d82a0aac..1583aeb4 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -139,6 +139,16 @@ script: when it follows the focus, the backend invokes KWin's "Move Mouse to Foc which centers it on the window KWin has focused. When komorebi stops, the backend asks KWin to unload the bridge. +KWin can restart under a running daemon, on the same session bus. The thread that serves +the connection watches the owner of `org.kde.KWin` on the bus. When KWin leaves it, the +bridge has gone with it and its windows too, and nothing will report them closing: +[`Table::compositor_lost`] marks every window closed and returns a `Destroy` for each, so the +window manager takes them out of its layout. When KWin is back, the daemon loads the bridge +into it again, the bridge sends a snapshot of the new KWin's desktop, and its events are +handled as before. The `Poll` call the old bridge held is still open in the daemon, since +zbus does not end a call when its caller leaves the bus: it is answered with nothing as soon +as it wakes, and the commands go to the new bridge's call. + [`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 @@ -219,6 +229,8 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | Every window is where komorebi asked for it, within the size its client keeps to | VM test | `vm-core-e2e`, `vm-client-geometry` | a client may refuse a size: the frame is what `window_rect` says | | A retile reaches KWin as one batch | framework path: the answer to `Poll` waits a millisecond after the first command for the others | `vm-latency` | none | | The window manager sees a frame it asked for at once | framework path: the KWin backend's `set_rect` records it in the table before KWin answers | `a_requested_rect_is_visible_at_once_and_replaced_by_the_real_one` | none | +| A KWin that restarts gets the bridge again, and the windows of the old one leave the layout | framework path: the connection's thread watches `NameOwnerChanged` for `org.kde.KWin`, and the table destroys every window when the name is lost | `when_kwin_goes_away_every_window_it_had_is_destroyed`, `vm-kwin-restart` | none | +| After KWin restarts, the commands go to the new bridge | framework path: a `Poll` held since before KWin last left the bus is answered with nothing, and passes on the wake-up it got | `a_poll_held_by_the_bridge_of_a_kwin_that_has_gone_gets_no_commands`, `vm-kwin-restart` ("a window opened in the third KWin is tiled") | 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, checking what KWin is asked to do for each | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a command for a window KWin no longer has is given back, and the rest are carried out` | none | @@ -289,6 +301,8 @@ A window is shown, and ends up on a tile: events of a real KWin, through the daemon. - [`nix/tests/vm/suites/core-e2e`](../../nix/tests/vm/suites/core-e2e/test.py): the daemon tiling a real KWin, checked against what KWin has. +- [`nix/tests/vm/suites/kwin-restart`](../../nix/tests/vm/suites/kwin-restart/test.py): KWin + restarting under the daemon. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager driven end to end against the fake. @@ -320,6 +334,7 @@ A window is shown, and ends up on a tile: [`kwin::state`]: ../../komorebi/src/kwin/state.rs [`Table`]: ../../komorebi/src/kwin/state.rs [`Table::handle`]: ../../komorebi/src/kwin/state.rs +[`Table::compositor_lost`]: ../../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 diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index eb01257c..cf1a65cb 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -143,3 +143,15 @@ to the middle of the focused window, for two different windows. The backend asks KWin reports the window it focused as active, so the action finds the right one. The cost is that the pointer can go to the middle of the focused window and nowhere else, which is what komorebi asks for. + +## Why does komorebi take every window out of its layout when KWin leaves the session bus? + +Because nothing else will say that they have gone. When KWin goes away under a running +session (it crashed, or another KWin replaced it), its clients lose their connection and +their windows go with it, and so does the bridge, which would have reported them closing. In +the spikes KWin was killed and started again under a running daemon on the same bus, twice: +the old windows vanished without a single `removed` event. What the daemon does see is the +bus itself: `NameOwnerChanged` says that `org.kde.KWin` has lost its owner, and later that it +has a new one. So losing the name counts as every window closing, and getting it back as the +moment to load the bridge into the new KWin, which then reports its desktop as it does at +start. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 12fbcb6c..9d2a41ce 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -74,6 +74,18 @@ and carries the commands out in KWin, in order. The script API cannot move the p when the pointer follows the focus komorebi invokes KWin's own "Move Mouse to Focus" shortcut, which puts the pointer in the middle of the window KWin has focused. +#### When KWin restarts + +KWin can go away while the session goes on: it crashed, or `kwin_wayland --replace` took its +place. The session bus stays, and the windows go with the old KWin. komorebi keeps running. It +watches who owns `org.kde.KWin` on the session bus, and when nobody does it takes every window +of the old KWin out of its layout, as if each had been closed: the bridge went with KWin, so +nothing reports them closing. When the name has an owner again, komorebi loads the bridge into +the new KWin, trying again for up to 15 seconds while KWin is not ready for it, and the bridge +reports the new KWin's windows and outputs as it does at start. A window that opens in the new +KWin is tiled. In the spikes the bridge was loaded again 1.0 to 1.1 seconds after the name had +an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a running daemon. + #### What komorebi leaves behind When it is stopped with `SIGINT` or `SIGTERM` it asks KWin to unload the script. The file @@ -120,8 +132,9 @@ 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 | +| `org.kde.KWin` | `/Scripting` | `org.kde.kwin.Scripting` | `unloadScript(s)`, `loadScript(ss) -> i` | at start, and when KWin is back after a restart; `unloadScript` again at exit | +| `org.kde.KWin` | `/Scripting/Script` | `org.kde.kwin.Script` | `run()` | after `loadScript` | +| `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `AddMatch(s)`, for the signal `NameOwnerChanged` | at start, to see KWin leave the bus and come back | | `org.kde.kglobalaccel` | `/component/kwin` | `org.kde.kglobalaccel.Component` | `invokeShortcut(s)`, with `MoveMouseToFocus` | when the pointer follows the focus | ## Files and directories diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index cce66e77..dd68907c 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -103,6 +103,8 @@ the run. - `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. + `restart_kwin()` stops the session's KWin and starts a new one on the same + bus, as when the compositor of a running session crashes, and waits for it. - `daemon` reads the daemon's view of the desktop from that log, started with `--log-level debug`: `daemon.events(log)` lists the window events it handled, in order, `daemon.window_ids(log)` maps a window's title to the daemon's id diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index f2ebecb6..d419f055 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -26,6 +26,7 @@ tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] } tracing = { workspace = true } tracing-subscriber = { workspace = true } zbus = { version = "5", default-features = false, features = ["tokio"] } +futures-util = "0.3" [features] default = ["schemars"] diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index 24125ff7..f8e04377 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -27,6 +27,13 @@ //! window events of [`crate::window_manager_event`], and queues every command of [`Backend`] for //! the script, which carries it out in KWin. //! +//! KWin can go away under a running daemon (it crashed, or `kwin_wayland --replace` took its +//! place) while the session bus stays. The daemon watches who owns `org.kde.KWin` on the bus: +//! when nobody does, every window of the old KWin is gone, and nothing will report it closing, so +//! the table reports each as destroyed ([`state::Table::compositor_lost`]); when the name has an +//! owner again, the daemon loads the script into the new KWin, which reports its desktop as it +//! does at start. +//! //! `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. @@ -42,6 +49,7 @@ use crate::core::Rect; use crate::window_manager_event_listener; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use futures_util::StreamExt; use parking_lot::Condvar; use parking_lot::Mutex; use serde_json::Value; @@ -84,20 +92,23 @@ struct Shared { queue: Mutex>, wake: Notify, batch: AtomicU64, + /// how many times KWin has left the session bus. A `Poll` held since before then was made by a + /// script that went with its KWin, and is answered with nothing rather than with the commands + kwin_lost: 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 + /// false once the thread that runs the runtime has ended, which is when KWin is gone: 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 + /// Run something on the runtime and wait for it, unless the runtime is gone: when KWin has gone + /// (the session is being torn down), its thread has ended and 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"); @@ -173,7 +184,8 @@ struct Poll { #[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. + /// are commands, or empty once `hold_ms` has passed, or empty as soon as KWin has left the bus + /// since the call was made. async fn poll(&self, args: String) -> String { let hold_ms = serde_json::from_str::(&args) .ok() @@ -181,8 +193,16 @@ impl Poll { .unwrap_or(HOLD_MS); let deadline = tokio::time::Instant::now() + Duration::from_millis(hold_ms); + let kwin = self.shared.kwin_lost.load(Ordering::SeqCst); loop { + if self.shared.kwin_lost.load(Ordering::SeqCst) != kwin { + // the script that made this call went with its KWin: the commands, and the wake-up + // that came for them, are for the script of the KWin that took its place + self.shared.wake.notify_one(); + return "[]".to_string(); + } + 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; @@ -229,7 +249,8 @@ pub struct KWinBackend { /// the desktop straight away. /// /// The connection is served by a thread of its own (`kwin-bridge-main`), which runs until the -/// daemon exits. +/// daemon exits or the session bus goes away. The same thread watches KWin on the bus, and loads +/// the script again into a KWin that has restarted. /// /// # Errors /// @@ -267,6 +288,7 @@ pub fn connect() -> eyre::Result> { queue: Mutex::new(VecDeque::new()), wake: Notify::new(), batch: AtomicU64::new(0), + kwin_lost: AtomicU64::new(0), ready: (Mutex::new(false), Condvar::new()), cursor_waiters: Mutex::new(HashMap::new()), next_token: AtomicU64::new(1), @@ -286,8 +308,7 @@ pub fn connect() -> eyre::Result> { 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; + supervise(thread_shared).await; } Err(error) => { let _ = started_tx.send(Err(error)); @@ -393,6 +414,52 @@ async fn load_script(connection: &Connection) -> eyre::Result<()> { Ok(()) } +/// Watch KWin itself. If it goes away (a crash, `kwin_wayland --replace`) its windows go with it; +/// when it is back the script has to be loaded again. +async fn supervise(shared: Arc) { + let Ok(connection) = shared.connection().await else { + return; + }; + + let Ok(dbus) = zbus::fdo::DBusProxy::new(&connection).await else { + return; + }; + let Ok(mut owner_changes) = dbus.receive_name_owner_changed().await else { + return; + }; + + while let Some(signal) = owner_changes.next().await { + let Ok(args) = signal.args() else { continue }; + if args.name().as_str() != "org.kde.KWin" { + continue; + } + + if args.new_owner().is_none() { + tracing::warn!("KWin went away; its windows are gone"); + shared.kwin_lost.fetch_add(1, Ordering::SeqCst); + let outputs = shared.table.lock().compositor_lost(Instant::now()); + shared.dispatch(outputs); + continue; + } + + tracing::info!("KWin is back; loading the bridge script again"); + let started = Instant::now(); + loop { + match load_script(&connection).await { + Ok(()) => break, + Err(error) if started.elapsed() < Duration::from_secs(15) => { + tracing::debug!("KWin is not ready for the script yet: {error}"); + tokio::time::sleep(Duration::from_millis(250)).await; + } + Err(error) => { + tracing::error!("could not load the bridge script into the new KWin: {error}"); + break; + } + } + } + } +} + /// KWin's own "Move Mouse to Focus" action: the scripting API cannot move the pointer async fn move_mouse_to_focus(shared: &Shared) -> eyre::Result<()> { let connection = shared.connection().await?; @@ -556,6 +623,7 @@ mod tests { queue: Mutex::new(VecDeque::new()), wake: Notify::new(), batch: AtomicU64::new(0), + kwin_lost: AtomicU64::new(0), ready: (Mutex::new(false), Condvar::new()), cursor_waiters: Mutex::new(HashMap::new()), next_token: AtomicU64::new(1), @@ -634,6 +702,36 @@ mod tests { assert_eq!(next_poll(&runtime, &backend), json!([])); } + /// zbus does not end a held call when its caller leaves the bus, so the `Poll` of the bridge of + /// a KWin that has gone is still waiting when the next bridge calls. Were it given the + /// commands, they would be answered to nobody and lost. + #[test] + fn a_poll_held_by_the_bridge_of_a_kwin_that_has_gone_gets_no_commands() { + let (runtime, backend) = offline(); + let poll = || { + let poll = Poll { + shared: backend.shared.clone(), + }; + async move { poll.poll(json!({ "hold_ms": 10_000 }).to_string()).await } + }; + + runtime.block_on(async { + let old = tokio::spawn(poll()); + tokio::time::sleep(Duration::from_millis(10)).await; + + // KWin leaves the bus, and the bridge of the KWin that takes its place calls + backend.shared.kwin_lost.fetch_add(1, Ordering::SeqCst); + let new = tokio::spawn(poll()); + tokio::time::sleep(Duration::from_millis(10)).await; + + backend.shared.push(json!({ "op": "cursor", "token": 1 })); + + assert_eq!(old.await.unwrap(), "[]"); + let reply: Value = serde_json::from_str(&new.await.unwrap()).unwrap(); + assert_eq!(reply[0]["cmds"], json!([{ "op": "cursor", "token": 1 }])); + }); + } + #[test] fn a_poll_with_nothing_to_send_is_answered_with_nothing_once_its_hold_is_over() { let (runtime, backend) = offline(); diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index 97c13b34..2bd92a99 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -59,6 +59,7 @@ use crate::window_manager_event::KWinNotification; use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; use serde_json::Value; +use serde_json::json; use std::collections::HashMap; use std::time::Duration; use std::time::Instant; @@ -213,6 +214,30 @@ impl Table { entry.kwin_normal } + /// KWin went away. Its windows go with it, and nothing will report them closing. + /// + /// Returns a [`WindowManagerEvent::Destroy`] for every window the window manager may manage, + /// as if each had been closed, and forgets which window has the focus. The windows stay in + /// the table as closed ones, so their ids are not given out again. A KWin that comes back + /// reports its desktop in a new snapshot. + pub fn compositor_lost(&mut self, now: Instant) -> Vec { + let ids: Vec = self + .windows + .iter() + .filter(|(_, e)| e.info.alive) + .map(|(id, _)| *id) + .collect(); + + let mut out = vec![]; + for id in ids { + let uuid = self.windows[&id].uuid.clone(); + out.extend(self.on_removed(&json!({ "id": uuid }), now)); + } + + self.foreground = None; + out + } + /// Records the frame komorebi has just asked KWin to give a window, so that the window manager /// sees it at once. The `geometry` event that says what the client did replaces it. pub fn note_requested_rect(&mut self, id: u32, rect: Rect) { @@ -516,7 +541,6 @@ fn process(pid: i32, class: &str) -> (String, String) { #[cfg(test)] mod tests { use super::*; - use serde_json::json; fn win(id: &str, desktops: &[&str]) -> Value { json!({ @@ -877,4 +901,25 @@ mod tests { "the client rounded it to its cell grid" ); } + + #[test] + fn when_kwin_goes_away_every_window_it_had_is_destroyed() { + let mut t = table(vec![win("a", &["d1"]), win("b", &["d1"])]); + t.handle(&json!({ "type": "activated", "id": "a" }), Instant::now()); + + let mut destroyed = events(&t.compositor_lost(Instant::now())); + destroyed.sort(); + assert_eq!(destroyed, vec!["Destroy 1", "Destroy 2"]); + assert_eq!(t.foreground(), None); + assert!(t.windows().is_empty()); + assert!( + t.compositor_lost(Instant::now()).is_empty(), + "a window is destroyed once" + ); + + // the windows of the KWin that comes back are new ones, with ids of their own + t.handle(&snapshot(vec![win("c", &["d1"])]), Instant::now()); + let ids: Vec = t.windows().iter().map(|w| w.id).collect(); + assert_eq!(ids, vec![3]); + } } diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index db583dbe..86bf3d22 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -202,6 +202,17 @@ class Kde: "stop", f"kwin-virtual@{self.name}.service", f"session-bus@{self.name}.service" ) + def restart_kwin(self) -> None: + """Stops the session's KWin and starts a new one, on the same bus, and waits for it. + + The bus outlives KWin, as it does when the compositor of a running session crashes or is + replaced. The clients of the old KWin go with it. + """ + self.systemctl("restart", f"kwin-virtual@{self.name}.service") + if not self.wait_for(lambda: self.has_name("org.kde.KWin"), timeout=60): + log = self.machine.execute(f"journalctl _UID={self.uid} --no-pager -n 40")[1] + raise AssertionError(f"KWin did not come back:\n{log}") + def start_komorebi(self, *args: str) -> None: """Starts the daemon in this session, with `args`, as the user unit `komorebi@NAME`. diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index 5fb407d0..2675538a 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -243,3 +243,25 @@ def test_a_session_has_the_users_data_and_config_directories_not_roots( "XDG_DATA_DIRS=/etc/profiles/per-user/komorebi/share:/run/current-system/sw/share" in words ) assert not any("/root" in word for word in words) + + +def test_restart_kwin_restarts_its_unit_alone_and_waits_for_the_new_one( + machine: FakeMachine, +) -> None: + machine.reply("busctl", status=0) + + Kde(machine, "main").restart_kwin() + + scripts = [inner(command) for command in machine.commands if " sh -c " in command] + assert scripts[0] == "systemctl --user restart kwin-virtual@main.service" + assert "busctl --user --no-pager list | grep -q '^org.kde.KWin '" in scripts[1:] + + +def test_restart_kwin_reports_the_journal_when_kwin_does_not_come_back( + machine: FakeMachine, +) -> None: + machine.reply("busctl", status=1) + machine.reply("journalctl", output="kwin: the socket is taken") + + with pytest.raises(AssertionError, match="the socket is taken"): + Kde(machine, "main", scale=0.01).restart_kwin() diff --git a/nix/tests/vm/suites/kwin-restart/default.nix b/nix/tests/vm/suites/kwin-restart/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/kwin-restart/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/kwin-restart/test.py b/nix/tests/vm/suites/kwin-restart/test.py new file mode 100644 index 00000000..eaac35a7 --- /dev/null +++ b/nix/tests/vm/suites/kwin-restart/test.py @@ -0,0 +1,131 @@ +# KWin restarts under a running daemon, as when the compositor of a session crashes or is replaced: +# the session bus stays, KWin leaves it and comes back, and the clients of the old KWin go with it. +# What only a real KWin can tell: that the daemon sees KWin go and come back on the bus, that it +# takes every window of the old KWin out of its layout, that it loads its script into the new +# KWin, and that it tiles what opens there, right away. Twice, as the spike did. +from komorebi_vm import Checks, Kde, daemon + +W, H = 1920, 1080 +# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for +CELL = 24 + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) + + +def daemon_log() -> str: + return kde.komorebi_log() + + +def loads() -> int: + """How many times the daemon has loaded its script into a KWin.""" + return daemon_log().count("loaded the KWin bridge script") + + +def where_asked(title: str) -> bool: + """KWin has the window where the daemon asked: the same place, and the size up to a cell.""" + want, wid = daemon.asked(daemon_log(), title), kde.wid(title) + if want is None or wid == "": + return False + have = kde.rect(wid) + return ( + (have.x, have.y) == (want.x, want.y) + and 0 <= want.w - have.w < CELL + and 0 <= want.h - have.h < CELL + ) + + +def open_window(title: str) -> None: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda: kde.wid(title) != "", timeout=30) + kde.wait_for(lambda: title in daemon.window_ids(daemon_log()), timeout=10) + + +def destroyed(titles: list[str]) -> bool: + """The daemon took every one of these windows out of its layout.""" + log = daemon_log() + ids = daemon.window_ids(log) + gone = {e.window for e in daemon.events(log) if e.kind == "Destroy"} + return all(ids.get(title) in gone for title in titles) + + +def alone(title: str) -> bool: + """The window is where the daemon asked, and the only one: it has the whole width.""" + return where_asked(title) and kde.rect(kde.wid(title)).w > W - 100 + + +def side_by_side(a: str, b: str) -> bool: + if not (where_asked(a) and where_asked(b)): + return False + ra, rb = kde.rect(kde.wid(a)), kde.rect(kde.wid(b)) + return not ra.overlaps(rb) and ra.w < W - 20 and rb.w < W - 20 + + +def restart(old: list[str], loaded: int) -> None: + kde.restart_kwin() + checks.check( + "the daemon saw KWin go", + kde.wait_for(lambda: "KWin went away" in daemon_log(), timeout=10), + ) + checks.check( + "every window of the old KWin left the layout", kde.wait_for(lambda: destroyed(old)) + ) + checks.check( + "the daemon loaded its script into the new KWin", + kde.wait_for(lambda: loads() == loaded, timeout=30), + ) + checks.check("the new KWin runs the script", kde.wait_for(kde.script_loaded)) + checks.check("the daemon is still running", kde.komorebi_running()) + + +print("== 1. three windows are tiled") +kde.start_komorebi("--log-level", "debug") +checks.check( + "the daemon loaded its script into KWin", kde.wait_for(lambda: loads() == 1, timeout=30) +) +before = ["pre1", "pre2", "pre3"] +for title in before: + open_window(title) +checks.check( + "every window is where the daemon asked for it", + kde.wait_for(lambda: all(where_asked(t) for t in before), timeout=20), +) + +print("== 2. KWin restarts") +restart(before, loaded=2) +checks.check("the windows of the old KWin are gone", all(kde.wid(t) == "" for t in before)) + +print("== 3. windows open in the new KWin") +open_window("post1") +checks.check("the first is tiled on its own", kde.wait_for(lambda: alone("post1"), timeout=20)) +open_window("post2") +checks.check( + "the second is tiled next to it", + kde.wait_for(lambda: side_by_side("post1", "post2"), timeout=20), +) +for title in ["post1", "post2"]: + asked = daemon.asked(daemon_log(), title) + print(f" {title}: asked {asked}, has {kde.rect(kde.wid(title))}") + +print("== 4. KWin restarts again, with one window open") +kde.close(kde.wid("post2")) +checks.check( + "the window that is left has the screen", kde.wait_for(lambda: alone("post1"), timeout=20) +) +restart(["post1"], loaded=3) +open_window("again") +checks.check( + "a window opened in the third KWin is tiled", kde.wait_for(lambda: alone("again"), timeout=20) +) + +print("== 5. 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())) + +kde.stop() +checks.finish() From 88aa78b874d79c8271c7a8ba1df84d4d498fb7b4 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 13:09:41 -0700 Subject: [PATCH 014/255] feat(wm): a command socket and the first messages Until now the daemon tiled what KWin reported and nothing else could reach it. komorebi takes its orders on a socket, as it does on Windows and on macOS: it handles no key itself, and whatever binds keys runs a command that writes a message. The daemon binds komorebi.sock in $XDG_RUNTIME_DIR/komorebi (DATA_DIR), reads one JSON SocketMessage per line on a thread per connection, and handles each message with the window manager locked, as the thread that handles events does. The first messages are the ones the first komorebic needs: State (the window manager as JSON, from state.rs), MonitorInformation, Query with a StateQuery, Retile and Stop. A question is answered on the same connection, and the answer ends when the daemon closes it. Stop unloads the bridge from KWin, removes the socket and exits; so does a stop signal. The socket is bound once the daemon is connected to KWin, so a komorebi that cannot connect, such as a second one in the same session, which the bus refuses, leaves the socket of the one that runs alone. With --fake-backend the daemon answers on its socket with no compositor at all, which is how the tests run it. komorebi-client is the other end: send_message, send_batch and send_query, and the types the messages are made of. Its doctests serve the socket themselves, tests/daemon.rs runs it against a window manager over the fake desktop, and komorebi/tests/socket.rs runs the daemon binary from its start to a Stop. --- Cargo.lock | 11 + Cargo.toml | 2 +- README.md | 16 +- deny.toml | 5 + docs/dev/ARCHITECTURE.md | 91 ++++++- docs/dev/DESIGN.md | 9 + docs/dev/PLATFORM.md | 14 +- komorebi-client/Cargo.toml | 16 ++ komorebi-client/src/lib.rs | 220 +++++++++++++++++ komorebi-client/tests/daemon.rs | 111 +++++++++ komorebi/Cargo.toml | 3 + komorebi/src/core/mod.rs | 68 ++++++ komorebi/src/desktop.rs | 15 +- komorebi/src/lib.rs | 12 +- komorebi/src/main.rs | 22 +- komorebi/src/monitor.rs | 28 +++ komorebi/src/process_command.rs | 412 ++++++++++++++++++++++++++++++++ komorebi/src/state.rs | 100 ++++++++ komorebi/src/window_manager.rs | 127 +++++++++- komorebi/tests/no_kwin.rs | 47 +++- komorebi/tests/socket.rs | 88 +++++++ komorebi/tests/wm_events.rs | 9 +- 22 files changed, 1389 insertions(+), 37 deletions(-) create mode 100644 komorebi-client/Cargo.toml create mode 100644 komorebi-client/src/lib.rs create mode 100644 komorebi-client/tests/daemon.rs create mode 100644 komorebi/src/process_command.rs create mode 100644 komorebi/src/state.rs create mode 100644 komorebi/tests/socket.rs diff --git a/Cargo.lock b/Cargo.lock index 1474f253..1b67cc30 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -975,10 +975,20 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "uuid", "version", "zbus", ] +[[package]] +name = "komorebi-client" +version = "0.1.0" +dependencies = [ + "komorebi", + "parking_lot", + "serde_json_lenient", +] + [[package]] name = "komorebi-layouts" version = "0.1.42" @@ -2086,6 +2096,7 @@ version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ + "getrandom 0.4.3", "js-sys", "serde_core", "wasm-bindgen", diff --git a/Cargo.toml b/Cargo.toml index c4bf2334..46b0675d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "2" -members = ["komorebi", "version"] +members = ["komorebi", "komorebi-client", "version"] [workspace.package] version = "0.1.0" diff --git a/README.md b/README.md index ae7bceef..72eeade3 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,12 @@ 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. +While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in +`$XDG_RUNTIME_DIR/komorebi` (the local data directory when there is no runtime +directory): a message can ask for the state of the window manager, ask which +monitor, workspace or container has the focus, retile every monitor, or stop +the daemon. [`komorebi-client`](komorebi-client) writes them. + `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 use. With [direnv](https://direnv.net), the [`.envrc`](.envrc) does it on @@ -41,7 +47,11 @@ without a checkout of the toolchain. 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. + some elements are locked in place. It answers the messages on the daemon's + socket (`core::SocketMessage`, `process_command`) and shows its state + (`state`). +- [`komorebi-client`](komorebi-client): a library that sends messages to the + daemon and reads its answers, and re-exports the types they are made of. - [`version`](version): the version string every binary reports. The layouts, which turn a work area and a number of containers into a rectangle @@ -87,6 +97,10 @@ backend and tiles them; after that it changes the model when the compositor reports that a window was shown, closed, focused, minimized or restored, and tiles the workspace in front again. +Everything else reaches the daemon as a message on its socket: one JSON +`SocketMessage` per line, handled one at a time with the window manager +locked. A message that asks a question is answered on the same connection. + ## Documentation `cargo doc --workspace --no-deps --open` builds the API documentation. diff --git a/deny.toml b/deny.toml index 8ce0cea6..71131d7a 100644 --- a/deny.toml +++ b/deny.toml @@ -34,6 +34,11 @@ crate = "komorebi" expression = "LicenseRef-Komorebi-2.0" license-files = [] +[[licenses.clarify]] +crate = "komorebi-client" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "komorebi-layouts" expression = "LicenseRef-Komorebi-2.0" diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 1583aeb4..c82ca934 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -7,8 +7,8 @@ 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, 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. +how an event about a window becomes a tile, and how a message on the daemon's socket is +answered. It grows with the code: each part of the daemon that is added has its place here. ## Vocabulary @@ -24,6 +24,10 @@ daemon that is added has its place here. number of containers into one rectangle, a **tile**, for each container. - **Event**: what the compositor reports about a window: it was shown, destroyed, given the focus, minimized or restored ([`WindowManagerEvent`]). +- **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order + (retile, stop) or a question (the state, the monitors, one [`StateQuery`]). +- **State**: the window manager's monitors, workspaces, containers and windows, and its + settings, as the daemon answers a `State` message with them ([`State`]). - **Compositor**: the program that owns the screen and the windows. On KDE Plasma it is KWin. - **Backend**: the implementation of the [`Backend`](../../komorebi/src/backend/mod.rs) @@ -154,6 +158,39 @@ and returns once the snapshot has arrived, so that the window manager reads a fu 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 command socket + +The daemon takes messages on a Unix socket, `komorebi.sock` in [`DATA_DIR`] +(`$XDG_RUNTIME_DIR/komorebi`, or the local data directory without a runtime directory). +[`WindowManager::new`] binds it, after it removes a socket file that a daemon that did not +stop cleanly left behind, and the window manager keeps the listener. The daemon connects to +KWin before it makes the window manager, so a komorebi that cannot connect, such as a second +one in the same session, whose bus refuses it `org.komorebi.Bridge`, exits before it touches +the socket of the one that is running. + +[`listen_for_commands`] starts a thread that accepts connections, and reads each connection +on a separate thread ([`read_commands_uds`]). A connection carries one [`SocketMessage`] +per line, as JSON with the variant's name in `type` and its arguments in `content`: +`{"type":"Query","content":"FocusedWorkspaceIndex"}`. Each message is handled by +[`WindowManager::process_command`] with the window manager locked, so messages are handled +one at a time. A message that waited a second for the lock is logged and dropped. + +A question is answered on the same connection: the [`State`] or the monitors as JSON, or +the answer to a [`StateQuery`] as one value in plain text. The answer has no framing; it +ends when the daemon closes the connection, which it does once it has read the last line. +A client therefore shuts down its side for writing after its message, and reads until the +end ([`send_query`]). An order is answered with nothing, and a client that sends only +orders can close the connection as soon as it has written them ([`send_message`], +[`send_batch`]). + +A message that fails (a query about the focused container when the workspace has none) is +logged, and the lines after it on that connection are not read. The client sees the +connection close with no answer. + +`Stop` ends the daemon: [`WindowManager::stop`] removes the socket, lets the backend give up +what it set up in the compositor (the KWin backend unloads the bridge), and exits with +status 0. `SIGINT` and `SIGTERM` do the same from `main.rs`, with the exit status 130. + ## The parts - [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the @@ -181,9 +218,15 @@ variables; [DESIGN.md](DESIGN.md#why-does-komorebi-run-a-script-inside-kwin) has - [`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. +- [`process_command`](../../komorebi/src/process_command.rs): the thread that listens on the + socket, and what the window manager does with each message. +- [`state`](../../komorebi/src/state.rs): the [`State`] a `State` message is answered with. +- [`komorebi-client`](../../komorebi-client/src/lib.rs): a library that writes messages on + the socket and reads the answers, for programs that talk to the daemon. - [`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. + fake with `--fake-backend`, makes the window manager, which binds the socket, loads and + tiles the desktop, starts the threads that listen on the socket and handle events, and + 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 @@ -222,6 +265,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | 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 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 | +| A komorebi that cannot connect to KWin leaves the socket of the running one alone | startup order: `main.rs` connects to KWin before [`WindowManager::new`] binds the socket | `without_kwin_komorebi_leaves_the_socket_it_finds_alone` | `--fake-backend` asks no bus, and takes the socket | | 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 | @@ -231,6 +275,9 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | The window manager sees a frame it asked for at once | framework path: the KWin backend's `set_rect` records it in the table before KWin answers | `a_requested_rect_is_visible_at_once_and_replaced_by_the_real_one` | none | | A KWin that restarts gets the bridge again, and the windows of the old one leave the layout | framework path: the connection's thread watches `NameOwnerChanged` for `org.kde.KWin`, and the table destroys every window when the name is lost | `when_kwin_goes_away_every_window_it_had_is_destroyed`, `vm-kwin-restart` | none | | After KWin restarts, the commands go to the new bridge | framework path: a `Poll` held since before KWin last left the bus is answered with nothing, and passes on the wake-up it got | `a_poll_held_by_the_bridge_of_a_kwin_that_has_gone_gets_no_commands`, `vm-kwin-restart` ("a window opened in the third KWin is tiled") | none | +| Messages are handled one at a time, and in order on one connection | framework path: [`read_commands_uds`] reads a connection line by line and handles each message with the window manager locked | `the_messages_on_one_connection_are_handled_in_order` | none | +| A socket left behind by a daemon that did not stop cleanly does not keep the next one from starting | framework path: [`WindowManager::new`] removes the file before it binds | `a_socket_file_left_behind_is_replaced` | none | +| A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | | 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, checking what KWin is asked to do for each | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a command for a window KWin no longer has is given back, and the rest are carried out` | none | @@ -276,6 +323,24 @@ A window is shown, and ends up on a tile: shortcut). 8. The index is rebuilt again, so the next event finds the window. +## One message, end to end + +A client asks for the state of the window manager: + +1. [`send_query`] connects to `komorebi.sock` in [`DATA_DIR`], writes + `{"type":"State"}`, and shuts down its side of the connection for writing. +2. The thread that [`listen_for_commands`] started accepts the connection and starts a + thread for it, which calls [`read_commands_uds`]. +3. `read_commands_uds` reads the line, parses it into [`SocketMessage`]`::State`, and locks + the window manager, waiting up to a second. +4. [`WindowManager::process_command`] makes a [`State`] from the window manager, a copy of + every monitor with its workspaces, containers and windows. Each window is serialized + with what the backend reports about it now: its frame, title, executable, class and path. +5. The state is written to the connection as pretty-printed JSON, and the index of managed + windows is rebuilt, as after every message. +6. There are no more lines, so `read_commands_uds` returns and the connection is closed. + `send_query` has read to the end, and returns the JSON. + ## Where to look in the code - [`komorebi/src/backend/mod.rs`](../../komorebi/src/backend/mod.rs): the trait. @@ -289,6 +354,10 @@ A window is shown, and ends up on a tile: offset a monitor gives the workspace it shows. - [`komorebi/src/process_event.rs`](../../komorebi/src/process_event.rs): what each event does, and the thread that handles them. +- [`komorebi/src/process_command.rs`](../../komorebi/src/process_command.rs): the socket, what + each message does, and the tests that send messages through a real socket. +- [`komorebi-client/src/lib.rs`](../../komorebi-client/src/lib.rs): the client side of the + socket. - [`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 @@ -305,6 +374,8 @@ A window is shown, and ends up on a tile: restarting under the daemon. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager driven end to end against the fake. +- [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket, + from its start to a `Stop`. [`Backend`]: ../../komorebi/src/backend/mod.rs [`WindowInfo`]: ../../komorebi/src/backend/mod.rs @@ -339,3 +410,15 @@ A window is shown, and ends up on a tile: [`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 +[`DATA_DIR`]: ../../komorebi/src/lib.rs +[`SocketMessage`]: ../../komorebi/src/core/mod.rs +[`StateQuery`]: ../../komorebi/src/core/mod.rs +[`State`]: ../../komorebi/src/state.rs +[`WindowManager::new`]: ../../komorebi/src/window_manager.rs +[`WindowManager::stop`]: ../../komorebi/src/window_manager.rs +[`WindowManager::process_command`]: ../../komorebi/src/process_command.rs +[`listen_for_commands`]: ../../komorebi/src/process_command.rs +[`read_commands_uds`]: ../../komorebi/src/process_command.rs +[`send_query`]: ../../komorebi-client/src/lib.rs +[`send_message`]: ../../komorebi-client/src/lib.rs +[`send_batch`]: ../../komorebi-client/src/lib.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index cf1a65cb..0049df8d 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -155,3 +155,12 @@ bus itself: `NameOwnerChanged` says that `org.kde.KWin` has lost its owner, and has a new one. So losing the name counts as every window closing, and getting it back as the moment to load the bridge into the new KWin, which then reports its desktop as it does at start. + +## Why does komorebi take its orders on a socket? + +komorebi responds to two things: what the compositor reports about windows, and the +messages it receives on its socket. It handles no keyboard or mouse input. Binding a key to +an action is the job of another program, which runs a command that writes a message on the +socket. This is the architecture that bspwm made popular on Linux and yabai on macOS, and +the one komorebi has on Windows and on macOS +([the design notes of komorebi for Mac](https://github.com/LGUG2Z/komorebi-for-mac/blob/master/docs/design.md)). diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 9d2a41ce..b775bc7d 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -88,10 +88,11 @@ an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a runnin #### 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. +When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it asks KWin +to unload the script and removes the socket. 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, and the socket file in the runtime directory, until the next start +replaces both or the session ends. ### A headless KWin @@ -142,6 +143,7 @@ What komorebi calls: | 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 | +| `$XDG_RUNTIME_DIR/komorebi/komorebi.sock` | the command socket | bound once the daemon is connected to KWin, after a file left there is removed; removed when the daemon stops | Without `XDG_RUNTIME_DIR` the directory is `komorebi` in the local data directory instead (see [`XDG_DATA_HOME`](#xdg_data_home)). @@ -157,11 +159,11 @@ either. An address with no bus behind it is the first error under [No KWin](#no- ### `XDG_RUNTIME_DIR` The runtime directory of the user, normally `/run/user/`: komorebi writes the bridge to -the `komorebi` directory in it. +the `komorebi` directory in it, and binds its command socket there. ### `XDG_DATA_HOME` -Read only when `XDG_RUNTIME_DIR` is not set: the bridge is then written to +Read only when `XDG_RUNTIME_DIR` is not set: the bridge and the socket then go to `$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if `XDG_DATA_HOME` is not set either). ### `RUST_LOG` diff --git a/komorebi-client/Cargo.toml b/komorebi-client/Cargo.toml new file mode 100644 index 00000000..066c69bd --- /dev/null +++ b/komorebi-client/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "komorebi-client" +version.workspace = true +edition = "2024" + +[dependencies] +komorebi = { path = "../komorebi", default-features = false } + +serde_json = { workspace = true } + +[dev-dependencies] +parking_lot = "0.12" + +[features] +default = ["schemars"] +schemars = ["komorebi/default"] diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs new file mode 100644 index 00000000..5ac831fa --- /dev/null +++ b/komorebi-client/src/lib.rs @@ -0,0 +1,220 @@ +//! A client for the komorebi daemon: it writes [`SocketMessage`]s on the daemon's socket and reads +//! the daemon's answers. +//! +//! The daemon listens on `komorebi.sock` in [`struct@DATA_DIR`], which is +//! `$XDG_RUNTIME_DIR/komorebi` in a desktop session. Every function here opens a new connection +//! and writes each message as one line of JSON. [`send_message`] and [`send_batch`] give +//! orders and read nothing back; [`send_query`] asks a question and returns the answer, which the +//! daemon ends by closing the connection. A function fails with the error of the connection, so a +//! daemon that is not running is an [`std::io::ErrorKind::NotFound`] or a +//! [`std::io::ErrorKind::ConnectionRefused`]. +//! +//! The crate also re-exports the types the messages and the answers are made of, so that a client +//! needs nothing else. +//! +//! # Example +//! +//! The examples on this page answer for the daemon: each one listens on the socket itself, in a +//! runtime directory made for it, before it sends anything. +//! +//! ```rust +//! # use std::io::{BufRead, BufReader, Write}; +//! # let runtime = format!("/tmp/komorebi-client-doc-crate-{}", std::process::id()); +//! # std::fs::create_dir_all(format!("{runtime}/komorebi"))?; +//! # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it +//! # let socket = komorebi_client::DATA_DIR.join("komorebi.sock"); +//! # let listener = std::os::unix::net::UnixListener::bind(&socket)?; +//! # let daemon = std::thread::spawn(move || -> std::io::Result { +//! # let (mut stream, _) = listener.accept()?; +//! # let mut line = String::new(); +//! # BufReader::new(stream.try_clone()?).read_line(&mut line)?; +//! # stream.write_all(b"2")?; +//! # Ok(line) +//! # }); +//! use komorebi_client::SocketMessage; +//! use komorebi_client::StateQuery; +//! use komorebi_client::send_query; +//! +//! let workspace = send_query(&SocketMessage::Query(StateQuery::FocusedWorkspaceIndex))?; +//! assert_eq!(workspace, "2"); +//! +//! # assert_eq!( +//! # daemon.join().unwrap()?, +//! # r#"{"type":"Query","content":"FocusedWorkspaceIndex"}"# +//! # ); +//! # std::fs::remove_dir_all(&runtime)?; +//! # Ok::<(), Box>(()) +//! ``` +//! +//! `komorebi-client/tests/daemon.rs` sends the same messages to a window manager that listens the +//! way the daemon does, over an in-memory desktop. + +pub use komorebi::DATA_DIR; +pub use komorebi::container::Container; +pub use komorebi::core::ApplicationIdentifier; +pub use komorebi::core::Axis; +pub use komorebi::core::CycleDirection; +pub use komorebi::core::DefaultLayout; +pub use komorebi::core::FocusFollowsMouseImplementation; +pub use komorebi::core::Layout; +pub use komorebi::core::MonocleFocusBehaviour; +pub use komorebi::core::MoveBehaviour; +pub use komorebi::core::OperationBehaviour; +pub use komorebi::core::OperationDirection; +pub use komorebi::core::Rect; +pub use komorebi::core::Sizing; +pub use komorebi::core::SocketMessage; +pub use komorebi::core::StateQuery; +pub use komorebi::core::WindowKind; +pub use komorebi::core::pathext::PathExt; +pub use komorebi::core::pathext::replace_env_in_path; +pub use komorebi::state::State; +pub use komorebi::window::Window; +pub use komorebi::workspace::Workspace; +use std::borrow::Borrow; +use std::io::BufReader; +use std::io::Read; +use std::io::Write; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; +use std::time::Duration; + +const KOMOREBI: &str = "komorebi.sock"; + +/// Sends one message to the daemon, and does not wait for it to be handled +/// +/// # Errors +/// +/// - The daemon's socket cannot be connected to, for example because the daemon is not running. +/// - The message cannot be written within a second. +/// +/// # Example +/// +/// ```rust +/// # use std::io::{BufRead, BufReader}; +/// # let runtime = format!("/tmp/komorebi-client-doc-message-{}", std::process::id()); +/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?; +/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it +/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock"); +/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?; +/// # let daemon = std::thread::spawn(move || -> std::io::Result { +/// # let (stream, _) = listener.accept()?; +/// # let mut line = String::new(); +/// # BufReader::new(stream).read_line(&mut line)?; +/// # Ok(line) +/// # }); +/// use komorebi_client::SocketMessage; +/// use komorebi_client::send_message; +/// +/// send_message(&SocketMessage::Retile)?; +/// +/// # assert_eq!(daemon.join().unwrap()?, r#"{"type":"Retile"}"#); +/// # std::fs::remove_dir_all(&runtime)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn send_message(message: &SocketMessage) -> std::io::Result<()> { + let socket = DATA_DIR.join(KOMOREBI); + let mut stream = UnixStream::connect(socket)?; + stream.set_write_timeout(Some(Duration::from_secs(1)))?; + stream.write_all(serde_json::to_string(message)?.as_bytes()) +} + +/// Sends several messages to the daemon on one connection, which handles them in order, and does +/// not wait for them to be handled +/// +/// # Errors +/// +/// The same as [`send_message`]. +/// +/// # Example +/// +/// ```rust +/// # use std::io::{BufRead, BufReader}; +/// # let runtime = format!("/tmp/komorebi-client-doc-batch-{}", std::process::id()); +/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?; +/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it +/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock"); +/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?; +/// # let daemon = std::thread::spawn(move || -> std::io::Result> { +/// # let (stream, _) = listener.accept()?; +/// # BufReader::new(stream).lines().collect() +/// # }); +/// use komorebi_client::SocketMessage; +/// use komorebi_client::send_batch; +/// +/// send_batch([SocketMessage::Retile, SocketMessage::Stop])?; +/// +/// # assert_eq!(daemon.join().unwrap()?, [r#"{"type":"Retile"}"#, r#"{"type":"Stop"}"#]); +/// # std::fs::remove_dir_all(&runtime)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn send_batch(messages: impl IntoIterator) -> std::io::Result<()> +where + Q: Borrow, +{ + let socket = DATA_DIR.join(KOMOREBI); + let mut stream = UnixStream::connect(socket)?; + stream.set_write_timeout(Some(Duration::from_secs(1)))?; + let msgs = messages.into_iter().fold(String::new(), |mut s, m| { + if let Ok(m_str) = serde_json::to_string(m.borrow()) { + s.push_str(&m_str); + s.push('\n'); + } + s + }); + stream.write_all(msgs.as_bytes()) +} + +/// Sends one message to the daemon and returns its answer: JSON for +/// [`SocketMessage::State`] and [`SocketMessage::MonitorInformation`], one value as text for +/// [`SocketMessage::Query`], and nothing for a message that is not a question +/// +/// # Errors +/// +/// - The daemon's socket cannot be connected to, for example because the daemon is not running. +/// - The message cannot be written within a second. +/// - The daemon sends nothing for a second before its answer is complete. +/// +/// # Example +/// +/// The answer to [`SocketMessage::State`] reads back as a [`State`]: +/// +/// ```rust +/// # use std::io::{BufRead, BufReader, Write}; +/// # let runtime = format!("/tmp/komorebi-client-doc-query-{}", std::process::id()); +/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?; +/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it +/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock"); +/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?; +/// # let daemon = std::thread::spawn(move || -> std::io::Result<()> { +/// # let (mut stream, _) = listener.accept()?; +/// # BufReader::new(stream.try_clone()?).read_line(&mut String::new())?; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # stream.write_all(state.as_bytes()) +/// # }); +/// use komorebi_client::SocketMessage; +/// use komorebi_client::State; +/// use komorebi_client::send_query; +/// +/// let state: State = serde_json::from_str(&send_query(&SocketMessage::State)?)?; +/// assert!(state.mouse_follows_focus); +/// +/// # daemon.join().unwrap()?; +/// # std::fs::remove_dir_all(&runtime)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn send_query(message: &SocketMessage) -> std::io::Result { + let socket = DATA_DIR.join(KOMOREBI); + + let mut stream = UnixStream::connect(socket)?; + stream.set_read_timeout(Some(Duration::from_secs(1)))?; + stream.set_write_timeout(Some(Duration::from_secs(1)))?; + stream.write_all(serde_json::to_string(message)?.as_bytes())?; + stream.shutdown(Shutdown::Write)?; + + let mut reader = BufReader::new(stream); + let mut response = String::new(); + reader.read_to_string(&mut response)?; + + Ok(response) +} diff --git a/komorebi-client/tests/daemon.rs b/komorebi-client/tests/daemon.rs new file mode 100644 index 00000000..434bf5d5 --- /dev/null +++ b/komorebi-client/tests/daemon.rs @@ -0,0 +1,111 @@ +//! The client against a window manager that listens the way the daemon does, with +//! [`listen_for_commands`], over an in-memory desktop with one monitor and two windows. +//! +//! The tests share the window manager, and its socket in a runtime directory of this process. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::set_backend; +use komorebi::core::Rect; +use komorebi::process_command::listen_for_commands; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event_listener; +use komorebi_client::DATA_DIR; +use komorebi_client::SocketMessage; +use komorebi_client::State; +use komorebi_client::StateQuery; +use komorebi_client::send_batch; +use komorebi_client::send_message; +use komorebi_client::send_query; +use parking_lot::Mutex; +use std::sync::Arc; +use std::sync::OnceLock; +use std::time::Duration; +use std::time::Instant; + +/// Starts the window manager once, with the windows 801 and 802 open, and returns the desktop +fn daemon() -> Arc { + static FAKE: OnceLock> = OnceLock::new(); + + FAKE.get_or_init(|| { + // /tmp: short enough for a unix socket path on macOS + let runtime = format!("/tmp/komorebi-client-test-{}", std::process::id()); + // SAFETY: the first test to get here sets it, before any thread reads the environment + unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; + std::fs::create_dir_all(&*DATA_DIR).unwrap(); + + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.open_window(801, "foot", "foot", "first"); + fake.open_window(802, "foot", "foot", "second"); + set_backend(fake.clone()); + + let mut wm = WindowManager::new(window_manager_event_listener::event_rx(), None).unwrap(); + wm.init().unwrap(); + wm.retile_all().unwrap(); + listen_for_commands(Arc::new(Mutex::new(wm))); + + fake + }) + .clone() +} + +/// Waits up to five seconds for `done`, since a message that is sent is handled on another thread +fn eventually(done: impl Fn() -> bool) -> bool { + let started = Instant::now(); + while started.elapsed() < Duration::from_secs(5) { + if done() { + return true; + } + std::thread::sleep(Duration::from_millis(10)); + } + false +} + +#[test] +fn the_state_reads_back_as_the_window_managers_state() -> Result<(), Box> { + daemon(); + + let state: State = serde_json::from_str(&send_query(&SocketMessage::State)?)?; + + let workspace = &state.monitors.elements()[0].workspaces()[0]; + let windows = workspace + .containers() + .iter() + .flat_map(|container| container.windows().iter().map(|window| window.id)) + .collect::>(); + assert_eq!(windows, [801, 802]); + Ok(()) +} + +#[test] +fn a_query_is_answered_with_one_value() -> Result<(), Box> { + daemon(); + + let kind = send_query(&SocketMessage::Query(StateQuery::FocusedContainerKind))?; + let layout = send_query(&SocketMessage::Query(StateQuery::FocusedWorkspaceLayout))?; + + assert_eq!(kind, "Single"); + assert_eq!(layout, "BSP"); + Ok(()) +} + +#[test] +fn a_retile_puts_a_window_moved_by_hand_back_on_its_tile() -> Result<(), Box> +{ + let fake = daemon(); + let tile = fake.rect_of(802); + let elsewhere = Rect { + left: 300, + top: 300, + right: 400, + bottom: 400, + }; + + fake.move_window_by_user(802, elsewhere); + send_message(&SocketMessage::Retile)?; + assert!(eventually(|| fake.rect_of(802) == tile)); + + fake.move_window_by_user(802, elsewhere); + send_batch(vec![SocketMessage::Retile; 2])?; + assert!(eventually(|| fake.rect_of(802) == tile)); + Ok(()) +} diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index d419f055..fb152296 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -28,6 +28,9 @@ tracing-subscriber = { workspace = true } zbus = { version = "5", default-features = false, features = ["tokio"] } futures-util = "0.3" +[dev-dependencies] +uuid = { version = "1", features = ["v4"] } + [features] default = ["schemars"] deadlock_detection = ["parking_lot/deadlock_detection"] diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index a3e0c917..91d37c9b 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -5,10 +5,15 @@ //! those of `komorebi-layouts`, re-exported here so that the rest of the crate has one place to //! import from. [`pathext`] resolves environment variables in configured paths and //! [`config_generation`] holds the rules that match applications by what they are called. +//! +//! [`SocketMessage`] is every message the daemon takes on its socket, and [`StateQuery`] every +//! question [`SocketMessage::Query`] can ask. use clap::ValueEnum; +use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; +use std::str::FromStr; use strum::Display; use strum::EnumString; @@ -252,3 +257,66 @@ pub enum WindowKind { UnfocusedLocked, Floating, } + +/// A question about the window manager that [`SocketMessage::Query`] asks, answered with one +/// value as text: an index, the name of a layout or of a container kind, or the version of the +/// daemon. +#[derive(Copy, Clone, Debug, Serialize, Deserialize, Display, EnumString, ValueEnum)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum StateQuery { + FocusedMonitorIndex, + FocusedWorkspaceIndex, + FocusedContainerIndex, + FocusedWindowIndex, + FocusedWorkspaceLayout, + FocusedContainerKind, + Version, +} + +/// A message to the daemon, as it is written on its socket: JSON, with the variant's name in +/// `type` and its arguments, if it has any, in `content`. +/// +/// # Example +/// +/// ```rust +/// use komorebi::core::SocketMessage; +/// use komorebi::core::StateQuery; +/// +/// let query = SocketMessage::Query(StateQuery::FocusedWorkspaceIndex); +/// assert_eq!( +/// String::from_utf8(query.as_bytes()?)?, +/// r#"{"type":"Query","content":"FocusedWorkspaceIndex"}"#, +/// ); +/// +/// let stop: SocketMessage = r#"{"type":"Stop"}"#.parse()?; +/// assert!(matches!(stop, SocketMessage::Stop)); +/// +/// # Ok::<(), Box>(()) +/// ``` +// serde_as must be before derive +#[serde_with::serde_as] +#[derive(Clone, Debug, Serialize, Deserialize, Display)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(tag = "type", content = "content")] +pub enum SocketMessage { + Stop, + Retile, + State, + MonitorInformation, + Query(StateQuery), +} + +impl SocketMessage { + /// Returns the message as JSON, the way the daemon reads it from its socket + pub fn as_bytes(&self) -> eyre::Result> { + Ok(serde_json::to_string(self)?.as_bytes().to_vec()) + } +} + +impl FromStr for SocketMessage { + type Err = serde_json::Error; + + fn from_str(s: &str) -> Result { + serde_json::from_str(s) + } +} diff --git a/komorebi/src/desktop.rs b/komorebi/src/desktop.rs index a7af3f01..65eee012 100644 --- a/komorebi/src/desktop.rs +++ b/komorebi/src/desktop.rs @@ -8,6 +8,7 @@ //! # Example //! //! ```rust +//! use std::path::PathBuf; //! use std::sync::Arc; //! //! use komorebi::backend::fake::FakeBackend; @@ -20,7 +21,8 @@ //! fake.open_window(1, "foot", "foot", "a terminal"); //! //! let (_sender, events) = crossbeam_channel::bounded(1); -//! let mut wm = WindowManager::new(events)?; +//! let socket = PathBuf::from(format!("/tmp/komorebi-desktop-doc-{}.sock", std::process::id())); +//! let mut wm = WindowManager::new(events, Some(socket.clone()))?; //! with_backend(fake, || { //! load_monitor_information(&mut wm)?; //! load_workspace_information(&mut wm) @@ -28,6 +30,7 @@ //! //! assert_eq!(wm.monitors().len(), 1); //! assert!(wm.focused_workspace()?.contains_window(1)); +//! # std::fs::remove_file(socket)?; //! # Ok::<(), color_eyre::eyre::Report>(()) //! ``` @@ -96,6 +99,7 @@ pub fn latest_monitor_information() -> eyre::Result> { /// # Example /// /// ```rust +/// use std::path::PathBuf; /// use std::sync::Arc; /// /// use komorebi::backend::fake::FakeBackend; @@ -105,7 +109,8 @@ pub fn latest_monitor_information() -> eyre::Result> { /// /// let fake = Arc::new(FakeBackend::with_one_monitor()); /// let (_sender, events) = crossbeam_channel::bounded(1); -/// let mut wm = WindowManager::new(events)?; +/// let socket = PathBuf::from(format!("/tmp/komorebi-monitors-doc-{}.sock", std::process::id())); +/// let mut wm = WindowManager::new(events, Some(socket.clone()))?; /// /// with_backend(fake, || { /// load_monitor_information(&mut wm)?; @@ -113,6 +118,7 @@ pub fn latest_monitor_information() -> eyre::Result> { /// })?; /// /// assert_eq!(wm.monitors().len(), 1); +/// # std::fs::remove_file(socket)?; /// # Ok::<(), color_eyre::eyre::Report>(()) /// ``` #[tracing::instrument(skip_all)] @@ -148,6 +154,7 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { /// # Example /// /// ```rust +/// use std::path::PathBuf; /// use std::sync::Arc; /// /// use komorebi::backend::fake::FakeBackend; @@ -162,7 +169,8 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { /// fake.set_normal(2, false); /// /// let (_sender, events) = crossbeam_channel::bounded(1); -/// let mut wm = WindowManager::new(events)?; +/// let socket = PathBuf::from(format!("/tmp/komorebi-windows-doc-{}.sock", std::process::id())); +/// let mut wm = WindowManager::new(events, Some(socket.clone()))?; /// with_backend(fake, || { /// load_monitor_information(&mut wm)?; /// load_workspace_information(&mut wm) @@ -171,6 +179,7 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { /// let workspace = wm.focused_workspace()?; /// assert!(workspace.contains_window(1)); /// assert!(!workspace.contains_window(2)); +/// # std::fs::remove_file(socket)?; /// # Ok::<(), color_eyre::eyre::Report>(()) /// ``` #[tracing::instrument(skip_all)] diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index ac675ddd..6a1b14a5 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -12,6 +12,10 @@ //! [`window_manager_event_listener`]. //! //! On KDE Plasma the backend is [`kwin::KWinBackend`], which talks to a script it loads into KWin. +//! +//! The daemon also listens on a socket, `komorebi.sock` in [`struct@DATA_DIR`], for the messages +//! in [`core::SocketMessage`]: [`process_command`] reads them and answers, with the window +//! manager's [`state::State`] for one. use color_eyre::eyre; use lazy_static::lazy_static; @@ -28,7 +32,9 @@ pub mod desktop; pub mod kwin; pub mod lockable_sequence; pub mod monitor; +pub mod process_command; pub mod process_event; +pub mod state; pub mod window; pub mod window_manager; pub mod window_manager_event; @@ -41,9 +47,9 @@ 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. + /// KWin and its command socket: `$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")) diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index fe9d0065..7ab2e5ec 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -6,15 +6,18 @@ //! 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`. +//! daemon then loads the monitors and the windows that are open, tiles them, listens for +//! messages on `komorebi.sock` in [`struct@DATA_DIR`], handles the events the backend reports on +//! a thread of their own, and runs until it is stopped, with `SIGINT`, `SIGTERM` or a `Stop` +//! message. use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; +use komorebi::DATA_DIR; use komorebi::backend; use komorebi::backend::fake::FakeBackend; +use komorebi::process_command::listen_for_commands; use komorebi::process_event::listen_for_events; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event_listener; @@ -118,8 +121,8 @@ 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 instead of KWin, for development and testing. Windows - /// and monitors are not real. + /// Run against an in-memory desktop instead of KWin, for development and testing of the + /// socket interface. Windows and monitors are not real. #[clap(long, hide = true)] fake_backend: bool, } @@ -128,6 +131,10 @@ fn main() -> eyre::Result<()> { let opts: Opts = Opts::parse(); setup(opts.log_level)?; + if !DATA_DIR.is_dir() { + std::fs::create_dir_all(&*DATA_DIR)?; + } + if opts.fake_backend { tracing::warn!("running against an in-memory desktop; nothing here is a real window"); backend::set_backend(Arc::new(FakeBackend::with_one_monitor())); @@ -141,11 +148,13 @@ fn main() -> eyre::Result<()> { let wm = Arc::new(Mutex::new(WindowManager::new( window_manager_event_listener::event_rx(), + None, )?)); wm.lock().init()?; wm.lock().retile_all()?; + listen_for_commands(wm.clone()); listen_for_events(wm.clone()); let (quit_sender, quit_receiver) = std::sync::mpsc::channel(); @@ -160,5 +169,8 @@ fn main() -> eyre::Result<()> { backend::backend().shutdown(); + let socket = DATA_DIR.join("komorebi.sock"); + let _ = std::fs::remove_file(socket); + std::process::exit(130); } diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index e672748a..6bfa64a6 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -9,6 +9,7 @@ use crate::DEFAULT_CONTAINER_PADDING; use crate::DEFAULT_WORKSPACE_PADDING; use crate::container::Container; +use crate::core::Layout; use crate::core::Rect; use crate::ring::Ring; use crate::workspace::Workspace; @@ -20,6 +21,27 @@ use serde::Serialize; use std::collections::VecDeque; use std::sync::atomic::Ordering; +/// A monitor's identity and bounds, as the daemon answers +/// [`SocketMessage::MonitorInformation`](crate::core::SocketMessage::MonitorInformation) with them +#[derive(Debug, Serialize, Deserialize)] +pub struct MonitorInformation { + pub id: u32, + pub device: String, + pub serial_number_id: String, + pub size: Rect, +} + +impl From<&Monitor> for MonitorInformation { + fn from(value: &Monitor) -> Self { + Self { + id: value.id, + device: value.device.clone(), + serial_number_id: value.serial_number_id.clone(), + size: value.size, + } + } +} + impl_ring_elements!(Monitor, Workspace); #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -164,6 +186,12 @@ impl Monitor { .resize(ensure_count, Workspace::default()); } } + + /// The layout of the focused workspace, if the monitor has one + pub fn focused_workspace_layout(&self) -> Option { + self.focused_workspace() + .map(|workspace| workspace.layout.clone()) + } } #[cfg(test)] diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs new file mode 100644 index 00000000..37759873 --- /dev/null +++ b/komorebi/src/process_command.rs @@ -0,0 +1,412 @@ +//! How the daemon answers the messages on its socket: [`listen_for_commands`] and +//! [`WindowManager::process_command`]. +//! +//! A client connects to `komorebi.sock` in [`struct@DATA_DIR`](crate::DATA_DIR) and writes one +//! [`SocketMessage`] as JSON per line. Each connection is read on a separate thread, and each +//! message is handled with the window manager locked. A message that asks a question is answered +//! on the same connection, and the answer ends when the daemon closes it: +//! +//! - **State**: the window manager's [`State`], as JSON. +//! - **MonitorInformation**: the id, the name and the bounds of each monitor, as JSON. +//! - **Query**: one value as text, the answer to a [`StateQuery`]. +//! +//! The others answer nothing: **Retile** tiles the focused workspace of every monitor again, and +//! **Stop** stops the daemon ([`WindowManager::stop`]). + +use crate::core::Layout; +use crate::core::SocketMessage; +use crate::core::StateQuery; +use crate::monitor::MonitorInformation; +use crate::state::State; +use crate::window_manager::WindowManager; +use color_eyre::eyre; +use color_eyre::eyre::OptionExt; +use parking_lot::Mutex; +use std::io::BufRead; +use std::io::BufReader; +use std::os::unix::net::UnixStream; +use std::str::FromStr; +use std::sync::Arc; +use std::time::Duration; +use version::build; + +/// Starts the thread that accepts connections on the window manager's +/// [`command_listener`](WindowManager::command_listener), and reads each connection on a separate +/// thread ([`read_commands_uds`]) +/// +/// When accepting fails, the error is logged and the listening thread is started again. +#[tracing::instrument] +pub fn listen_for_commands(wm: Arc>) { + std::thread::spawn(move || { + loop { + let wm = wm.clone(); + + let _ = std::thread::spawn(move || { + let listener = wm + .lock() + .command_listener + .try_clone() + .expect("could not clone unix listener"); + + tracing::info!("listening on komorebi.sock"); + for client in listener.incoming() { + match client { + Ok(stream) => { + let wm_clone = wm.clone(); + std::thread::spawn(move || { + match read_commands_uds(&wm_clone, stream) { + Ok(()) => {} + Err(error) => { + tracing::error!("{error}") + } + } + }); + } + Err(error) => { + tracing::error!("failed to get unix stream {}", error); + break; + } + } + } + }) + .join(); + + tracing::error!("restarting failed thread"); + } + }); +} + +impl WindowManager { + /// Handles one message, and writes the answer to a question to `reply` + /// + /// # Errors + /// + /// - A query about the focused monitor, workspace or container when there is none. + /// - The window manager fails to retile, for one of the reasons + /// [`WindowManager::retile_all`] gives. + /// - The answer cannot be written to `reply`. + #[tracing::instrument(skip(self, reply, message))] + pub fn process_command( + &mut self, + message: SocketMessage, + mut reply: impl std::io::Write, + ) -> eyre::Result<()> { + tracing::info!("processing command: {message}"); + + match message { + SocketMessage::Retile => self.retile_all()?, + SocketMessage::State => { + let state = match serde_json::to_string_pretty(&State::from(&*self)) { + Ok(state) => state, + Err(error) => error.to_string(), + }; + + tracing::info!("replying to state"); + + reply.write_all(state.as_bytes())?; + + tracing::info!("replying to state done"); + } + SocketMessage::MonitorInformation => { + let mut monitors = vec![]; + for monitor in self.monitors() { + monitors.push(MonitorInformation::from(monitor)); + } + + let monitors_state = serde_json::to_string_pretty(&monitors) + .unwrap_or_else(|error| error.to_string()); + + reply.write_all(monitors_state.as_bytes())?; + } + SocketMessage::Query(query) => { + let response = match query { + StateQuery::FocusedMonitorIndex => self.focused_monitor_idx().to_string(), + StateQuery::FocusedWorkspaceIndex => self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx() + .to_string(), + StateQuery::FocusedContainerIndex => self + .focused_workspace()? + .focused_container_idx() + .to_string(), + StateQuery::FocusedWindowIndex => { + self.focused_container()?.focused_window_idx().to_string() + } + StateQuery::Version => build::VERSION.to_string(), + StateQuery::FocusedWorkspaceLayout => { + let focused_monitor = + self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor.focused_workspace_layout().map_or_else( + || "None".to_string(), + |layout| match layout { + Layout::Default(default_layout) => default_layout.to_string(), + }, + ) + } + StateQuery::FocusedContainerKind => { + match self.focused_workspace()?.focused_container() { + None => "None".to_string(), + Some(container) => { + if container.windows().len() > 1 { + "Stack".to_string() + } else { + "Single".to_string() + } + } + } + } + }; + + reply.write_all(response.as_bytes())?; + } + SocketMessage::Stop => { + self.stop()?; + } + } + + self.update_known_window_ids(); + + tracing::info!("processed command: {message}"); + + Ok(()) + } +} + +/// Reads the messages on one connection, one per line, and hands each to +/// [`WindowManager::process_command`] with the connection to answer on +/// +/// A message that arrives while the window manager has been locked for a second is logged and +/// dropped. +/// +/// # Errors +/// +/// - The connection cannot be read, or cloned to be read and written at once. +/// - A line is not a [`SocketMessage`]: the lines after it are not read. +/// - [`WindowManager::process_command`] fails: the lines after it are not read. +pub fn read_commands_uds( + wm: &Arc>, + mut stream: UnixStream, +) -> eyre::Result<()> { + let reader = BufReader::new(stream.try_clone()?); + // TODO(raggi): while this processes more than one command, if there are + // replies there is no clearly defined protocol for framing yet - it's + // perhaps whole-json objects for now, but termination is signalled by + // socket shutdown. + for line in reader.lines() { + let message = SocketMessage::from_str(&line?)?; + + match wm.try_lock_for(Duration::from_secs(1)) { + None => { + tracing::warn!( + "could not acquire window manager lock, not processing message: {message}" + ); + } + Some(mut wm) => { + wm.process_command(message.clone(), &mut stream)?; + } + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend::fake::FakeBackend; + use crate::backend::with_backend; + use crate::core::Rect; + use std::io::Read; + use std::io::Write; + use std::net::Shutdown; + use std::path::PathBuf; + use uuid::Uuid; + + /// A window manager over `fake`, listening on a socket for this test alone in /tmp, which is + /// short enough for a unix socket path on macOS. The socket is removed when the test is done. + struct Daemon { + fake: Arc, + wm: Arc>, + socket: PathBuf, + } + + impl Drop for Daemon { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.socket); + } + } + + impl Daemon { + fn new(fake: FakeBackend) -> Self { + let fake = Arc::new(fake); + let socket = PathBuf::from(format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4())); + + let (_sender, events) = crossbeam_channel::bounded(1); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(events, Some(socket.clone())).unwrap(); + wm.init().unwrap(); + wm + }); + + Self { + fake, + wm: Arc::new(Mutex::new(wm)), + socket, + } + } + + /// Writes `lines` on a new connection, has the window manager read the connection the + /// way the daemon does, and returns what it wrote back + fn send(&self, lines: &str) -> eyre::Result { + let mut client = UnixStream::connect(&self.socket)?; + client.write_all(lines.as_bytes())?; + client.shutdown(Shutdown::Write)?; + + // the client reads on another thread, so that an answer bigger than the + // socket's buffer does not block the window manager writing it + let reading = std::thread::spawn(move || { + let mut reply = String::new(); + client.read_to_string(&mut reply).map(|_| reply) + }); + + let (stream, _) = self.wm.lock().command_listener.accept()?; + let handled = with_backend(self.fake.clone(), || read_commands_uds(&self.wm, stream)); + + let reply = reading.join().expect("the client does not panic")?; + handled.map(|()| reply) + } + + fn ask(&self, message: SocketMessage) -> eyre::Result { + self.send(&serde_json::to_string(&message)?) + } + } + + fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect { + Rect { + left, + top, + right, + bottom, + } + } + + fn two_windows(first: u32) -> FakeBackend { + let fake = FakeBackend::with_one_monitor(); + fake.open_window(first, "foot", "foot", "first"); + fake.open_window(first + 1, "foot", "foot", "second"); + fake + } + + #[test] + fn the_state_has_every_window_of_every_workspace() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(701)); + + let state: serde_json::Value = serde_json::from_str(&daemon.ask(SocketMessage::State)?)?; + + let windows = &state["monitors"]["elements"][0]["workspaces"]["elements"][0]["containers"] + ["elements"]; + assert_eq!(windows[0]["windows"]["elements"][0]["id"], 701); + assert_eq!(windows[1]["windows"]["elements"][0]["id"], 702); + assert_eq!( + windows[1]["windows"]["elements"][0]["details"]["title"], + "second" + ); + assert_eq!(state["mouse_follows_focus"], true); + Ok(()) + } + + #[test] + fn monitor_information_names_each_monitor_and_its_bounds() -> eyre::Result<()> { + let fake = FakeBackend::with_one_monitor(); + fake.add_monitor( + 2, + "Virtual-1", + rect(1920, 0, 1920, 1080), + rect(1920, 0, 1920, 1080), + ); + let daemon = Daemon::new(fake); + + let monitors: serde_json::Value = + serde_json::from_str(&daemon.ask(SocketMessage::MonitorInformation)?)?; + + assert_eq!(monitors.as_array().map(Vec::len), Some(2)); + assert_eq!(monitors[1]["id"], 2); + assert_eq!(monitors[1]["device"], "Virtual-1"); + assert_eq!(monitors[1]["size"]["left"], 1920); + assert_eq!(monitors[0]["size"]["right"], 1920); + Ok(()) + } + + #[test] + fn a_query_is_answered_with_one_value() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(711)); + let query = |query| daemon.ask(SocketMessage::Query(query)); + + assert_eq!(query(StateQuery::FocusedMonitorIndex)?, "0"); + assert_eq!(query(StateQuery::FocusedWorkspaceIndex)?, "0"); + assert_eq!(query(StateQuery::FocusedContainerIndex)?, "0"); + assert_eq!(query(StateQuery::FocusedWindowIndex)?, "0"); + assert_eq!(query(StateQuery::FocusedWorkspaceLayout)?, "BSP"); + assert_eq!(query(StateQuery::FocusedContainerKind)?, "Single"); + // the version is shadow-rs's description of the build, the package version first + let version = format!("pkg_version:{}", env!("CARGO_PKG_VERSION")); + assert!(query(StateQuery::Version)?.contains(&version)); + Ok(()) + } + + #[test] + fn a_query_about_a_container_on_an_empty_workspace_is_an_error() { + let daemon = Daemon::new(FakeBackend::with_one_monitor()); + + let answer = daemon.ask(SocketMessage::Query(StateQuery::FocusedWindowIndex)); + + assert_eq!( + answer.map_err(|error| error.to_string()), + Err(String::from("there is no container")) + ); + } + + #[test] + fn retile_puts_a_window_moved_by_hand_back_on_its_tile() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(721)); + daemon.ask(SocketMessage::Retile)?; + let tile = daemon.fake.rect_of(721); + + daemon + .fake + .move_window_by_user(721, rect(300, 300, 400, 400)); + assert_ne!(daemon.fake.rect_of(721), tile); + + assert_eq!(daemon.ask(SocketMessage::Retile)?, ""); + assert_eq!(daemon.fake.rect_of(721), tile); + Ok(()) + } + + #[test] + fn the_messages_on_one_connection_are_handled_in_order() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(731)); + daemon + .fake + .move_window_by_user(731, rect(300, 300, 400, 400)); + + let reply = daemon.send( + "{\"type\":\"Retile\"}\n{\"type\":\"Query\",\"content\":\"FocusedContainerKind\"}\n", + )?; + + assert_eq!(reply, "Single"); + assert_ne!(daemon.fake.rect_of(731), Some(rect(300, 300, 400, 400))); + Ok(()) + } + + #[test] + fn a_line_that_is_not_a_message_is_an_error() { + let daemon = Daemon::new(FakeBackend::with_one_monitor()); + + let reply = daemon.send("{\"type\":\"Nonsense\"}\n"); + + assert!(reply.is_err()); + } +} diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs new file mode 100644 index 00000000..885dc280 --- /dev/null +++ b/komorebi/src/state.rs @@ -0,0 +1,100 @@ +//! [`State`], the window manager as the daemon shows it: every monitor, with its workspaces, their +//! containers and the windows in them, and the settings that apply to all of them. +//! +//! The daemon writes it as JSON in answer to [`SocketMessage::State`]. +//! +//! [`SocketMessage::State`]: crate::core::SocketMessage::State + +use crate::core::Rect; +use crate::monitor::Monitor; +use crate::ring::Ring; +use crate::window_manager::WindowManager; +use crate::workspace::Workspace; +use serde::Deserialize; +use serde::Serialize; +use std::collections::VecDeque; + +/// A copy of the window manager's monitors, with their workspaces, containers and windows, and +/// of its settings, which serializes to JSON +/// +/// # Example +/// +/// ```rust +/// use std::path::PathBuf; +/// use std::sync::Arc; +/// +/// use komorebi::backend::fake::FakeBackend; +/// use komorebi::backend::with_backend; +/// use komorebi::state::State; +/// use komorebi::window_manager::WindowManager; +/// +/// let fake = Arc::new(FakeBackend::with_one_monitor()); +/// fake.open_window(9, "foot", "foot", "a terminal"); +/// let (_sender, events) = crossbeam_channel::bounded(1); +/// let socket = PathBuf::from(format!("/tmp/komorebi-state-doc-{}.sock", std::process::id())); +/// +/// let state = with_backend(fake, || -> color_eyre::Result { +/// let mut wm = WindowManager::new(events, Some(socket.clone()))?; +/// wm.init()?; +/// Ok(State::from(&wm)) +/// })?; +/// # std::fs::remove_file(&socket)?; +/// +/// let workspace = &state.monitors.elements()[0].workspaces()[0]; +/// assert_eq!(workspace.containers()[0].windows()[0].id, 9); +/// +/// # Ok::<(), Box>(()) +/// ``` +#[allow(clippy::struct_excessive_bools)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct State { + pub monitors: Ring, + pub work_area_offset: Option, + pub mouse_follows_focus: bool, +} + +impl From<&WindowManager> for State { + fn from(wm: &WindowManager) -> Self { + // Every field of a monitor and of a workspace is copied by name here, so that what does + // not need to be shown in the state can be left out of the copy. + let mut stripped_monitors = Ring::default(); + *stripped_monitors.elements_mut() = wm + .monitors() + .iter() + .map(|monitor| Monitor { + id: monitor.id, + device: monitor.device.clone(), + serial_number_id: monitor.serial_number_id.clone(), + size: monitor.size, + work_area_size: monitor.work_area_size, + work_area_offset: monitor.work_area_offset, + workspaces: { + let mut ws = Ring::default(); + *ws.elements_mut() = monitor + .workspaces() + .iter() + .map(|workspace| Workspace { + containers: workspace.containers.clone(), + layout: workspace.layout.clone(), + workspace_padding: workspace.workspace_padding, + container_padding: workspace.container_padding, + globals: workspace.globals, + }) + .collect::>(); + ws.focus(monitor.workspaces.focused_idx()); + ws + }, + container_padding: monitor.container_padding, + workspace_padding: monitor.workspace_padding, + }) + .collect::>(); + stripped_monitors.focus(wm.monitors.focused_idx()); + + Self { + monitors: stripped_monitors, + work_area_offset: wm.work_area_offset, + mouse_follows_focus: wm.mouse_follows_focus, + } + } +} diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 6898a75d..b662efce 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -5,8 +5,16 @@ //! workspace each window it manages is on. It changes when an event comes in //! ([`WindowManager::process_event`]), and every change ends with the focused workspace tiled //! again ([`WindowManager::update_focused_workspace`]). +//! +//! It also owns the daemon's command socket, which [`listen_for_commands`] reads +//! ([`WindowManager::process_command`]), and stops the daemon when it is asked to +//! ([`WindowManager::stop`]). +//! +//! [`listen_for_commands`]: crate::process_command::listen_for_commands +use crate::DATA_DIR; use crate::LibraryError; +use crate::backend::backend; use crate::container::Container; use crate::core::Rect; use crate::desktop; @@ -19,10 +27,16 @@ use color_eyre::eyre; use color_eyre::eyre::OptionExt; use crossbeam_channel::Receiver; use std::collections::HashMap; +use std::io::ErrorKind; +use std::os::unix::net::UnixListener; +use std::path::PathBuf; #[derive(Debug)] pub struct WindowManager { pub monitors: Ring, + /// The socket the daemon takes messages on, `komorebi.sock` in [`struct@DATA_DIR`] unless + /// [`WindowManager::new`] was given another path + pub command_listener: UnixListener, 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 @@ -37,10 +51,37 @@ impl_ring_elements!(WindowManager, Monitor); impl WindowManager { /// 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 { + /// `incoming` and listens on `custom_socket_path`, or on `komorebi.sock` in + /// [`struct@DATA_DIR`] when that is `None`: [`WindowManager::init`] loads the monitors from + /// the backend + /// + /// A socket file that is left over at that path is removed first. + /// + /// # Errors + /// + /// - The leftover socket file is there but cannot be removed. + /// - The socket cannot be bound, for example because its directory does not exist. + pub fn new( + incoming: Receiver, + custom_socket_path: Option, + ) -> eyre::Result { + let socket = custom_socket_path.unwrap_or_else(|| DATA_DIR.join("komorebi.sock")); + + match std::fs::remove_file(&socket) { + Ok(()) => {} + Err(error) => match error.kind() { + ErrorKind::NotFound => {} + _ => { + return Err(error.into()); + } + }, + }; + + let listener = UnixListener::bind(&socket)?; + Ok(Self { monitors: Ring::default(), + command_listener: listener, mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -155,6 +196,20 @@ impl WindowManager { self.update_focused_workspace(false, false) } + /// Stops the daemon: removes the command socket, lets the backend give up what it set up in + /// the compositor, and exits the process with status 0 + #[tracing::instrument(skip(self))] + pub fn stop(&mut self) -> eyre::Result<()> { + tracing::info!("received stop command, terminating process"); + + let socket = DATA_DIR.join("komorebi.sock"); + let _ = std::fs::remove_file(socket); + + backend().shutdown(); + + std::process::exit(0) + } + /// Tiles the focused workspace of every monitor #[tracing::instrument(skip(self))] pub fn retile_all(&mut self) -> eyre::Result<()> { @@ -205,23 +260,73 @@ mod tests { use super::*; use crate::backend::fake::FakeBackend; use crate::backend::with_backend; + use crossbeam_channel::Sender; + use crossbeam_channel::bounded; + use std::path::PathBuf; use std::sync::Arc; + use uuid::Uuid; - fn setup_window_manager() -> WindowManager { - let (_sender, receiver) = crossbeam_channel::bounded(1); + struct TestContext { + socket_path: Option, + } + + impl Drop for TestContext { + fn drop(&mut self) { + if let Some(socket_path) = &self.socket_path { + // Clean up the socket file + std::fs::remove_file(socket_path).unwrap(); + } + } + } + + fn setup_window_manager() -> (WindowManager, TestContext) { + let (_sender, receiver): (Sender, Receiver) = + bounded(1); + + // Temporary socket path for testing + // /tmp: short enough for a unix socket path on macOS, and writable wherever the tests run + let socket_name = format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4()); + let socket_path = PathBuf::from(socket_name); // Create a new WindowManager instance - let wm = WindowManager::new(receiver); + let wm = WindowManager::new(receiver, Some(socket_path.clone())); // Window Manager should be created successfully assert!(wm.is_ok()); - wm.unwrap() + ( + wm.unwrap(), + TestContext { + socket_path: Some(socket_path), + }, + ) } #[test] fn test_create_window_manager() { - let _wm = setup_window_manager(); + let (_wm, _test_context) = setup_window_manager(); + } + + #[test] + fn a_socket_file_left_behind_is_replaced() -> eyre::Result<()> { + let socket_path = PathBuf::from(format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4())); + std::fs::write(&socket_path, "left behind by a daemon that crashed")?; + let _test_context = TestContext { + socket_path: Some(socket_path.clone()), + }; + + let (_sender, receiver): (Sender, Receiver) = + bounded(1); + let wm = WindowManager::new(receiver, Some(socket_path.clone()))?; + + assert_eq!( + wm.command_listener + .local_addr()? + .as_pathname() + .map(PathBuf::from), + Some(socket_path) + ); + Ok(()) } fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect { @@ -256,7 +361,7 @@ mod tests { #[test] fn init_puts_each_open_window_on_the_monitor_it_is_on() -> eyre::Result<()> { let fake = two_monitors(&[601]); - let mut wm = setup_window_manager(); + let (mut wm, _test_context) = setup_window_manager(); with_backend(fake, || wm.init())?; @@ -273,7 +378,7 @@ mod tests { #[test] fn retile_all_tiles_the_focused_workspace_of_every_monitor() -> eyre::Result<()> { let fake = two_monitors(&[611]); - let mut wm = setup_window_manager(); + let (mut wm, _test_context) = setup_window_manager(); with_backend(fake.clone(), || { wm.init()?; @@ -292,7 +397,7 @@ mod tests { let fake = Arc::new(FakeBackend::with_one_monitor()); fake.open_window(621, "foot", "foot", "stays"); fake.open_window(622, "foot", "foot", "closes"); - let mut wm = setup_window_manager(); + let (mut wm, _test_context) = setup_window_manager(); with_backend(fake.clone(), || { wm.init()?; @@ -309,7 +414,7 @@ mod tests { fn a_minimized_window_is_kept_out_of_the_workspace() -> eyre::Result<()> { let fake = Arc::new(FakeBackend::with_one_monitor()); fake.open_window(631, "foot", "foot", "minimized"); - let mut wm = setup_window_manager(); + let (mut wm, _test_context) = setup_window_manager(); with_backend(fake, || { wm.init()?; diff --git a/komorebi/tests/no_kwin.rs b/komorebi/tests/no_kwin.rs index eea65d3f..8c03143e 100644 --- a/komorebi/tests/no_kwin.rs +++ b/komorebi/tests/no_kwin.rs @@ -1,6 +1,10 @@ -//! `komorebi` connects to KWin unless it is told to run against the in-memory desktop, and says -//! what went wrong when it cannot. +//! `komorebi` connects to KWin unless it is told to run against the in-memory desktop, says +//! what went wrong when it cannot, and then leaves the socket of a komorebi that is running +//! alone. +use std::os::unix::net::UnixListener; +use std::os::unix::net::UnixStream; +use std::path::Path; use std::process::Command; use std::process::Stdio; use std::time::Duration; @@ -8,12 +12,26 @@ use std::time::Duration; /// A bus that is not there, so that a test never reaches the KWin of the session it runs in const NO_BUS: &str = "unix:path=/nonexistent/komorebi-test.bus"; +/// A runtime directory of the test's own, made empty: komorebi makes its data directory, and +/// binds its socket there with `--fake-backend`, before anything else, so the user's runtime +/// directory is kept out of it, and it is writable where the user's home is not (the nix +/// sandbox). /tmp: short enough for a unix socket path on macOS. +fn runtime(test: &str) -> String { + let runtime = format!("/tmp/komorebi-no-kwin-{test}-{}", std::process::id()); + let _ = std::fs::remove_dir_all(&runtime); + std::fs::create_dir_all(&runtime).unwrap(); + runtime +} + #[test] fn without_a_session_bus_komorebi_exits_with_an_error_naming_it() { + let runtime = runtime("bus"); let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) + .env("XDG_RUNTIME_DIR", &runtime) .output() .expect("komorebi runs"); + let _ = std::fs::remove_dir_all(&runtime); assert_eq!(output.status.code(), Some(1)); @@ -24,11 +42,35 @@ fn without_a_session_bus_komorebi_exits_with_an_error_naming_it() { ); } +#[test] +fn without_kwin_komorebi_leaves_the_socket_it_finds_alone() { + let runtime = runtime("socket"); + let socket = Path::new(&runtime).join("komorebi").join("komorebi.sock"); + std::fs::create_dir_all(socket.parent().unwrap()).unwrap(); + // the socket of the komorebi that is running + let running = UnixListener::bind(&socket).unwrap(); + + let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) + .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) + .env("XDG_RUNTIME_DIR", &runtime) + .output() + .expect("komorebi runs"); + + let still_there = UnixStream::connect(&socket).is_ok(); + drop(running); + let _ = std::fs::remove_dir_all(&runtime); + + assert_eq!(output.status.code(), Some(1)); + assert!(still_there, "the socket of the running komorebi was taken"); +} + #[test] fn with_the_fake_backend_komorebi_runs_without_a_session_bus() { + let runtime = runtime("fake"); let mut daemon = Command::new(env!("CARGO_BIN_EXE_komorebi")) .args(["--fake-backend", "--log-level", "error"]) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) + .env("XDG_RUNTIME_DIR", &runtime) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() @@ -39,5 +81,6 @@ fn with_the_fake_backend_komorebi_runs_without_a_session_bus() { daemon.kill().expect("komorebi can be stopped"); daemon.wait().expect("komorebi can be waited for"); + let _ = std::fs::remove_dir_all(&runtime); assert!(exited.is_none(), "komorebi exited: {exited:?}"); } diff --git a/komorebi/tests/socket.rs b/komorebi/tests/socket.rs new file mode 100644 index 00000000..43b0b6d1 --- /dev/null +++ b/komorebi/tests/socket.rs @@ -0,0 +1,88 @@ +//! The daemon over its socket: `komorebi --fake-backend` answers on `komorebi.sock` in its +//! runtime directory, and stops when it is sent `Stop`. + +use std::io::Read; +use std::io::Write; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; +use std::path::Path; +use std::process::Child; +use std::process::Command; +use std::process::Stdio; +use std::time::Duration; +use std::time::Instant; + +/// The daemon, which is killed if the test ends before it stopped +struct Daemon(Child); + +impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +/// Waits up to ten seconds for `done` +fn eventually(mut done: impl FnMut() -> bool) -> bool { + let started = Instant::now(); + while started.elapsed() < Duration::from_secs(10) { + if done() { + return true; + } + std::thread::sleep(Duration::from_millis(20)); + } + false +} + +/// Writes `message` on a new connection to `socket` and returns the answer +fn send(socket: &Path, message: &str) -> std::io::Result { + let mut stream = UnixStream::connect(socket)?; + stream.write_all(message.as_bytes())?; + stream.shutdown(Shutdown::Write)?; + + let mut answer = String::new(); + stream.read_to_string(&mut answer)?; + Ok(answer) +} + +#[test] +fn the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to() { + // /tmp: short enough for a unix socket path on macOS + let runtime = format!("/tmp/komorebi-socket-test-{}", std::process::id()); + let socket = Path::new(&runtime).join("komorebi").join("komorebi.sock"); + let _ = std::fs::remove_dir_all(&runtime); + std::fs::create_dir_all(&runtime).unwrap(); + + let mut daemon = Daemon( + Command::new(env!("CARGO_BIN_EXE_komorebi")) + .arg("--fake-backend") + .env("XDG_RUNTIME_DIR", &runtime) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("komorebi runs"), + ); + + assert!( + eventually(|| send(&socket, r#"{"type":"State"}"#).is_ok()), + "nothing answers on {}", + socket.display() + ); + + let monitors: serde_json::Value = + serde_json::from_str(&send(&socket, r#"{"type":"MonitorInformation"}"#).unwrap()).unwrap(); + // the fake's one monitor + assert_eq!(monitors[0]["size"]["right"], 1920); + + send(&socket, r#"{"type":"Stop"}"#).unwrap(); + + let mut status = None; + assert!(eventually(|| { + status = daemon.0.try_wait().unwrap(); + status.is_some() + })); + assert_eq!(status.and_then(|status| status.code()), Some(0)); + assert!(!socket.exists(), "the socket is left behind"); + + let _ = std::fs::remove_dir_all(&runtime); +} diff --git a/komorebi/tests/wm_events.rs b/komorebi/tests/wm_events.rs index 34f79af9..4ecdf1bf 100644 --- a/komorebi/tests/wm_events.rs +++ b/komorebi/tests/wm_events.rs @@ -57,9 +57,16 @@ fn desktop() -> (Arc, WindowManager) { fn desktop_on(fake: FakeBackend) -> (Arc, WindowManager) { let fake = Arc::new(fake); let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmb-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); let wm = with_backend(fake.clone(), || { - let mut wm = WindowManager::new(receiver).unwrap(); + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); wm.init().unwrap(); wm }); From 6f657e53e3b818e2cb8017bd2b0651286cf4c5e3 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 13:26:31 -0700 Subject: [PATCH 015/255] feat(cli): komorebic The daemon answers on its socket, but a person has no way to write a message on it. komorebic is that way: each subcommand that asks something of the daemon is one message, sent with komorebi-client, and a question's answer is printed. komorebic is a separate program because the daemon takes no input but its socket, so a key binding, a script and a terminal all drive it the same way. It has what the daemon can answer so far: state, monitor-information, query, retile and stop. Around them, start runs the komorebi on the PATH in the background and passes it what follows a --, such as --fake-backend to try it without a compositor; log follows the daemon's log, which the daemon now writes to a file a day in LOG_DIR as well as to stdout; data-directory shows where the socket is; completions prints a shell completion script. The hidden docgen writes each subcommand's help to docs/cli, in fences that name their language and wrapped at 100 columns whatever the width of the terminal, so that the pages are the same wherever they are generated; just docgen runs it. The user guide starts here: docs/index.md for KDE Plasma, and a page on running komorebi. tests/cli.rs runs each subcommand against a socket the test serves in place of the daemon. In the VM tests the guests get komorebic next to the daemon, and vm-core-e2e reads the daemon's state with it (the windows it manages, the one it focuses, after KWin restarts too) and stops it with komorebic stop, which unloads the bridge and removes the socket. In the VM test library, Kde.state asks again, a second (times the scale) after an empty answer or a failed command, up to 10 times. The daemon drops a query when it cannot take hold of the window manager within a second, and komorebic then prints an empty line and succeeds; komorebic itself gives the daemon a second to answer and fails when that is not enough. A daemon busy with the first windows does either on a machine that is loaded or slow, and a suite that polled the state died on JSONDecodeError. An answer that is not JSON still fails at once. --- CONTRIBUTING.md | 3 +- Cargo.lock | 170 +++++++++++++++++++ Cargo.toml | 5 +- README.md | 22 ++- deny.toml | 5 + docs/cli/completions.md | 14 ++ docs/cli/data-directory.md | 10 ++ docs/cli/log.md | 10 ++ docs/cli/monitor-information.md | 10 ++ docs/cli/query.md | 15 ++ docs/cli/retile.md | 10 ++ docs/cli/start.md | 14 ++ docs/cli/state.md | 10 ++ docs/cli/stop.md | 10 ++ docs/dev/ARCHITECTURE.md | 17 +- docs/dev/DESIGN.md | 7 + docs/dev/PLATFORM.md | 17 +- docs/dev/vm-tests.md | 9 +- docs/index.md | 94 +++++++++++ docs/usage/running-komorebi.md | 98 +++++++++++ flake.nix | 17 +- justfile | 5 + komorebi-client/src/lib.rs | 1 + komorebi/Cargo.toml | 1 + komorebi/src/lib.rs | 6 + komorebi/src/main.rs | 30 +++- komorebi/tests/no_kwin.rs | 15 +- komorebi/tests/socket.rs | 3 + komorebic/Cargo.toml | 21 +++ komorebic/src/main.rs | 239 +++++++++++++++++++++++++++ komorebic/tests/cli.rs | 212 ++++++++++++++++++++++++ nix/tests/vm/default.nix | 6 +- nix/tests/vm/lib/komorebi_vm/kde.py | 52 ++++++ nix/tests/vm/lib/tests/test_kde.py | 142 ++++++++++++++++ nix/tests/vm/nodes/headless.nix | 3 +- nix/tests/vm/suites/core-e2e/test.py | 56 ++++++- 36 files changed, 1320 insertions(+), 39 deletions(-) create mode 100644 docs/cli/completions.md create mode 100644 docs/cli/data-directory.md create mode 100644 docs/cli/log.md create mode 100644 docs/cli/monitor-information.md create mode 100644 docs/cli/query.md create mode 100644 docs/cli/retile.md create mode 100644 docs/cli/start.md create mode 100644 docs/cli/state.md create mode 100644 docs/cli/stop.md create mode 100644 docs/index.md create mode 100644 docs/usage/running-komorebi.md create mode 100644 komorebic/Cargo.toml create mode 100644 komorebic/src/main.rs create mode 100644 komorebic/tests/cli.rs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fcf1169b..584b9072 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,7 +87,8 @@ the flake and `github` for workflows. Every line of a message, the header included, is at most 80 columns, and the body says why the change is made. Documentation lands in the commit that changes the behavior it describes, not -in a later one. +in a later one. A change to a `komorebic` subcommand regenerates its page in +[`docs/cli`](docs/cli) with `just docgen`. ## Zero-Clause BSD diff --git a/Cargo.lock b/Cargo.lock index 1b67cc30..d269c192 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -219,8 +219,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", "serde", + "wasm-bindgen", "windows-link", ] @@ -247,6 +249,15 @@ dependencies = [ "terminal_size", ] +[[package]] +name = "clap_complete" +version = "4.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" +dependencies = [ + "clap", +] + [[package]] name = "clap_derive" version = "4.6.7" @@ -576,6 +587,15 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-tail" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73c8ee8694b2ad6d79aa976ad8572ca376c0450290041e6e3ae75147356b6ad2" +dependencies = [ + "memchr", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -974,6 +994,7 @@ dependencies = [ "strum", "tokio", "tracing", + "tracing-appender", "tracing-subscriber", "uuid", "version", @@ -1004,6 +1025,21 @@ dependencies = [ "tracing", ] +[[package]] +name = "komorebic" +version = "0.1.0" +dependencies = [ + "chrono", + "clap", + "clap_complete", + "color-eyre", + "fs-tail", + "komorebi-client", + "pastey", + "sysinfo", + "version", +] + [[package]] name = "konst" version = "0.2.20" @@ -1156,6 +1192,15 @@ dependencies = [ "libc", ] +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -1198,12 +1243,31 @@ dependencies = [ "objc2-encode", ] +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "objc2-encode" version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "object" version = "0.40.0" @@ -1761,6 +1825,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + [[package]] name = "syn" version = "2.0.119" @@ -1794,6 +1864,20 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "sysinfo" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ab6a2f8bfe508deb3c6406578252e491d299cbbf3bc0529ecc3313aee4a52f" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -1951,6 +2035,19 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror", + "time", + "tracing-subscriber", +] + [[package]] name = "tracing-attributes" version = "0.1.31" @@ -2172,6 +2269,49 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -2185,6 +2325,17 @@ dependencies = [ "windows-strings", ] +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -2213,6 +2364,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -2240,6 +2401,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "winnow" version = "1.0.4" diff --git a/Cargo.toml b/Cargo.toml index 46b0675d..fc6dfd52 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "2" -members = ["komorebi", "komorebi-client", "version"] +members = ["komorebi", "komorebi-client", "komorebic", "version"] [workspace.package] version = "0.1.0" @@ -13,6 +13,7 @@ komorebi-layouts = { git = "https://github.com/LGUG2Z/komorebi", rev = "f08aa555 "schemars", ] } +chrono = "0.4" clap = { version = "4", features = ["derive", "wrap_help"] } color-eyre = "0.6" crossbeam-channel = "0.5" @@ -23,7 +24,9 @@ schemars = "1.1" serde = { version = "1", features = ["derive"] } serde_json = { package = "serde_json_lenient", version = "0.2" } shadow-rs = "1" +sysinfo = "0.38" tracing = "0.1" +tracing-appender = "0.2" tracing-subscriber = { version = "0.3", features = ["env-filter"] } [workspace.metadata.crane] diff --git a/README.md b/README.md index 72eeade3..75687334 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,21 @@ While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in `$XDG_RUNTIME_DIR/komorebi` (the local data directory when there is no runtime directory): a message can ask for the state of the window manager, ask which monitor, workspace or container has the focus, retile every monitor, or stop -the daemon. [`komorebi-client`](komorebi-client) writes them. +the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +the command line, is how a person sends them. `komorebic start` runs the +`komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma +session: + +```sh +cargo build --locked +export PATH="$PWD/target/debug:$PATH" +komorebic start +komorebic state +komorebic stop +``` + +`komorebic start -- --fake-backend` tries the daemon and `komorebic` without a +compositor, against the in-memory desktop. `nix develop` provides the Rust toolchain that [`rust-toolchain.toml`](rust-toolchain.toml) selects, a nightly `rustfmt`, and the tools `just check` and the flake's checks @@ -52,6 +66,9 @@ without a checkout of the toolchain. (`state`). - [`komorebi-client`](komorebi-client): a library that sends messages to the daemon and reads its answers, and re-exports the types they are made of. +- [`komorebic`](komorebic): the command line. A subcommand that asks something + of the daemon is one message on its socket; `start`, `log`, `data-directory`, + `completions` and the hidden `docgen` work without the daemon. - [`version`](version): the version string every binary reports. The layouts, which turn a work area and a number of containers into a rectangle @@ -103,6 +120,9 @@ locked. A message that asks a question is answered on the same connection. ## Documentation +The user guide starts at [`docs/index.md`](docs/index.md), and +[`docs/cli`](docs/cli) has a page for every `komorebic` subcommand, which +`just docgen` writes from the subcommands' help. `cargo doc --workspace --no-deps --open` builds the API documentation. [`CONTRIBUTING.md`](CONTRIBUTING.md) says how to work on the code. [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md) describes the model, diff --git a/deny.toml b/deny.toml index 71131d7a..267bda37 100644 --- a/deny.toml +++ b/deny.toml @@ -44,6 +44,11 @@ crate = "komorebi-layouts" expression = "LicenseRef-Komorebi-2.0" license-files = [] +[[licenses.clarify]] +crate = "komorebic" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "version" expression = "LicenseRef-Komorebi-2.0" diff --git a/docs/cli/completions.md b/docs/cli/completions.md new file mode 100644 index 00000000..ed664143 --- /dev/null +++ b/docs/cli/completions.md @@ -0,0 +1,14 @@ +```text +Generate komorebic CLI completions for the target shell + +Usage: completions + +Arguments: + + [possible values: bash, elvish, fish, powershell, zsh] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/data-directory.md b/docs/cli/data-directory.md new file mode 100644 index 00000000..c1c9158e --- /dev/null +++ b/docs/cli/data-directory.md @@ -0,0 +1,10 @@ +```text +Show the path to komorebi's data directory, which has its socket + +Usage: data-directory + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/log.md b/docs/cli/log.md new file mode 100644 index 00000000..0b3fa97c --- /dev/null +++ b/docs/cli/log.md @@ -0,0 +1,10 @@ +```text +Tail komorebi's process logs (cancel with Ctrl-C) + +Usage: log + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/monitor-information.md b/docs/cli/monitor-information.md new file mode 100644 index 00000000..c50c6ac2 --- /dev/null +++ b/docs/cli/monitor-information.md @@ -0,0 +1,10 @@ +```text +Show information about connected monitors + +Usage: monitor-information + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/query.md b/docs/cli/query.md new file mode 100644 index 00000000..f2a6a955 --- /dev/null +++ b/docs/cli/query.md @@ -0,0 +1,15 @@ +```text +Query the current window manager state + +Usage: query + +Arguments: + + [possible values: focused-monitor-index, focused-workspace-index, focused-container-index, + focused-window-index, focused-workspace-layout, focused-container-kind, version] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/retile.md b/docs/cli/retile.md new file mode 100644 index 00000000..310d1cc1 --- /dev/null +++ b/docs/cli/retile.md @@ -0,0 +1,10 @@ +```text +Force the retiling of all managed windows + +Usage: retile + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/start.md b/docs/cli/start.md new file mode 100644 index 00000000..af684bd8 --- /dev/null +++ b/docs/cli/start.md @@ -0,0 +1,14 @@ +```text +Start komorebi as a background process + +Usage: start [-- ...] + +Arguments: + [KOMOREBI_ARGS]... + Arguments to pass to komorebi, after a `--`: `komorebic start -- --log-level debug` + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/state.md b/docs/cli/state.md new file mode 100644 index 00000000..c6ac520d --- /dev/null +++ b/docs/cli/state.md @@ -0,0 +1,10 @@ +```text +Show a JSON representation of the current window manager state + +Usage: state + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/stop.md b/docs/cli/stop.md new file mode 100644 index 00000000..889ec1ab --- /dev/null +++ b/docs/cli/stop.md @@ -0,0 +1,10 @@ +```text +Stop the komorebi process + +Usage: stop + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index c82ca934..28aa7885 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -223,6 +223,10 @@ status 0. `SIGINT` and `SIGTERM` do the same from `main.rs`, with the exit statu - [`state`](../../komorebi/src/state.rs): the [`State`] a `State` message is answered with. - [`komorebi-client`](../../komorebi-client/src/lib.rs): a library that writes messages on the socket and reads the answers, for programs that talk to the daemon. +- [`komorebic`](../../komorebic/src/main.rs): the command line. A subcommand that asks + something of the daemon is one message, sent with `komorebi-client`; `start` runs the + daemon, `log` follows its log file in [`LOG_DIR`], and the hidden `docgen` writes + `docs/cli`. - [`main.rs`](../../komorebi/src/main.rs): the daemon. It connects to KWin, or installs the fake with `--fake-backend`, makes the window manager, which binds the socket, loads and tiles the desktop, starts the threads that listen on the socket and handle events, and @@ -325,10 +329,10 @@ A window is shown, and ends up on a tile: ## One message, end to end -A client asks for the state of the window manager: +`komorebic state` asks for the state of the window manager: -1. [`send_query`] connects to `komorebi.sock` in [`DATA_DIR`], writes - `{"type":"State"}`, and shuts down its side of the connection for writing. +1. `komorebic` calls [`send_query`], which connects to `komorebi.sock` in [`DATA_DIR`], + writes `{"type":"State"}`, and shuts down its side of the connection for writing. 2. The thread that [`listen_for_commands`] started accepts the connection and starts a thread for it, which calls [`read_commands_uds`]. 3. `read_commands_uds` reads the line, parses it into [`SocketMessage`]`::State`, and locks @@ -339,7 +343,7 @@ A client asks for the state of the window manager: 5. The state is written to the connection as pretty-printed JSON, and the index of managed windows is rebuilt, as after every message. 6. There are no more lines, so `read_commands_uds` returns and the connection is closed. - `send_query` has read to the end, and returns the JSON. + `send_query` has read to the end, and returns the JSON, which `komorebic` prints. ## Where to look in the code @@ -358,6 +362,8 @@ A client asks for the state of the window manager: each message does, and the tests that send messages through a real socket. - [`komorebi-client/src/lib.rs`](../../komorebi-client/src/lib.rs): the client side of the socket. +- [`komorebic/src/main.rs`](../../komorebic/src/main.rs): the subcommands, and + [`komorebic/tests/cli.rs`](../../komorebic/tests/cli.rs), what each writes on the socket. - [`komorebi/src/kwin/mod.rs`](../../komorebi/src/kwin/mod.rs): the KWin backend, its D-Bus service and the held call. - [`komorebi/src/kwin/state.rs`](../../komorebi/src/kwin/state.rs): the table, with the @@ -369,7 +375,7 @@ A client asks for the state of the window manager: - [`nix/tests/vm/suites/kwin-events`](../../nix/tests/vm/suites/kwin-events/test.py): the events of a real KWin, through the daemon. - [`nix/tests/vm/suites/core-e2e`](../../nix/tests/vm/suites/core-e2e/test.py): the daemon - tiling a real KWin, checked against what KWin has. + tiling a real KWin, checked against what KWin has, and read and stopped with `komorebic`. - [`nix/tests/vm/suites/kwin-restart`](../../nix/tests/vm/suites/kwin-restart/test.py): KWin restarting under the daemon. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager @@ -411,6 +417,7 @@ A client asks for the state of the window manager: [`bridge.test.js`]: ../../komorebi/src/kwin/bridge.test.js [`fixtures`]: ../../komorebi/src/kwin/fixtures [`DATA_DIR`]: ../../komorebi/src/lib.rs +[`LOG_DIR`]: ../../komorebi/src/lib.rs [`SocketMessage`]: ../../komorebi/src/core/mod.rs [`StateQuery`]: ../../komorebi/src/core/mod.rs [`State`]: ../../komorebi/src/state.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 0049df8d..67ab1d07 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -164,3 +164,10 @@ an action is the job of another program, which runs a command that writes a mess socket. This is the architecture that bspwm made popular on Linux and yabai on macOS, and the one komorebi has on Windows and on macOS ([the design notes of komorebi for Mac](https://github.com/LGUG2Z/komorebi-for-mac/blob/master/docs/design.md)). + +## Why is `komorebic` a separate program? + +Because the daemon takes no input but its socket. `komorebic` turns a command line into one +message on the socket and, for a question, prints the answer. A key binding, a script and a +person at a terminal all drive komorebi the same way, by running `komorebic` (the design +notes of komorebi for Mac, linked above). diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index b775bc7d..e1870181 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -144,9 +144,11 @@ What komorebi calls: |---|---|---| | `$XDG_RUNTIME_DIR/komorebi/bridge.js` | the script KWin loads, with its configuration (the D-Bus names and the hold time of `Poll`) on its first line | written at every start; the directory is removed at logout | | `$XDG_RUNTIME_DIR/komorebi/komorebi.sock` | the command socket | bound once the daemon is connected to KWin, after a file left there is removed; removed when the daemon stops | +| `$XDG_DATA_HOME/komorebi/komorebi.log.YYYY-MM-DD` | the daemon's log, with colors, which `komorebic log` follows | a file a day (the UTC date), never removed by komorebi | +| `$XDG_DATA_HOME/komorebi/komorebi_plaintext.log.YYYY-MM-DD` | the same log without colors | as above | -Without `XDG_RUNTIME_DIR` the directory is `komorebi` in the local data directory instead -(see [`XDG_DATA_HOME`](#xdg_data_home)). +Without `XDG_RUNTIME_DIR` the bridge and the socket are in `komorebi` in the local data +directory instead, with the logs (see [`XDG_DATA_HOME`](#xdg_data_home)). ## Environment variables @@ -163,8 +165,10 @@ the `komorebi` directory in it, and binds its command socket there. ### `XDG_DATA_HOME` -Read only when `XDG_RUNTIME_DIR` is not set: the bridge and the socket then go to -`$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if `XDG_DATA_HOME` is not set either). +The logs are written to `$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if +`XDG_DATA_HOME` is not set), which the daemon makes before anything else: a home it cannot +write to stops it at once. When `XDG_RUNTIME_DIR` is not set, the bridge and the socket go +there too. ### `RUST_LOG` @@ -178,8 +182,9 @@ Whether an error carries a backtrace. komorebi sets it to `1` when it is not set ### `NO_COLOR` -When set to anything but the empty string, the log has no ANSI colors, which is what a log -written to a file wants. The VM tests set it. +When set to anything but the empty string, the log the daemon prints on its standard output +has no ANSI colors, which is what standard output redirected to a file wants. The VM tests +set it. The log files are not affected: one has colors and the other none. ## The bridge's environment diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index dd68907c..27c78e22 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -54,8 +54,8 @@ own Wayland socket), so a test can run several sessions side by side and none touches another. A virtual KWin has no real output, so it cannot draw: it can place windows and answer questions about them, but it cannot take a screenshot. A third unit, `komorebi@NAME`, runs the daemon in a session, built from the -commit under test and installed on the node; it is not bound to KWin's unit, so -a test can restart KWin under a running daemon. +commit under test and installed on the node with `komorebic`; it is not bound to +KWin's unit, so a test can restart KWin under a running daemon. KWin wants a DRM render node, which needs a GPU. The test driver gives every aarch64 guest one `virtio-gpu-pci`; on x86_64 the node adds it, unless `komorebi.vm.renderNode` is false. @@ -105,6 +105,11 @@ the run. started, and `script_loaded()` asks KWin whether it runs the bridge. `restart_kwin()` stops the session's KWin and starts a new one on the same bus, as when the compositor of a running session crashes, and waits for it. +- `komorebic(*args)` runs `komorebic` in the session and returns what it + printed, failing the test if it fails. `state()` is the daemon's state as + `komorebic state` prints it, `managed(workspace)` the number of windows the + daemon has on a workspace of the first monitor, and `focused_title(workspace)` + the title of the window it has focused there. - `daemon` reads the daemon's view of the desktop from that log, started with `--log-level debug`: `daemon.events(log)` lists the window events it handled, in order, `daemon.window_ids(log)` maps a window's title to the daemon's id diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..ef04d17f --- /dev/null +++ b/docs/index.md @@ -0,0 +1,94 @@ +# komorebi for KDE + +## Overview + +`komorebi` is a tiling window manager for KDE Plasma on Wayland. It decides where each window +goes, and KWin, the window manager of Plasma, moves and draws the windows. + +`komorebi` is a daemon that runs in the background, and it is controlled with a CLI, +`komorebic`. Every `komorebic` command that asks something of the daemon is a message on its +socket, so anything that can run a command can drive `komorebi`: a terminal, a script, or a +program that binds keys, which is how a key is given an action. + +`komorebi` aims to make _as few modifications as possible_ to the operating system and desktop +environment by default. Users are free to make such modifications in their own configuration +files for `komorebi`, but these will always remain opt-in and off-by-default. + +## How it fits together + +_komorebi_ only responds to the events KWin reports about windows and to the messages it +receives on a dedicated socket. _komorebic_ is a CLI that writes messages on _komorebi_'s +socket. _komorebi_ doesn't handle any keyboard or mouse inputs: a program that binds keys, +such as the custom shortcuts in Plasma's System Settings, runs _komorebic_ commands. + +```text + PROCESS SOCKET +key bindings --------> komorebic <------> komorebi +``` + +## Getting started + +[Running komorebi](usage/running-komorebi.md) explains how to get the two programs, start and +stop the daemon, ask it what it is doing and read its log. The [CLI reference](cli/start.md) +has a page for every `komorebic` command, generated from its help. + +## Community + +There is a [Discord server](https://discord.gg/mGkn66PHkx) available for +`komorebi`-related discussion, help, troubleshooting etc. + +There is a [YouTube +channel](https://www.youtube.com/channel/UCeai3-do-9O4MNy9_xjO6mg) where I post +`komorebi` development videos, feature previews and release overviews. Subscribing +to the channel (which is monetized as part of the YouTube Partner Program) and +watching videos is a really simple and passive way to contribute financially to +the development and maintenance of `komorebi`. + +There is an [Awesome List](https://github.com/LGUG2Z/awesome-komorebi) which +showcases the many awesome projects that exist in the `komorebi` ecosystem. + +## Licensing for Personal Use + +`komorebi` is licensed under the [Komorebi 2.0.0 license](https://github.com/LGUG2Z/komorebi-license), which is a fork +of the [PolyForm Strict 1.0.0 license](https://polyformproject.org/licenses/strict/1.0.0). On a high level this means +that you are free to do whatever you want with `komorebi` for personal use other than redistribution, or distribution of +new works (i.e. hard-forks) based on the software. + +Anyone is free to make their own fork of `komorebi` with changes intended either for personal use or for integration +back upstream via pull requests. + +The [Komorebi 2.0.0 License](https://github.com/LGUG2Z/komorebi-license) does not permit any kind of commercial use ( +i.e. using `komorebi` at work). + +## Sponsorship for Personal Use + +`komorebi` is a free and educational source project, and one that encourages you +to make charitable donations if you find the software to be useful and have the +financial means. + +I encourage you to make a charitable donation to the [Palestine Children's +Relief Fund](https://pcrf1.app.neoncrm.com/forms/gaza-recovery) or to contribute +to a [Gaza Funds campaign](https://gazafunds.com) before you consider sponsoring +me on GitHub. + +[GitHub Sponsors is enabled for this +project](https://github.com/sponsors/LGUG2Z). Sponsors can claim custom roles on +the Discord server, get shout-outs at the end of _komorebi_-related videos on +YouTube, and gain the ability to submit feature requests on the issue tracker. + +If you would like to tip or sponsor the project but are unable to use GitHub +Sponsors, you may also sponsor through [Ko-fi](https://ko-fi.com/lgug2z), or +make an anonymous Bitcoin donation to `bc1qv73wzspc77k46uty4vp85x8sdp24mphvm58f6q`. + +## Licensing for Commercial Use + +A dedicated Individual Commercial Use License is available for those who want to +use `komorebi` at work. + +The Individual Commercial Use License adds “Commercial Use” as a “Permitted Use” +for the licensed individual only, for the duration of a valid paid license +subscription only. All provisions and restrictions enumerated in the [Komorebi +License](https://github.com/LGUG2Z/komorebi-license) continue to apply. + +More information, pricing and purchase links for Individual Commercial Use +Licenses [can be found here](https://lgug2z.com/software/komorebi). diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md new file mode 100644 index 00000000..748254bd --- /dev/null +++ b/docs/usage/running-komorebi.md @@ -0,0 +1,98 @@ +# Running komorebi + +`komorebi` is the daemon that tiles your windows, and `komorebic` is the command line you +control it with. This page covers starting and stopping the daemon, asking it what it is +doing, and reading its log. + +## Getting the two programs + +On Linux, the flake's default package has both: in a checkout of the repository, +`nix build` leaves them in `result/bin`, and `nix profile install .` puts them on your +`PATH`. Without nix, build them with the Rust toolchain that `rust-toolchain.toml` +selects: + +```sh +cargo build --release --locked +export PATH="$PWD/target/release:$PATH" +``` + +## Starting and stopping + +[`komorebic start`](../cli/start.md) runs the `komorebi` on your `PATH` in the background, +and checks three seconds later that it is running. It tries three times. If `komorebi` has +not started by then, `komorebic start` runs it once more in the foreground and prints what +it wrote on its standard error, which explains why it did not start. When a `komorebi` is +running already, `komorebic start` does nothing. + +`komorebi` manages the windows of the Plasma Wayland session it is started in: it connects +to KWin on the session bus and loads a script into it, so start it from a terminal in that +session. Outside a Plasma session it exits with an error that says what is missing, which +`komorebic start` prints. + +Everything after a `--` is passed to `komorebi`. `--fake-backend` runs it against an +in-memory desktop with one monitor and no windows instead of KWin, which is a way to try the +daemon and `komorebic` without a compositor: + +```sh +komorebic start +komorebic start -- --log-level debug +komorebic start -- --fake-backend +``` + +[`komorebic stop`](../cli/stop.md) tells the daemon to stop. It asks KWin to unload its +script, removes its socket and exits. Stopping the process with `SIGINT` or `SIGTERM` does +the same. + +## Asking komorebi what it is doing + +The daemon answers questions on its socket, and these commands print the answers: + +- [`komorebic state`](../cli/state.md): every monitor, with its workspaces, their + containers and the windows in them, as JSON. +- [`komorebic monitor-information`](../cli/monitor-information.md): the id, the name and + the bounds of every monitor, as JSON. +- [`komorebic query`](../cli/query.md): one value, the answer to one question: the index of + the focused monitor, workspace, container or window, the layout of the focused workspace, + whether the focused container is a single window or a stack, or the version of the + daemon. + +```sh +komorebic query focused-workspace-index +komorebic state | jq '.monitors.elements[0].workspaces.elements[0].containers.elements | length' +``` + +[`komorebic retile`](../cli/retile.md) tiles the windows of every monitor again, which puts +a window that was moved by hand back on its tile. + +When the daemon is not running, these commands fail: there is no socket to write to. + +## The socket and the data directory + +The daemon listens on `komorebi.sock` in its data directory, `$XDG_RUNTIME_DIR/komorebi` +(the local data directory, `~/.local/share/komorebi`, when there is no runtime directory). +[`komorebic data-directory`](../cli/data-directory.md) prints the directory, if it exists. + +## The log + +The daemon logs to its standard output and to a file a day in `~/.local/share/komorebi` +(`$XDG_DATA_HOME/komorebi` when that is set): `komorebi.log.YYYY-MM-DD`, with colors, and +`komorebi_plaintext.log.YYYY-MM-DD`, without. The day is the UTC date. + +[`komorebic log`](../cli/log.md) follows the file of the current day, with colors, until +you press Ctrl-C. The `--log-level` of `komorebi` sets how much is logged: `error`, `warn`, +`info` (the default), `debug` or `trace`. + +## Shell completions + +[`komorebic completions`](../cli/completions.md) prints a completion script for bash, +elvish, fish, PowerShell or zsh: + +```sh +komorebic completions fish > ~/.config/fish/completions/komorebic.fish +komorebic completions bash > ~/.local/share/bash-completion/completions/komorebic +``` + +## Every command + +[`docs/cli`](../cli/start.md) has a page for every `komorebic` command, generated from its +help with `just docgen`. diff --git a/flake.nix b/flake.nix index 9694a5fc..e7f51b82 100644 --- a/flake.nix +++ b/flake.nix @@ -94,6 +94,7 @@ fullBuild ; komorebi = extractBinary "komorebi"; + komorebic = extractBinary "komorebic"; }; in flake-parts.lib.mkFlake { inherit inputs; } { @@ -122,8 +123,8 @@ pkgs = mkPkgs system; build = mkKomorebiPackages { inherit pkgs; }; isLinux = pkgs.stdenv.hostPlatform.isLinux; - # the daemon each guest runs, built for the guest's system - komorebiFor = guestSystem: self.packages.${guestSystem}.komorebi; + # the daemon and komorebic each guest runs, built for the guest's system + komorebiFor = guestSystem: self.packages.${guestSystem}.komorebi-full; # a Mac runs the guests under HVF, which is slower than KVM vm = import ./nix/tests/vm { hostPkgs = pkgs; @@ -236,7 +237,7 @@ }; packages = lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { - inherit (build) komorebi; + inherit (build) komorebi komorebic; komorebi-full = build.fullBuild; default = build.fullBuild; }; @@ -247,6 +248,11 @@ program = "${build.komorebi}/bin/komorebi"; meta.description = "The komorebi daemon"; }; + komorebic = { + type = "app"; + program = "${build.komorebic}/bin/komorebic"; + meta.description = "The command line interface of komorebi"; + }; default = config.apps.komorebi; }; @@ -290,7 +296,10 @@ flake = { overlays.default = final: _: { - inherit ((mkKomorebiPackages { pkgs = mkPkgs final.stdenv.hostPlatform.system; })) komorebi; + inherit ((mkKomorebiPackages { pkgs = mkPkgs final.stdenv.hostPlatform.system; })) + komorebi + komorebic + ; }; overlays.komorebi = self.overlays.default; }; diff --git a/justfile b/justfile index 5efb510f..3726a9ca 100644 --- a/justfile +++ b/justfile @@ -43,5 +43,10 @@ vm-all: just vm "$name" done +# write the help of every komorebic subcommand to docs/cli, one page each +docgen: + rm -f docs/cli/*.md + cargo run --package komorebic --locked -- docgen --output docs/cli + run target *args: cargo run --bin {{ target }} --locked -- {{ args }} diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index 5ac831fa..c249345e 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -50,6 +50,7 @@ //! way the daemon does, over an in-memory desktop. pub use komorebi::DATA_DIR; +pub use komorebi::LOG_DIR; pub use komorebi::container::Container; pub use komorebi::core::ApplicationIdentifier; pub use komorebi::core::Axis; diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index fb152296..674252c1 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -24,6 +24,7 @@ serde_with = { version = "3", features = ["schemars_1"] } strum = { version = "0.28", features = ["derive"] } tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] } tracing = { workspace = true } +tracing-appender = { workspace = true } tracing-subscriber = { workspace = true } zbus = { version = "5", default-features = false, features = ["tokio"] } futures-util = "0.3" diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 6a1b14a5..d0056428 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -58,6 +58,12 @@ lazy_static! { .expect("there is no local data directory") .join("komorebi") }); + /// Where the logs live: persistent, unlike [`struct@DATA_DIR`]. The daemon writes a file a day + /// here, `komorebi.log.YYYY-MM-DD`, and the same without colors in + /// `komorebi_plaintext.log.YYYY-MM-DD`. + pub static ref LOG_DIR: PathBuf = dirs::data_local_dir() + .expect("there is no local data directory") + .join("komorebi"); } /// The padding, in pixels, between the edge of a monitor's work area and the tiles of its diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 7ab2e5ec..920791a7 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -10,11 +10,15 @@ //! messages on `komorebi.sock` in [`struct@DATA_DIR`], handles the events the backend reports on //! a thread of their own, and runs until it is stopped, with `SIGINT`, `SIGTERM` or a `Stop` //! message. +//! +//! It logs to standard output and to a file a day in [`struct@LOG_DIR`], which `komorebic log` +//! follows. use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; use komorebi::DATA_DIR; +use komorebi::LOG_DIR; use komorebi::backend; use komorebi::backend::fake::FakeBackend; use komorebi::process_command::listen_for_commands; @@ -24,9 +28,11 @@ use komorebi::window_manager_event_listener; use parking_lot::Mutex; use serde::Deserialize; use std::sync::Arc; +use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::EnvFilter; +use tracing_subscriber::layer::SubscriberExt; -fn setup(log_level: LogLevel) -> eyre::Result<()> { +fn setup(log_level: LogLevel) -> eyre::Result<(WorkerGuard, WorkerGuard)> { if std::env::var("RUST_LIB_BACKTRACE").is_err() { unsafe { std::env::set_var("RUST_LIB_BACKTRACE", "1"); @@ -50,10 +56,26 @@ fn setup(log_level: LogLevel) -> eyre::Result<()> { } } + std::fs::create_dir_all(&*LOG_DIR)?; + let appender = tracing_appender::rolling::daily(&*LOG_DIR, "komorebi_plaintext.log"); + let color_appender = tracing_appender::rolling::daily(&*LOG_DIR, "komorebi.log"); + let (non_blocking, guard) = tracing_appender::non_blocking(appender); + let (color_non_blocking, color_guard) = tracing_appender::non_blocking(color_appender); + tracing::subscriber::set_global_default( tracing_subscriber::fmt::Subscriber::builder() .with_env_filter(EnvFilter::from_default_env()) - .finish(), + .finish() + .with( + tracing_subscriber::fmt::Layer::default() + .with_writer(non_blocking) + .with_ansi(false), + ) + .with( + tracing_subscriber::fmt::Layer::default() + .with_writer(color_non_blocking) + .with_ansi(true), + ), )?; // https://github.com/tokio-rs/tracing/blob/master/examples/examples/panic_hook.rs @@ -75,7 +97,7 @@ fn setup(log_level: LogLevel) -> eyre::Result<()> { ); })); - Ok(()) + Ok((guard, color_guard)) } #[cfg(feature = "deadlock_detection")] @@ -129,7 +151,7 @@ struct Opts { fn main() -> eyre::Result<()> { let opts: Opts = Opts::parse(); - setup(opts.log_level)?; + let (_guard, _color_guard) = setup(opts.log_level)?; if !DATA_DIR.is_dir() { std::fs::create_dir_all(&*DATA_DIR)?; diff --git a/komorebi/tests/no_kwin.rs b/komorebi/tests/no_kwin.rs index 8c03143e..417c68a3 100644 --- a/komorebi/tests/no_kwin.rs +++ b/komorebi/tests/no_kwin.rs @@ -12,10 +12,11 @@ use std::time::Duration; /// A bus that is not there, so that a test never reaches the KWin of the session it runs in const NO_BUS: &str = "unix:path=/nonexistent/komorebi-test.bus"; -/// A runtime directory of the test's own, made empty: komorebi makes its data directory, and -/// binds its socket there with `--fake-backend`, before anything else, so the user's runtime -/// directory is kept out of it, and it is writable where the user's home is not (the nix -/// sandbox). /tmp: short enough for a unix socket path on macOS. +/// A runtime directory of the test's own, made empty, which is also its home: komorebi makes +/// its log directory in the home and its data directory in the runtime directory, and binds its +/// socket there with `--fake-backend`, before anything else, so the user's are kept out of it, +/// and it is writable where the user's home is not (the nix sandbox). /tmp: short enough for a +/// unix socket path on macOS. fn runtime(test: &str) -> String { let runtime = format!("/tmp/komorebi-no-kwin-{test}-{}", std::process::id()); let _ = std::fs::remove_dir_all(&runtime); @@ -29,6 +30,8 @@ fn without_a_session_bus_komorebi_exits_with_an_error_naming_it() { let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) .env("XDG_RUNTIME_DIR", &runtime) + .env("HOME", &runtime) + .env_remove("XDG_DATA_HOME") .output() .expect("komorebi runs"); let _ = std::fs::remove_dir_all(&runtime); @@ -53,6 +56,8 @@ fn without_kwin_komorebi_leaves_the_socket_it_finds_alone() { let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) .env("XDG_RUNTIME_DIR", &runtime) + .env("HOME", &runtime) + .env_remove("XDG_DATA_HOME") .output() .expect("komorebi runs"); @@ -71,6 +76,8 @@ fn with_the_fake_backend_komorebi_runs_without_a_session_bus() { .args(["--fake-backend", "--log-level", "error"]) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) .env("XDG_RUNTIME_DIR", &runtime) + .env("HOME", &runtime) + .env_remove("XDG_DATA_HOME") .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() diff --git a/komorebi/tests/socket.rs b/komorebi/tests/socket.rs index 43b0b6d1..42f4c6d5 100644 --- a/komorebi/tests/socket.rs +++ b/komorebi/tests/socket.rs @@ -56,7 +56,10 @@ fn the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to() { let mut daemon = Daemon( Command::new(env!("CARGO_BIN_EXE_komorebi")) .arg("--fake-backend") + // the logs go to the home directory, which may not be writable (the nix sandbox) .env("XDG_RUNTIME_DIR", &runtime) + .env("HOME", &runtime) + .env_remove("XDG_DATA_HOME") .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() diff --git a/komorebic/Cargo.toml b/komorebic/Cargo.toml new file mode 100644 index 00000000..f4c5d1e7 --- /dev/null +++ b/komorebic/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "komorebic" +version.workspace = true +description = "The command-line interface for Komorebi, a tiling window manager for KDE Plasma" +edition = "2024" + +[dependencies] +komorebi-client = { path = "../komorebi-client", default-features = false } +version = { path = "../version" } + +clap = { workspace = true } +clap_complete = "4" +chrono = { workspace = true } +color-eyre = { workspace = true } +fs-tail = "0.1" +pastey = { workspace = true } +sysinfo = { workspace = true } + +[features] +default = ["schemars"] +schemars = ["komorebi-client/default"] diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs new file mode 100644 index 00000000..5ef74b49 --- /dev/null +++ b/komorebic/src/main.rs @@ -0,0 +1,239 @@ +//! `komorebic`, the command line interface of komorebi for KDE Plasma. +//! +//! A subcommand that asks something of the daemon is one message on its socket: an order, such as +//! `stop` or `retile`, is written and `komorebic` exits; a question, such as `state` or `query`, +//! is written and the answer is printed. The messages are [`komorebi_client::SocketMessage`]s, +//! sent with [`komorebi_client::send_message`] and [`komorebi_client::send_query`]. +//! +//! The others work without the daemon: `start` runs `komorebi` in the background, `log` follows +//! its log, `data-directory` shows where its socket is, and `completions` prints a completion +//! script for a shell. The hidden `docgen` writes the help of every subcommand as Markdown, wrapped +//! at 100 columns whatever the width of the terminal, which is how `docs/cli` is made. + +use chrono::Utc; +use clap::CommandFactory; +use clap::Parser; +use color_eyre::eyre; +use fs_tail::TailedFile; +use komorebi_client::SocketMessage; +use komorebi_client::StateQuery; +use komorebi_client::send_message; +use komorebi_client::send_query; +use std::fs::File; +use std::io::BufRead; +use std::io::Write; +use std::path::PathBuf; +use std::process::Command; +use std::process::Stdio; +use std::time::Duration; +use sysinfo::ProcessesToUpdate; + +macro_rules! gen_enum_subcommand_args { + // SubCommand Pattern: Enum Type + ( $( $name:ident: $element:ty ),+ $(,)? ) => { + $( + pastey::paste! { + #[derive(clap::Parser)] + pub struct $name { + #[clap(value_enum)] + [<$element:snake>]: $element + } + } + )+ + }; +} + +gen_enum_subcommand_args! { + Query: StateQuery, +} + +#[derive(Parser)] +#[allow(clippy::struct_excessive_bools)] +struct Start { + /// Arguments to pass to komorebi, after a `--`: `komorebic start -- --log-level debug` + #[clap(last = true)] + komorebi_args: Vec, +} + +#[derive(Parser)] +struct Stop {} + +#[derive(Parser)] +struct Docgen { + /// Output directory for generated documentation files + #[clap(short, long)] + output: Option, +} + +#[derive(Parser)] +struct Completions { + #[clap(value_enum)] + shell: clap_complete::Shell, +} + +#[derive(Parser)] +#[clap(author, about, version = version::LONG_VERSION)] +struct Opts { + #[clap(subcommand)] + subcmd: SubCommand, +} + +#[derive(Parser)] +enum SubCommand { + #[clap(hide = true)] + Docgen(Docgen), + /// Generate komorebic CLI completions for the target shell + #[clap(arg_required_else_help = true)] + Completions(Completions), + /// Start komorebi as a background process + Start(Start), + /// Stop the komorebi process + Stop(Stop), + /// Show the path to komorebi's data directory, which has its socket + #[clap(alias = "datadir")] + DataDirectory, + /// Show a JSON representation of the current window manager state + State, + /// Show information about connected monitors + #[clap(alias = "monitor-info")] + MonitorInformation, + /// Query the current window manager state + #[clap(arg_required_else_help = true)] + Query(Query), + /// Tail komorebi's process logs (cancel with Ctrl-C) + Log, + /// Force the retiling of all managed windows + Retile, +} + +fn print_query(message: &SocketMessage) { + match send_query(message) { + Ok(response) => println!("{response}"), + Err(error) => panic!("{}", error), + } +} + +fn main() -> eyre::Result<()> { + let opts: Opts = Opts::parse(); + + match opts.subcmd { + SubCommand::Docgen(args) => { + let mut cli = Opts::command(); + let subcommands = cli.get_subcommands_mut(); + + let output_dir = args.output.unwrap_or_else(|| PathBuf::from("docs/cli")); + std::fs::create_dir_all(&output_dir)?; + + let ignore = [ + "docgen", + "splash", + "alt-focus-hack", + "identify-border-overflow-application", + "load-custom-layout", + "workspace-custom-layout", + "named-workspace-custom-layout", + "workspace-custom-layout-rule", + "named-workspace-custom-layout-rule", + "focus-follows-mouse", + "toggle-focus-follows-mouse", + "format-app-specific-configuration", + ]; + + for cmd in subcommands { + let name = cmd.get_name().to_string(); + if !ignore.contains(&name.as_str()) { + // the same pages whatever the width of the terminal docgen runs in + let help_text = cmd.clone().term_width(100).render_long_help().to_string(); + let outpath = output_dir.join(format!("{name}.md")); + let markdown = format!("```text\n{help_text}\n```\n"); + std::fs::write(&outpath, markdown)?; + println!("{}", outpath.display()); + } + } + } + SubCommand::Completions(args) => { + let mut cli = Opts::command(); + clap_complete::generate(args.shell, &mut cli, "komorebic", &mut std::io::stdout()); + } + SubCommand::Start(args) => { + let mut command = &mut Command::new("komorebi"); + + command = command + .args(&args.komorebi_args) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .stdin(Stdio::null()); + + let mut system = sysinfo::System::new_all(); + system.refresh_processes(ProcessesToUpdate::All, true); + + let mut attempts = 0; + let mut running = system + .processes_by_exact_name("komorebi".as_ref()) + .next() + .is_some(); + + while !running && attempts <= 2 { + command.spawn()?; + + print!("Waiting for komorebi to start... "); + std::io::stdout().flush()?; + std::thread::sleep(Duration::from_secs(3)); + + system.refresh_processes(ProcessesToUpdate::All, true); + + if system + .processes_by_exact_name("komorebi".as_ref()) + .next() + .is_some() + { + println!("Started!"); + running = true; + } else { + println!("komorebi did not start... Trying again"); + attempts += 1; + } + } + + if !running { + println!("\nRunning komorebi directly for detailed error output\n"); + if let Ok(output) = Command::new("komorebi").args(&args.komorebi_args).output() { + println!("{}", String::from_utf8(output.stderr)?); + } + } + } + SubCommand::Stop(_) => { + send_message(&SocketMessage::Stop)?; + } + SubCommand::DataDirectory => { + let dir = &*komorebi_client::DATA_DIR; + if dir.exists() { + println!("{}", dir.display()); + } + } + SubCommand::Log => { + let timestamp = Utc::now().format("%Y-%m-%d").to_string(); + let color_log = komorebi_client::LOG_DIR.join(format!("komorebi.log.{timestamp}")); + let file = TailedFile::new(File::open(color_log)?); + let locked = file.lock(); + #[allow(clippy::significant_drop_in_scrutinee, clippy::lines_filter_map_ok)] + for line in locked.lines().flatten() { + println!("{line}"); + } + } + SubCommand::Retile => { + send_message(&SocketMessage::Retile)?; + } + SubCommand::State => { + print_query(&SocketMessage::State); + } + SubCommand::Query(args) => { + print_query(&SocketMessage::Query(args.state_query)); + } + SubCommand::MonitorInformation => { + print_query(&SocketMessage::MonitorInformation); + } + } + + Ok(()) +} diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs new file mode 100644 index 00000000..ce285a94 --- /dev/null +++ b/komorebic/tests/cli.rs @@ -0,0 +1,212 @@ +//! `komorebic` as a person runs it, against a socket the test serves in place of the daemon: what +//! each subcommand writes on the socket, and what it prints. + +use std::io::Read; +use std::io::Write; +use std::os::unix::net::UnixListener; +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use std::process::Output; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; +use std::thread::JoinHandle; + +/// A runtime directory for one test, short enough for a unix socket path on macOS, with the +/// `komorebi` directory the daemon would make in it +struct Runtime(PathBuf); + +impl Runtime { + fn new() -> Self { + static NEXT: AtomicU32 = AtomicU32::new(0); + let dir = PathBuf::from(format!( + "/tmp/komorebic-test-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::SeqCst) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("komorebi")).unwrap(); + Self(dir) + } + + /// Listens on the daemon's socket, takes one connection, and answers what it reads on it with + /// `answer`. The thread returns what it read. + fn serve(&self, answer: &'static str) -> JoinHandle { + let listener = UnixListener::bind(self.0.join("komorebi").join("komorebi.sock")).unwrap(); + + std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut message = String::new(); + stream.read_to_string(&mut message).unwrap(); + stream.write_all(answer.as_bytes()).unwrap(); + message + }) + } + + fn komorebic(&self, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(args) + .env("XDG_RUNTIME_DIR", &self.0) + .output() + .unwrap() + } +} + +impl Drop for Runtime { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[test] +fn state_prints_the_answer_of_the_daemon() { + let runtime = Runtime::new(); + let daemon = runtime.serve(r#"{"monitors":{"elements":[],"focused":0}}"#); + + let output = runtime.komorebic(&["state"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!(daemon.join().unwrap(), r#"{"type":"State"}"#); + assert_eq!( + stdout(&output), + "{\"monitors\":{\"elements\":[],\"focused\":0}}\n" + ); +} + +#[test] +fn query_asks_the_question_it_is_given() { + let runtime = Runtime::new(); + let daemon = runtime.serve("1"); + + let output = runtime.komorebic(&["query", "focused-workspace-index"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!( + daemon.join().unwrap(), + r#"{"type":"Query","content":"FocusedWorkspaceIndex"}"# + ); + assert_eq!(stdout(&output), "1\n"); +} + +#[test] +fn monitor_information_prints_the_answer_of_the_daemon() { + let runtime = Runtime::new(); + let daemon = runtime.serve("[]"); + + let output = runtime.komorebic(&["monitor-info"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!(daemon.join().unwrap(), r#"{"type":"MonitorInformation"}"#); + assert_eq!(stdout(&output), "[]\n"); +} + +#[test] +fn stop_and_retile_send_their_message_and_print_nothing() { + for (subcommand, message) in [ + ("stop", r#"{"type":"Stop"}"#), + ("retile", r#"{"type":"Retile"}"#), + ] { + let runtime = Runtime::new(); + let daemon = runtime.serve(""); + + let output = runtime.komorebic(&[subcommand]); + + assert!(output.status.success(), "{subcommand}: {output:?}"); + assert_eq!(daemon.join().unwrap(), message, "{subcommand}"); + assert_eq!(stdout(&output), "", "{subcommand}"); + } +} + +#[test] +fn without_a_daemon_a_question_fails() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["state"]); + + assert!(!output.status.success(), "{output:?}"); + assert_eq!(stdout(&output), ""); +} + +#[test] +fn data_directory_shows_where_the_socket_is() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["data-directory"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!( + stdout(&output), + format!("{}\n", runtime.0.join("komorebi").display()) + ); +} + +#[test] +fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { + let runtime = Runtime::new(); + let docs = runtime.0.join("cli"); + + let output = runtime.komorebic(&["docgen", "--output", docs.to_str().unwrap()]); + + assert!(output.status.success(), "{output:?}"); + let mut pages = std::fs::read_dir(&docs) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect::>(); + pages.sort(); + assert_eq!( + pages, + [ + "completions.md", + "data-directory.md", + "log.md", + "monitor-information.md", + "query.md", + "retile.md", + "start.md", + "state.md", + "stop.md", + ] + ); + + let query = std::fs::read_to_string(Path::new(&docs).join("query.md")).unwrap(); + assert!(query.starts_with("```text\n"), "{query}"); + assert!(query.ends_with("\n```\n"), "{query}"); + assert!(query.contains("focused-workspace-index"), "{query}"); +} + +#[test] +fn docgen_writes_the_same_pages_whatever_the_width_of_the_terminal() { + let runtime = Runtime::new(); + // without a terminal, clap wraps the help at the width in COLUMNS + let query_page = |columns: &str| { + let docs = runtime.0.join(format!("cli-{columns}")); + let output = Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(["docgen", "--output", docs.to_str().unwrap()]) + .env("COLUMNS", columns) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + std::fs::read_to_string(docs.join("query.md")).unwrap() + }; + + let narrow = query_page("40"); + + assert_eq!(narrow, query_page("250")); + // the possible values of a query are wrapped at 100 columns + assert!(narrow.lines().any(|line| line.len() > 40), "{narrow}"); + assert!(narrow.lines().all(|line| line.len() <= 100), "{narrow}"); +} + +#[test] +fn completions_are_a_script_that_knows_the_subcommands() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["completions", "bash"]); + + assert!(output.status.success(), "{output:?}"); + assert!(stdout(&output).contains("monitor-information")); +} diff --git a/nix/tests/vm/default.nix b/nix/tests/vm/default.nix index b530d40d..245f72cb 100644 --- a/nix/tests/vm/default.nix +++ b/nix/tests/vm/default.nix @@ -3,9 +3,9 @@ # the flake. See docs/dev/vm-tests.md. # # `hostPkgs` is the pkgs of the machine that runs QEMU; the guests are always Linux. `komorebiFor` -# returns the komorebi package of a system, and the guests get the one of their own. `scale` says -# how much slower than KVM that machine is (1 for KVM, 1.5 for HVF on a Mac, 8 for TCG), and every -# wait in the suites is multiplied by it. +# returns the package of `komorebi` and `komorebic` for a system, and the guests get the one of +# their own. `scale` says how much slower than KVM that machine is (1 for KVM, 1.5 for HVF on a +# Mac, 8 for TCG), and every wait in the suites is multiplied by it. { hostPkgs, komorebiFor, diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index 86bf3d22..b7eae826 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -1,9 +1,11 @@ """A KWin session inside a test machine, and the tools to look at it.""" +import json import shlex import time from collections.abc import Callable from dataclasses import dataclass +from typing import Any from PIL import Image @@ -237,6 +239,53 @@ class Kde: """The daemon's log since it was last started, or the empty string before that.""" return self.machine.execute(f"cat {self.runtime}/komorebi-{self.name}.log")[1] + def komorebic(self, *args: str) -> str: + """Runs `komorebic` with `args` inside the session and returns what it printed. + + It fails the test unless `komorebic` succeeds, as it does when no daemon answers. + `komorebic` finds the daemon's socket in the user's runtime directory, which every session + of the user shares, so one daemon at a time can answer it. + """ + return self.sh(shlex.join(["komorebic", *args])) + + def state(self, attempts: int = 10) -> dict[str, Any]: + """The daemon's state, as `komorebic state` prints it. + + The daemon answers a query when it can take hold of the window manager within a second, + and answers nothing when it cannot, which is what a daemon busy with a window that has + just opened does on a machine that is loaded or slow: `komorebic` then prints an empty + line and succeeds. It also gives the daemon a second to answer, and fails when that is not + enough. The query is asked again, a second (times `scale`) after an empty answer or a + failure, up to `attempts` times, and fails the test if the daemon does not answer every + time. An answer that is not JSON and not empty fails at once. + """ + for attempt in range(attempts): + status, out = self.run(shlex.join(["komorebic", "state"])) + if status == 0 and out.strip(): + return json.loads(out) + if attempt + 1 < attempts: + time.sleep(self.scale) + raise AssertionError( + f"the daemon did not answer `komorebic state`, {attempts} times: {status} {out!r}" + ) + + def focused_title(self, workspace: int = 0) -> str: + """The title of the window the daemon has focused on a workspace of the first monitor. + + That is the focused window of the workspace's focused container, as the daemon's state + has it, or the empty string when the workspace has no container. + """ + containers = self._workspace(workspace)["containers"] + if not containers["elements"]: + return "" + windows = containers["elements"][containers["focused"]]["windows"] + return windows["elements"][windows["focused"]]["details"]["title"] + + def managed(self, workspace: int = 0) -> int: + """The number of windows the daemon has on a workspace of the first monitor.""" + containers = self._workspace(workspace)["containers"]["elements"] + return sum(len(container["windows"]["elements"]) for container in containers) + def monitor_bridge(self, path: str) -> None: """Starts recording the bridge's traffic on the session bus to `path`, in the background. @@ -337,6 +386,9 @@ class Kde: """The number of outputs KWin has enabled.""" return int(self.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'")) + def _workspace(self, workspace: int) -> dict[str, Any]: + return self.state()["monitors"]["elements"][0]["workspaces"]["elements"][workspace] + def _wrap(self, command: str, session: bool = True) -> str: env = self.env if session else f"XDG_RUNTIME_DIR={shlex.quote(self.runtime)}" return f"runuser -u {self.user} -- env {env} sh -c {shlex.quote(command)}" diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index 2675538a..9e246032 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -1,3 +1,4 @@ +import json import shlex import pytest @@ -265,3 +266,144 @@ def test_restart_kwin_reports_the_journal_when_kwin_does_not_come_back( with pytest.raises(AssertionError, match="the socket is taken"): Kde(machine, "main", scale=0.01).restart_kwin() + + +def test_komorebic_runs_inside_the_session_and_returns_what_it_printed( + machine: FakeMachine, +) -> None: + machine.reply("komorebic query", output="2\n") + + assert Kde(machine, "main").komorebic("query", "focused-workspace-index") == "2\n" + (command,) = machine.commands + assert inner(command) == "komorebic query focused-workspace-index" + assert "WAYLAND_DISPLAY=wayland-main" in command + assert "XDG_RUNTIME_DIR=/run/user/1000" in command + + +def test_komorebic_fails_the_test_when_no_daemon_answers(machine: FakeMachine) -> None: + machine.reply("komorebic", status=1, output="") + + with pytest.raises(AssertionError, match="komorebic state"): + Kde(machine, "main").komorebic("state") + + +def test_a_daemon_that_says_nothing_is_asked_again( + machine: FakeMachine, monkeypatch: pytest.MonkeyPatch +) -> None: + kde = Kde(machine, "main", scale=0.0) + answers = iter(["\n", "\n", a_state(workspace())]) + + def execute(command: str, /) -> tuple[int, str]: + machine.commands.append(command) + return 0, next(answers) + + monkeypatch.setattr(machine, "execute", execute) + + assert kde.state()["monitors"]["focused"] == 0 + assert len(machine.commands) == 3 + + +def test_a_daemon_that_always_says_nothing_fails_the_test_after_the_attempts( + machine: FakeMachine, +) -> None: + machine.reply("komorebic state", output="\n") + + with pytest.raises(AssertionError, match="did not answer"): + Kde(machine, "main", scale=0.0).state(attempts=3) + assert len(machine.commands) == 3 + + +def test_a_komorebic_that_gives_up_waiting_is_asked_again( + machine: FakeMachine, monkeypatch: pytest.MonkeyPatch +) -> None: + # `komorebic` waits a second for the daemon and panics (exit status 101) when it is not enough + answers = iter([(101, "thread 'main' panicked"), (0, a_state(workspace()))]) + + def execute(command: str, /) -> tuple[int, str]: + machine.commands.append(command) + return next(answers) + + monkeypatch.setattr(machine, "execute", execute) + + assert Kde(machine, "main", scale=0.0).state()["monitors"]["focused"] == 0 + assert len(machine.commands) == 2 + + +def test_an_answer_that_is_not_json_fails_at_once(machine: FakeMachine) -> None: + machine.reply("komorebic state", output="panic: Resource temporarily unavailable\n") + + with pytest.raises(ValueError): + Kde(machine, "main", scale=0.0).state() + assert len(machine.commands) == 1 + + +def window(title: str) -> dict[str, object]: + return {"id": 1, "details": {"title": title, "exe": "foot", "class": "foot", "path": ""}} + + +def container(*titles: str, focused: int = 0) -> dict[str, object]: + return { + "id": "c", + "locked": False, + "windows": {"elements": [window(t) for t in titles], "focused": focused}, + } + + +def workspace(*containers: dict[str, object], focused: int = 0) -> dict[str, object]: + return {"containers": {"elements": list(containers), "focused": focused}} + + +def a_state(*workspaces: dict[str, object]) -> str: + """What `komorebic state` prints for one monitor with these workspaces.""" + monitor = {"id": 1, "workspaces": {"elements": list(workspaces), "focused": 0}} + return json.dumps({"monitors": {"elements": [monitor], "focused": 0}}) + + +def test_the_state_is_what_komorebic_state_prints(machine: FakeMachine) -> None: + machine.reply("komorebic state", output=a_state(workspace())) + + state = Kde(machine, "main").state() + + assert state["monitors"]["elements"][0]["workspaces"]["focused"] == 0 + assert [inner(command) for command in machine.commands] == ["komorebic state"] + + +def test_managed_counts_the_windows_of_every_container_of_the_workspace( + machine: FakeMachine, +) -> None: + machine.reply( + "komorebic state", + output=a_state(workspace(container("a", "b"), container("c")), workspace(container("d"))), + ) + kde = Kde(machine, "main") + + assert kde.managed() == 3 + assert kde.managed(1) == 1 + + +def test_managed_is_zero_for_a_workspace_without_containers(machine: FakeMachine) -> None: + machine.reply("komorebic state", output=a_state(workspace())) + + assert Kde(machine, "main").managed() == 0 + + +def test_focused_title_is_the_focused_window_of_the_focused_container( + machine: FakeMachine, +) -> None: + machine.reply( + "komorebic state", + output=a_state( + workspace(container("a"), container("b", "c", focused=1), focused=1), + workspace(container("d")), + ), + ) + kde = Kde(machine, "main") + + assert kde.focused_title() == "c" + assert kde.focused_title(1) == "d" + + +def test_focused_title_is_empty_for_a_workspace_without_containers(machine: FakeMachine) -> None: + machine.reply("komorebic state", output=a_state(workspace())) + + assert Kde(machine, "main").focused_title() == "" diff --git a/nix/tests/vm/nodes/headless.nix b/nix/tests/vm/nodes/headless.nix index 638c6d15..bd0ccb22 100644 --- a/nix/tests/vm/nodes/headless.nix +++ b/nix/tests/vm/nodes/headless.nix @@ -2,7 +2,8 @@ # own user units, once for every session a test starts, each with its own private session bus and # Wayland socket (`session-bus@NAME`, `kwin-virtual@NAME`). A virtual KWin has no real output, so it # cannot draw: pixel and pointer tests use the session node instead. `komorebi@NAME` runs the daemon -# in a session; `komorebi` is the package, which the test framework passes in. +# in a session; `komorebi` is the package of the daemon and `komorebic`, which the test framework +# passes in. { config, lib, diff --git a/nix/tests/vm/suites/core-e2e/test.py b/nix/tests/vm/suites/core-e2e/test.py index e711fe49..231508b9 100644 --- a/nix/tests/vm/suites/core-e2e/test.py +++ b/nix/tests/vm/suites/core-e2e/test.py @@ -1,9 +1,12 @@ # komorebi tiles a real KWin. What only a real KWin can tell: that the commands the daemon queues # reach KWin through the held call and that KWin carries them out, so that each window is where # the daemon asked for it (`komorebi/tests/wm_events.rs` checks the window manager's side against -# the fake), and that the daemon and KWin agree on which window has the focus. A window manager -# that agrees with itself proves nothing, so what the daemon believes is read from its debug log -# and what KWin has through kdotool. +# the fake), that the daemon and KWin agree on which window has the focus, that `komorebic` reaches +# the daemon of a session and reads its state, and that `komorebic stop` gives KWin back what the +# daemon set up in it. A window manager that agrees with itself proves nothing, so what the daemon +# believes is read from its debug log and from `komorebic state`, and what KWin has through kdotool. +import json + from komorebi_vm import Checks, Kde, Rect, daemon W, H = 1920, 1080 @@ -53,6 +56,18 @@ def focus_agrees() -> bool: return daemon.window_ids(log).get(kde.title(active)) == focus_changes[-1] +def answering() -> bool: + """`komorebic monitor-information` is answered, with the session's one output.""" + status, out = kde.run("komorebic monitor-information") + return status == 0 and json.loads(out)[0]["size"]["right"] == W + + +def state_agrees() -> bool: + """The window komorebi's state has focused is the one KWin has.""" + active = kde.active() + return active != "" and kde.title(active) == kde.focused_title() + + def report(titles: list[str]) -> None: for title in titles: print(f" {title}: asked {asked(title)}, has {kde.rect(kde.wid(title))}") @@ -65,6 +80,7 @@ checks.check( kde.wait_for(lambda: "loaded the KWin bridge script" in daemon_log(), timeout=30), ) checks.check("KWin runs the script", kde.script_loaded()) +checks.check("the daemon is up and answering komorebic", kde.wait_for(answering, timeout=30)) print("== 2. three windows are tiled") titles = ["win1", "win2", "win3"] @@ -83,11 +99,14 @@ checks.check("win1 and win3 do not overlap", not rects[0].overlaps(rects[2])) checks.check("win2 and win3 do not overlap", not rects[1].overlaps(rects[2])) checks.check("the windows share the screen: none is full width", all(r.w < W - 20 for r in rects)) checks.check("KWin and the daemon agree on the focused window", kde.wait_for(focus_agrees)) +checks.check("komorebi manages the three windows", kde.wait_for(lambda: kde.managed() == 3)) +checks.check("komorebi's state focuses the window KWin does", kde.wait_for(state_agrees)) print("== 3. the focus moves by hand") kde.activate(kde.wid("win1")) checks.check("KWin focused win1", kde.wait_for(lambda: kde.title(kde.active()) == "win1")) checks.check("... and the daemon followed", kde.wait_for(focus_agrees)) +checks.check("... and its state says so", kde.wait_for(state_agrees)) print("== 4. minimize and restore") kde.minimize(kde.wid("win2")) @@ -130,13 +149,36 @@ checks.check( ), ) report(["win1", "win2"]) +checks.check("komorebi manages the two that are left", kde.wait_for(lambda: kde.managed() == 2)) checks.check("KWin carried out every command", "the bridge could not do" not in daemon_log()) -print("== 6. stop") -kde.stop_komorebi() -checks.check("the daemon exited", not kde.komorebi_running()) +print("== 6. KWin restarts under the daemon") +kde.restart_kwin() +checks.check( + "the daemon loaded its script into the new KWin", + kde.wait_for(lambda: daemon_log().count("loaded the KWin bridge script") == 2, timeout=30), +) +checks.check( + "komorebi let go of the windows of the old KWin", kde.wait_for(lambda: kde.managed() == 0) +) +kde.spawn("foot -T afterwards sleep 3000") +kde.wait_for(lambda: kde.wid("afterwards") != "", timeout=30) +checks.check("a window opened in the new KWin is managed", kde.wait_for(lambda: kde.managed() == 1)) +checks.check( + "... and tiled on its own", + kde.wait_for( + lambda: where_asked("afterwards") and kde.rect(kde.wid("afterwards")).w > W - 100, + timeout=20, + ), +) +report(["afterwards"]) + +print("== 7. komorebic stop") +kde.komorebic("stop") +checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running())) +checks.check("its socket is gone", kde.run(f"test -e {kde.runtime}/komorebi/komorebi.sock")[0] != 0) checks.check("the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded())) -checks.check("the windows stay", kde.wid("win1") != "" and kde.wid("win2") != "") +checks.check("the window stays", kde.wid("afterwards") != "") kde.stop() checks.finish() From e2d757bbb0e85af833a07fe9a4b52b2a189f84d3 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 14:41:18 -0700 Subject: [PATCH 016/255] feat(wm): subscribe to notifications A program such as a status bar has to follow the window manager, and so far it could only ask: komorebi on Windows and on macOS sends notifications for that. The daemon now keeps subscribers, each a Unix socket in its data directory that a program listens on, and after each event and each message it handles, it connects to every subscriber and writes the event or the message with the state after it. A subscriber can ask to be sent only what changed the state; a window that is shown and a new subscription are always sent, so a subscriber has the state as soon as it subscribes. A subscriber that cannot be connected to is dropped with its socket file and not tried again, and a stopping daemon closes an empty connection to each one. komorebic gains subscribe-socket and unsubscribe-socket, and komorebi-client subscribe and subscribe_with_options, which bind the socket and subscribe. The tests subscribe through real sockets against the fake desktop: a shown window is sent with the state that has it, a subscriber that filters is not sent a question that changed nothing, and one that is gone is dropped. --- README.md | 13 +- docs/cli/subscribe-socket.md | 14 + docs/cli/unsubscribe-socket.md | 14 + docs/dev/ARCHITECTURE.md | 66 ++++- docs/dev/DESIGN.md | 11 + docs/dev/PLATFORM.md | 9 +- docs/index.md | 6 +- docs/usage/running-komorebi.md | 3 + docs/usage/subscribing-to-notifications.md | 83 ++++++ komorebi-client/src/lib.rs | 160 ++++++++++++ komorebi-client/tests/subscribe.rs | 281 +++++++++++++++++++++ komorebi/src/core/mod.rs | 44 +++- komorebi/src/lib.rs | 196 +++++++++++++- komorebi/src/main.rs | 12 + komorebi/src/process_command.rs | 51 +++- komorebi/src/process_event.rs | 23 ++ komorebi/src/state.rs | 31 ++- komorebi/src/window_manager.rs | 25 +- komorebic/src/main.rs | 36 +++ komorebic/tests/cli.rs | 25 ++ 20 files changed, 1078 insertions(+), 25 deletions(-) create mode 100644 docs/cli/subscribe-socket.md create mode 100644 docs/cli/unsubscribe-socket.md create mode 100644 docs/usage/subscribing-to-notifications.md create mode 100644 komorebi-client/tests/subscribe.rs diff --git a/README.md b/README.md index 75687334..abb6b4ee 100644 --- a/README.md +++ b/README.md @@ -62,10 +62,12 @@ without a checkout of the toolchain. (`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. It answers the messages on the daemon's - socket (`core::SocketMessage`, `process_command`) and shows its state - (`state`). + socket (`core::SocketMessage`, `process_command`), shows its state (`state`), + and sends its subscribers a notification of each event and message it handles + (`notify_subscribers`). - [`komorebi-client`](komorebi-client): a library that sends messages to the - daemon and reads its answers, and re-exports the types they are made of. + daemon, reads its answers, subscribes to its notifications, and re-exports + the types they are made of. - [`komorebic`](komorebic): the command line. A subcommand that asks something of the daemon is one message on its socket; `start`, `log`, `data-directory`, `completions` and the hidden `docgen` work without the daemon. @@ -118,6 +120,11 @@ Everything else reaches the daemon as a message on its socket: one JSON `SocketMessage` per line, handled one at a time with the window manager locked. A message that asks a question is answered on the same connection. +A program such as a status bar can subscribe to the daemon's notifications: it +listens on a socket of its own, and after each event and each message, the +daemon connects to it and writes the event or the message with the state of +the window manager. + ## Documentation The user guide starts at [`docs/index.md`](docs/index.md), and diff --git a/docs/cli/subscribe-socket.md b/docs/cli/subscribe-socket.md new file mode 100644 index 00000000..647ec0aa --- /dev/null +++ b/docs/cli/subscribe-socket.md @@ -0,0 +1,14 @@ +```text +Subscribe to komorebi events using a Unix Domain Socket + +Usage: subscribe-socket + +Arguments: + + Name of the socket to send event notifications to + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/unsubscribe-socket.md b/docs/cli/unsubscribe-socket.md new file mode 100644 index 00000000..faaaf985 --- /dev/null +++ b/docs/cli/unsubscribe-socket.md @@ -0,0 +1,14 @@ +```text +Unsubscribe from komorebi events + +Usage: unsubscribe-socket + +Arguments: + + Name of the socket to stop sending event notifications to + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 28aa7885..9cb61ff1 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -7,8 +7,9 @@ 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, the backend that reaches KWin, -how an event about a window becomes a tile, and how a message on the daemon's socket is -answered. It grows with the code: each part of the daemon that is added has its place here. +how an event about a window becomes a tile, how a message on the daemon's socket is +answered, and how subscribers are notified of both. It grows with the code: each part of the +daemon that is added has its place here. ## Vocabulary @@ -28,6 +29,10 @@ answered. It grows with the code: each part of the daemon that is added has its (retile, stop) or a question (the state, the monitors, one [`StateQuery`]). - **State**: the window manager's monitors, workspaces, containers and windows, and its settings, as the daemon answers a `State` message with them ([`State`]). +- **Subscriber**: a program that listens on a socket of its own in [`DATA_DIR`] and has + asked the daemon, by the name of that socket, to send it notifications. +- **Notification**: what a subscriber is sent after each event and each message the window + manager handles: the event or the message, and the state after it ([`Notification`]). - **Compositor**: the program that owns the screen and the windows. On KDE Plasma it is KWin. - **Backend**: the implementation of the [`Backend`](../../komorebi/src/backend/mod.rs) @@ -191,6 +196,37 @@ connection close with no answer. what it set up in the compositor (the KWin backend unloads the bridge), and exits with status 0. `SIGINT` and `SIGTERM` do the same from `main.rs`, with the exit status 130. +## Notifications + +A subscriber binds a socket in [`DATA_DIR`] and sends `AddSubscriberSocket` with its name, +or `AddSubscriberSocketWithOptions` with its name and [`SubscribeOptions`] +([`subscribe`], [`subscribe_with_options`], `komorebic subscribe-socket`). +[`WindowManager::process_command`] records it in [`SUBSCRIPTION_SOCKETS`], and its options in +[`SUBSCRIPTION_SOCKET_OPTIONS`]. `RemoveSubscriberSocket` takes it out again. The +subscribers are kept in memory only, and a daemon that restarts has none. + +At the end of [`WindowManager::process_event`] and of [`WindowManager::process_command`], +the window manager calls [`notify_subscribers`] with a [`Notification`]: the event or the +message ([`NotificationEvent`]), and the [`State`] after it. A [`State`] made before the event +or the message is compared with the window manager after it ([`State::has_been_modified`]); +the monitors are compared down to the windows, and a window by its id only. An event about a +window komorebi does not manage, and a message that fails, return before this and are not +notified. + +[`notify_subscribers`] serializes the notification once, and for each subscriber connects to +its socket, writes the JSON and closes the connection, all on the thread that handled the +event or the message, with the window manager still locked. A subscriber with +`filter_state_changes` is skipped when the state did not change, unless the notification is +about a window being shown or a subscriber being added. A subscriber that cannot be +connected to is removed, with its socket file, after the loop. Writing to a subscriber that +was connected to has no timeout, and a failed write returns an error from the call that +handled the event or the message. A subscriber that stops reading therefore holds the window +manager, and with it the thread that handles events: the backend's events wait in the +channel of [`window_manager_event_listener`], and past 20 the backend drops them. + +When the daemon stops ([`WindowManager::stop`], or `SIGINT` and `SIGTERM` in `main.rs`), it +connects to each subscriber and shuts the connection down without writing anything. + ## The parts - [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the @@ -220,9 +256,13 @@ status 0. `SIGINT` and `SIGTERM` do the same from `main.rs`, with the exit statu [`bridge.js`](../../komorebi/src/kwin/bridge.js), the bridge. - [`process_command`](../../komorebi/src/process_command.rs): the thread that listens on the socket, and what the window manager does with each message. -- [`state`](../../komorebi/src/state.rs): the [`State`] a `State` message is answered with. +- [`state`](../../komorebi/src/state.rs): the [`State`] a `State` message is answered with, + and whether an event or a message changed it. +- [`lib.rs`](../../komorebi/src/lib.rs): the subscribers, the [`Notification`], and + [`notify_subscribers`]. - [`komorebi-client`](../../komorebi-client/src/lib.rs): a library that writes messages on - the socket and reads the answers, for programs that talk to the daemon. + the socket and reads the answers, and subscribes to notifications, for programs that talk + to the daemon. - [`komorebic`](../../komorebic/src/main.rs): the command line. A subcommand that asks something of the daemon is one message, sent with `komorebi-client`; `start` runs the daemon, `log` follows its log file in [`LOG_DIR`], and the hidden `docgen` writes @@ -282,6 +322,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | Messages are handled one at a time, and in order on one connection | framework path: [`read_commands_uds`] reads a connection line by line and handles each message with the window manager locked | `the_messages_on_one_connection_are_handled_in_order` | none | | A socket left behind by a daemon that did not stop cleanly does not keep the next one from starting | framework path: [`WindowManager::new`] removes the file before it binds | `a_socket_file_left_behind_is_replaced` | none | | A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | +| A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | 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, checking what KWin is asked to do for each | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a command for a window KWin no longer has is given back, and the rest are carried out` | none | @@ -326,6 +367,9 @@ A window is shown, and ends up on a tile: `focus`, and the pointer follows it (on KWin, through its "Move Mouse to Focus" shortcut). 8. The index is rebuilt again, so the next event finds the window. +9. [`notify_subscribers`] sends every subscriber a [`Notification`] of the `Show`, with the + state that now has the window. A `Show` is sent to a subscriber with + `filter_state_changes` too, whether or not it changed the state. ## One message, end to end @@ -341,7 +385,8 @@ A window is shown, and ends up on a tile: every monitor with its workspaces, containers and windows. Each window is serialized with what the backend reports about it now: its frame, title, executable, class and path. 5. The state is written to the connection as pretty-printed JSON, and the index of managed - windows is rebuilt, as after every message. + windows is rebuilt, as after every message. The subscribers are sent a notification of + the `State` message, except those with `filter_state_changes`: it changed nothing. 6. There are no more lines, so `read_commands_uds` returns and the connection is closed. `send_query` has read to the end, and returns the JSON, which `komorebic` prints. @@ -362,6 +407,8 @@ A window is shown, and ends up on a tile: each message does, and the tests that send messages through a real socket. - [`komorebi-client/src/lib.rs`](../../komorebi-client/src/lib.rs): the client side of the socket. +- [`komorebi-client/tests/subscribe.rs`](../../komorebi-client/tests/subscribe.rs): + subscribers and the notifications they are sent, through real sockets. - [`komorebic/src/main.rs`](../../komorebic/src/main.rs): the subcommands, and [`komorebic/tests/cli.rs`](../../komorebic/tests/cli.rs), what each writes on the socket. - [`komorebi/src/kwin/mod.rs`](../../komorebi/src/kwin/mod.rs): the KWin backend, its D-Bus @@ -421,6 +468,13 @@ A window is shown, and ends up on a tile: [`SocketMessage`]: ../../komorebi/src/core/mod.rs [`StateQuery`]: ../../komorebi/src/core/mod.rs [`State`]: ../../komorebi/src/state.rs +[`State::has_been_modified`]: ../../komorebi/src/state.rs +[`SubscribeOptions`]: ../../komorebi/src/core/mod.rs +[`Notification`]: ../../komorebi/src/lib.rs +[`NotificationEvent`]: ../../komorebi/src/lib.rs +[`notify_subscribers`]: ../../komorebi/src/lib.rs +[`SUBSCRIPTION_SOCKETS`]: ../../komorebi/src/lib.rs +[`SUBSCRIPTION_SOCKET_OPTIONS`]: ../../komorebi/src/lib.rs [`WindowManager::new`]: ../../komorebi/src/window_manager.rs [`WindowManager::stop`]: ../../komorebi/src/window_manager.rs [`WindowManager::process_command`]: ../../komorebi/src/process_command.rs @@ -429,3 +483,5 @@ A window is shown, and ends up on a tile: [`send_query`]: ../../komorebi-client/src/lib.rs [`send_message`]: ../../komorebi-client/src/lib.rs [`send_batch`]: ../../komorebi-client/src/lib.rs +[`subscribe`]: ../../komorebi-client/src/lib.rs +[`subscribe_with_options`]: ../../komorebi-client/src/lib.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 67ab1d07..1454bb66 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -171,3 +171,14 @@ Because the daemon takes no input but its socket. `komorebic` turns a command li message on the socket and, for a question, prints the answer. A key binding, a script and a person at a terminal all drive komorebi the same way, by running `komorebic` (the design notes of komorebi for Mac, linked above). + +## Why does komorebi send notifications to subscribers? + +So that a program such as a status bar can follow the window manager. The README of komorebi +for Windows demonstrates a custom status bar integrated through its notifications +([Window Manager Event Subscriptions](https://github.com/LGUG2Z/komorebi#window-manager-event-subscriptions)), +and komorebi for Mac sends the same notifications to Unix sockets, which is also how +`komorebic` talks to its daemon +([its README](https://github.com/LGUG2Z/komorebi-for-mac#window-manager-event-subscriptions)). +A subscriber here is a Unix socket, as on macOS. The named pipes that komorebi on Windows +sends notifications to are not ported, since the socket subscribers do the same. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index e1870181..d56e38fe 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -89,10 +89,10 @@ an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a runnin #### What komorebi leaves behind When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it asks KWin -to unload the script and removes the socket. 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, and the socket file in the runtime directory, until the next start -replaces both or the session ends. +to unload the script, closes an empty connection to each subscriber, and removes the socket. +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, and the socket file in +the runtime directory, until the next start replaces both or the session ends. ### A headless KWin @@ -144,6 +144,7 @@ What komorebi calls: |---|---|---| | `$XDG_RUNTIME_DIR/komorebi/bridge.js` | the script KWin loads, with its configuration (the D-Bus names and the hold time of `Poll`) on its first line | written at every start; the directory is removed at logout | | `$XDG_RUNTIME_DIR/komorebi/komorebi.sock` | the command socket | bound once the daemon is connected to KWin, after a file left there is removed; removed when the daemon stops | +| `$XDG_RUNTIME_DIR/komorebi/NAME` | the socket of a subscriber, which the subscriber binds and names in its subscription | removed by the daemon, with the subscriber, when it cannot connect to it | | `$XDG_DATA_HOME/komorebi/komorebi.log.YYYY-MM-DD` | the daemon's log, with colors, which `komorebic log` follows | a file a day (the UTC date), never removed by komorebi | | `$XDG_DATA_HOME/komorebi/komorebi_plaintext.log.YYYY-MM-DD` | the same log without colors | as above | diff --git a/docs/index.md b/docs/index.md index ef04d17f..7a5f98a1 100644 --- a/docs/index.md +++ b/docs/index.md @@ -29,8 +29,10 @@ key bindings --------> komorebic <------> komorebi ## Getting started [Running komorebi](usage/running-komorebi.md) explains how to get the two programs, start and -stop the daemon, ask it what it is doing and read its log. The [CLI reference](cli/start.md) -has a page for every `komorebic` command, generated from its help. +stop the daemon, ask it what it is doing and read its log. +[Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program +such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page +for every `komorebic` command, generated from its help. ## Community diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md index 748254bd..0e0eb08f 100644 --- a/docs/usage/running-komorebi.md +++ b/docs/usage/running-komorebi.md @@ -66,6 +66,9 @@ a window that was moved by hand back on its tile. When the daemon is not running, these commands fail: there is no socket to write to. +A program that wants to know what komorebi does without asking can subscribe to its +notifications instead ([Subscribing to notifications](subscribing-to-notifications.md)). + ## The socket and the data directory The daemon listens on `komorebi.sock` in its data directory, `$XDG_RUNTIME_DIR/komorebi` diff --git a/docs/usage/subscribing-to-notifications.md b/docs/usage/subscribing-to-notifications.md new file mode 100644 index 00000000..79f34b8c --- /dev/null +++ b/docs/usage/subscribing-to-notifications.md @@ -0,0 +1,83 @@ +# Subscribing to notifications + +A program such as a status bar, a widget or a script can follow what komorebi does by +subscribing to its notifications. After each event the window manager handles (a window +was shown, closed, focused, minimized or restored) and each message it takes on its socket, +the daemon sends every subscriber a notification: the event or the message, and the state +of the window manager after it. + +## Subscribing + +A subscriber listens on a Unix socket of its own in the daemon's data directory, +`$XDG_RUNTIME_DIR/komorebi` (on NixOS and most systemd distributions, +`/run/user//komorebi`), and tells the daemon the name of the socket with +[`komorebic subscribe-socket`](../cli/subscribe-socket.md). The socket has to exist before +it subscribes: the daemon sends the notification of the subscription at once, and removes a +subscriber it cannot connect to. + +With [socat](http://www.dest-unreach.org/socat/), a shell can subscribe and print every +notification: + +```sh +socat -u UNIX-LISTEN:"$XDG_RUNTIME_DIR/komorebi/bar.sock",fork STDOUT & +komorebic subscribe-socket bar.sock +``` + +[`komorebic unsubscribe-socket bar.sock`](../cli/unsubscribe-socket.md) stops the +notifications. + +## Notifications + +The daemon sends each notification on a new connection to the subscriber's socket: it +connects, writes one JSON object, and closes the connection. There is no newline after the +object. The first notification a subscriber receives is the one of its subscription. + +A notification has two fields: + +- `event`: the event or the message. An event is a window event, with the signal it came + from and the window, such as + `{"type":"Show","content":[{"type":"KWin","content":"WindowAdded"},{"id":...}]}`. A + message is written the way a client writes it on the daemon's socket, such as + `{"type":"Retile"}`. +- `state`: the state of the window manager after it, with the same fields as what + [`komorebic state`](../cli/state.md) prints, on one line. + +An event about a window that komorebi does not manage, and a message that fails, are not +sent. + +## Only when something changed + +A subscriber can ask to be sent a notification only when the event or the message changed +the state, with the `filter_state_changes` option. It is still sent the notification of a +window that is shown and of every new subscription, so it receives the state as soon as it +subscribes. `komorebic subscribe-socket` has no option for it; a program writes the message +on the daemon's socket itself: + +```sh +printf '%s' '{"type":"AddSubscriberSocketWithOptions","content":["bar.sock",{"filter_state_changes":true}]}' | + socat - UNIX-CONNECT:"$XDG_RUNTIME_DIR/komorebi/komorebi.sock" +``` + +## When a subscriber goes away + +A subscriber that the daemon cannot connect to, because its program has exited or its +socket was removed, is removed at the next notification, and its socket file with it. The +daemon does not try it again: a program that wants notifications again subscribes again. +The daemon keeps its subscribers only while it runs, so after a restart every program has +to subscribe again. + +When the daemon stops, it connects to each subscriber and closes the connection without +writing anything. + +A subscriber should accept and read every connection as it comes. The daemon writes each +notification while the window manager is locked, and waits when the socket's buffer is +full, so a subscriber that stops reading can hold up the window manager. While it is held +up, the window events KWin reports wait for it, and once 20 are waiting the daemon drops +the ones that come after them. + +## In Rust + +The `komorebi-client` crate has `subscribe` and `subscribe_with_options`, which listen on +the socket, subscribe, and return the listener: each connection on it is one +`Notification`. `cargo doc --package komorebi-client --open` shows their documentation, +with an example. diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index c249345e..f06c7f7c 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -9,6 +9,10 @@ //! daemon that is not running is an [`std::io::ErrorKind::NotFound`] or a //! [`std::io::ErrorKind::ConnectionRefused`]. //! +//! [`subscribe`] and [`subscribe_with_options`] make the program a subscriber: they listen on a +//! socket of its own in [`struct@DATA_DIR`], and ask the daemon to send a [`Notification`] to it +//! after each event and each message the window manager handles. +//! //! The crate also re-exports the types the messages and the answers are made of, so that a client //! needs nothing else. //! @@ -51,6 +55,8 @@ pub use komorebi::DATA_DIR; pub use komorebi::LOG_DIR; +pub use komorebi::Notification; +pub use komorebi::NotificationEvent; pub use komorebi::container::Container; pub use komorebi::core::ApplicationIdentifier; pub use komorebi::core::Axis; @@ -66,6 +72,7 @@ pub use komorebi::core::Rect; pub use komorebi::core::Sizing; pub use komorebi::core::SocketMessage; pub use komorebi::core::StateQuery; +pub use komorebi::core::SubscribeOptions; pub use komorebi::core::WindowKind; pub use komorebi::core::pathext::PathExt; pub use komorebi::core::pathext::replace_env_in_path; @@ -77,6 +84,7 @@ use std::io::BufReader; use std::io::Read; use std::io::Write; use std::net::Shutdown; +use std::os::unix::net::UnixListener; use std::os::unix::net::UnixStream; use std::time::Duration; @@ -219,3 +227,155 @@ pub fn send_query(message: &SocketMessage) -> std::io::Result { Ok(response) } + +/// Listens on the socket `name` in [`struct@DATA_DIR`], and asks the daemon to send a +/// [`Notification`] to it after each event and each message the window manager handles +/// +/// A socket file that is left over at that path is removed first. Each notification comes on a +/// new connection, as JSON, and ends when the daemon closes the connection; the first is the +/// notification of the subscription itself. When the daemon stops, it connects and closes the +/// connection without writing anything. +/// +/// A subscriber that the daemon cannot connect to, because its program has exited or its socket +/// was removed, is removed at the next notification, with its socket file. It has to subscribe +/// again: the daemon does not try it again, and does not keep its subscribers when it restarts. +/// +/// # Errors +/// +/// - The socket file left over at that path cannot be removed. +/// - The socket cannot be bound, for example because [`struct@DATA_DIR`] does not exist. +/// - The subscription cannot be sent, for one of the reasons [`send_message`] gives. +/// +/// # Example +/// +/// ```rust +/// # use std::io::{BufRead, BufReader, Write}; +/// # let runtime = format!("/tmp/komorebi-client-doc-subscribe-{}", std::process::id()); +/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?; +/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the sockets are in it +/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock"); +/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?; +/// # let daemon = std::thread::spawn(move || -> std::io::Result { +/// # let (stream, _) = listener.accept()?; +/// # let mut message = String::new(); +/// # BufReader::new(stream).read_line(&mut message)?; +/// # let subscriber = komorebi_client::DATA_DIR.join("bar.sock"); +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let notification = format!(r#"{{"event":{message},"state":{state}}}"#); +/// # std::os::unix::net::UnixStream::connect(subscriber)?.write_all(notification.as_bytes())?; +/// # Ok(message) +/// # }); +/// use std::io::Read; +/// +/// use komorebi_client::Notification; +/// use komorebi_client::NotificationEvent; +/// use komorebi_client::SocketMessage; +/// use komorebi_client::subscribe; +/// +/// let listener = subscribe("bar.sock")?; +/// +/// // the first notification is the one of the subscription +/// let (mut connection, _) = listener.accept()?; +/// let mut json = String::new(); +/// connection.read_to_string(&mut json)?; +/// let notification: Notification = serde_json::from_str(&json)?; +/// assert!(matches!( +/// notification.event, +/// NotificationEvent::Socket(SocketMessage::AddSubscriberSocket(name)) if name == "bar.sock" +/// )); +/// +/// # assert_eq!( +/// # daemon.join().unwrap()?, +/// # r#"{"type":"AddSubscriberSocket","content":"bar.sock"}"# +/// # ); +/// # std::fs::remove_dir_all(&runtime)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn subscribe(name: &str) -> std::io::Result { + let socket = DATA_DIR.join(name); + + match std::fs::remove_file(&socket) { + Ok(()) => {} + Err(error) => match error.kind() { + std::io::ErrorKind::NotFound => {} + _ => { + return Err(error); + } + }, + }; + + let listener = UnixListener::bind(&socket)?; + + send_message(&SocketMessage::AddSubscriberSocket(name.to_string()))?; + + Ok(listener) +} + +/// The same as [`subscribe`], with the [`SubscribeOptions`] the daemon applies to this subscriber +/// +/// With `filter_state_changes`, the daemon sends a notification only when the event or the message +/// changed the [`State`], and always when a window is shown and when a subscriber is added. +/// +/// # Errors +/// +/// The same as [`subscribe`]. +/// +/// # Example +/// +/// ```rust +/// # use std::io::{BufRead, BufReader}; +/// # let runtime = format!("/tmp/komorebi-client-doc-options-{}", std::process::id()); +/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?; +/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the sockets are in it +/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock"); +/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?; +/// # let daemon = std::thread::spawn(move || -> std::io::Result { +/// # let (stream, _) = listener.accept()?; +/// # let mut message = String::new(); +/// # BufReader::new(stream).read_line(&mut message)?; +/// # Ok(message) +/// # }); +/// use komorebi_client::DATA_DIR; +/// use komorebi_client::SubscribeOptions; +/// use komorebi_client::subscribe_with_options; +/// +/// let options = SubscribeOptions { +/// filter_state_changes: true, +/// }; +/// let listener = subscribe_with_options("bar.sock", options)?; +/// +/// let socket = DATA_DIR.join("bar.sock"); +/// assert_eq!(listener.local_addr()?.as_pathname(), Some(socket.as_path())); +/// +/// # assert_eq!( +/// # daemon.join().unwrap()?, +/// # r#"{"type":"AddSubscriberSocketWithOptions","content":["bar.sock",{"filter_state_changes":true}]}"# +/// # ); +/// # std::fs::remove_dir_all(&runtime)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn subscribe_with_options( + name: &str, + options: SubscribeOptions, +) -> std::io::Result { + let socket = DATA_DIR.join(name); + + match std::fs::remove_file(&socket) { + Ok(()) => {} + Err(error) => match error.kind() { + std::io::ErrorKind::NotFound => {} + _ => { + return Err(error); + } + }, + }; + + let listener = UnixListener::bind(&socket)?; + + send_message(&SocketMessage::AddSubscriberSocketWithOptions( + name.to_string(), + options, + ))?; + + Ok(listener) +} diff --git a/komorebi-client/tests/subscribe.rs b/komorebi-client/tests/subscribe.rs new file mode 100644 index 00000000..5c22ee40 --- /dev/null +++ b/komorebi-client/tests/subscribe.rs @@ -0,0 +1,281 @@ +//! Subscribers against a window manager that listens the way the daemon does, with +//! [`listen_for_commands`], over an in-memory desktop with one monitor: each subscriber listens on a +//! socket of its own in a runtime directory of this process, subscribes with `komorebi-client`, and +//! reads the notifications the window manager sends it. +//! +//! The tests share the window manager, and take turns: every subscriber is sent every +//! notification, so a test that ran at the same time as another would read the other's +//! notifications too. Window ids are 901 and up. + +use komorebi::SUBSCRIPTION_SOCKETS; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::set_backend; +use komorebi::process_command::listen_for_commands; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use komorebi::window_manager_event_listener; +use komorebi_client::DATA_DIR; +use komorebi_client::Notification; +use komorebi_client::NotificationEvent; +use komorebi_client::SocketMessage; +use komorebi_client::SubscribeOptions; +use komorebi_client::send_query; +use komorebi_client::subscribe; +use komorebi_client::subscribe_with_options; +use parking_lot::Mutex; +use std::io::ErrorKind; +use std::io::Read; +use std::os::unix::net::UnixListener; +use std::sync::Arc; +use std::sync::OnceLock; +use std::sync::mpsc::Receiver; +use std::time::Duration; + +struct Daemon { + fake: Arc, + wm: Arc>, +} + +impl Daemon { + /// Opens the window `id` and has the window manager handle the event of it being shown + fn show(&self, id: u32) { + self.fake.open_window(id, "foot", "foot", "a terminal"); + self.handle(WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + )); + } + + /// Has the window manager handle the event of the window `id` being minimized + fn minimize(&self, id: u32) { + self.handle(WindowManagerEvent::Minimize( + SystemNotification::KWin(KWinNotification::WindowMinimized), + Window::from(id), + )); + } + + fn handle(&self, event: WindowManagerEvent) { + self.wm.lock().process_event(event).unwrap(); + } +} + +/// Starts the window manager once, and waits for the other tests to be done with it +fn daemon() -> (parking_lot::MutexGuard<'static, ()>, &'static Daemon) { + static TURN: Mutex<()> = parking_lot::const_mutex(()); + static DAEMON: OnceLock = OnceLock::new(); + + let turn = TURN.lock(); + let daemon = DAEMON.get_or_init(|| { + // /tmp: short enough for a unix socket path on macOS + let runtime = format!("/tmp/komorebi-subscribe-test-{}", std::process::id()); + // SAFETY: the first test to get here sets it, before any thread reads the environment + unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; + std::fs::create_dir_all(&*DATA_DIR).unwrap(); + + let fake = Arc::new(FakeBackend::with_one_monitor()); + set_backend(fake.clone()); + + let mut wm = WindowManager::new(window_manager_event_listener::event_rx(), None).unwrap(); + wm.init().unwrap(); + let wm = Arc::new(Mutex::new(wm)); + listen_for_commands(wm.clone()); + + Daemon { fake, wm } + }); + + (turn, daemon) +} + +/// A subscriber whose notifications are read on another thread. It unsubscribes when it is +/// dropped, and waits for the window manager to have handled that. +struct Subscriber { + name: &'static str, + notifications: Receiver, +} + +impl Subscriber { + fn new(name: &'static str, listener: UnixListener) -> Self { + let (sender, notifications) = std::sync::mpsc::channel(); + + std::thread::spawn(move || { + for connection in listener.incoming() { + let mut json = String::new(); + connection.unwrap().read_to_string(&mut json).unwrap(); + let notification = serde_json::from_str(&json).unwrap(); + if sender.send(notification).is_err() { + break; + } + } + }); + + Self { + name, + notifications, + } + } + + /// Returns the notifications received until, and with, the first one whose event `last` is + /// true of, waiting up to five seconds for each + fn until(&self, last: impl Fn(&NotificationEvent) -> bool) -> Vec { + let mut received: Vec = vec![]; + loop { + let notification = self + .notifications + .recv_timeout(Duration::from_secs(5)) + .unwrap_or_else(|_| { + panic!("{} received {received:?}, and then nothing", self.name) + }); + let done = last(¬ification.event); + received.push(notification); + if done { + return received; + } + } + } + + /// Returns the next notification, which is the one of the subscription itself + fn subscribed(&self) -> Notification { + let notification = self + .notifications + .recv_timeout(Duration::from_secs(5)) + .expect("the notification of the subscription"); + assert!( + subscribed(self.name)(¬ification.event), + "{notification:?}" + ); + notification + } +} + +impl Drop for Subscriber { + fn drop(&mut self) { + // send_query returns once the window manager has handled the message and closed the + // connection + let unsubscribe = SocketMessage::RemoveSubscriberSocket(self.name.to_string()); + let _ = send_query(&unsubscribe); + } +} + +fn subscribed(name: &str) -> impl Fn(&NotificationEvent) -> bool + '_ { + move |event| match event { + NotificationEvent::Socket(SocketMessage::AddSubscriberSocket(socket)) + | NotificationEvent::Socket(SocketMessage::AddSubscriberSocketWithOptions(socket, _)) => { + socket == name + } + _ => false, + } +} + +fn shown(id: u32) -> impl Fn(&NotificationEvent) -> bool { + move |event| { + matches!( + event, + NotificationEvent::WindowManager(WindowManagerEvent::Show(_, window)) if window.id == id + ) + } +} + +fn minimized(id: u32) -> impl Fn(&NotificationEvent) -> bool { + move |event| { + matches!( + event, + NotificationEvent::WindowManager(WindowManagerEvent::Minimize(_, window)) if window.id == id + ) + } +} + +fn is_state(notification: &Notification) -> bool { + matches!( + notification.event, + NotificationEvent::Socket(SocketMessage::State) + ) +} + +/// Returns true if and only if the first workspace of the first monitor has the window `id` +fn on_the_workspace(notification: &Notification, id: u32) -> bool { + notification.state.monitors.elements()[0].workspaces()[0].contains_window(id) +} + +#[test] +fn a_subscriber_is_sent_the_window_that_was_shown_and_the_state_after_it() +-> Result<(), Box> { + let (_turn, daemon) = daemon(); + let subscriber = Subscriber::new("shown.sock", subscribe("shown.sock")?); + let subscription = subscriber.subscribed(); + assert!(!on_the_workspace(&subscription, 901)); + + daemon.show(901); + + let received = subscriber.until(shown(901)); + assert_eq!(received.len(), 1, "{received:?}"); + assert!(on_the_workspace(&received[0], 901)); + Ok(()) +} + +#[test] +fn a_subscriber_that_filters_state_changes_is_not_sent_what_changed_nothing() +-> Result<(), Box> { + let (_turn, daemon) = daemon(); + let options = SubscribeOptions { + filter_state_changes: true, + }; + let filtered = Subscriber::new( + "filtered.sock", + subscribe_with_options("filtered.sock", options)?, + ); + filtered.subscribed(); + let everything = Subscriber::new("everything.sock", subscribe("everything.sock")?); + everything.subscribed(); + // a subscriber that filters is sent the subscription of another, which changes nothing + assert!(subscribed("everything.sock")( + &filtered.until(|_| true)[0].event + )); + + // asking for the state changes nothing; a window that is shown is always sent, and one that + // is minimized leaves its workspace, which is a change + send_query(&SocketMessage::State)?; + daemon.show(911); + daemon.minimize(911); + + let received = filtered.until(minimized(911)); + assert!(!received.iter().any(is_state), "{received:?}"); + assert!(shown(911)(&received[0].event), "{received:?}"); + assert!(!on_the_workspace(&received[1], 911)); + let received = everything.until(minimized(911)); + assert!(is_state(&received[0]), "{received:?}"); + Ok(()) +} + +#[test] +fn a_subscriber_that_is_gone_is_dropped_and_not_tried_again() +-> Result<(), Box> { + let (_turn, _daemon) = daemon(); + let socket = DATA_DIR.join("gone.sock"); + let gone = subscribe("gone.sock")?; + let mut json = String::new(); + gone.accept()?.0.read_to_string(&mut json)?; + let notification: Notification = serde_json::from_str(&json)?; + assert!(subscribed("gone.sock")(¬ification.event)); + + // the program exits: the socket file is left behind, and nothing listens on it + drop(gone); + assert!(socket.exists()); + send_query(&SocketMessage::State)?; + + assert!(!SUBSCRIPTION_SOCKETS.lock().contains_key("gone.sock")); + assert!(!socket.exists()); + + // a program that listens on the same socket again is sent nothing until it subscribes again + let again = UnixListener::bind(&socket)?; + again.set_nonblocking(true)?; + send_query(&SocketMessage::State)?; + assert_eq!( + again.accept().map(|_| ()).map_err(|error| error.kind()), + Err(ErrorKind::WouldBlock) + ); + std::fs::remove_file(&socket)?; + Ok(()) +} diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 91d37c9b..f5c474ae 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -6,8 +6,9 @@ //! import from. [`pathext`] resolves environment variables in configured paths and //! [`config_generation`] holds the rules that match applications by what they are called. //! -//! [`SocketMessage`] is every message the daemon takes on its socket, and [`StateQuery`] every -//! question [`SocketMessage::Query`] can ask. +//! [`SocketMessage`] is every message the daemon takes on its socket, [`StateQuery`] every +//! question [`SocketMessage::Query`] can ask, and [`SubscribeOptions`] what a subscriber can ask +//! of its notifications. use clap::ValueEnum; use color_eyre::eyre; @@ -273,6 +274,40 @@ pub enum StateQuery { Version, } +/// The options of a subscriber, which [`SocketMessage::AddSubscriberSocketWithOptions`] sets +/// +/// A subscriber added with [`SocketMessage::AddSubscriberSocket`] has the default options, and is +/// sent a notification for every event and message the window manager handles. With +/// `filter_state_changes`, it is sent one only when the event or the message changed the +/// [`State`](crate::state::State), and always when a window is shown and when a subscriber is +/// added, so a new subscriber receives the state as soon as it subscribes. +/// +/// # Example +/// +/// ```rust +/// use komorebi::core::SocketMessage; +/// use komorebi::core::SubscribeOptions; +/// +/// let options = SubscribeOptions { +/// filter_state_changes: true, +/// }; +/// let message = SocketMessage::AddSubscriberSocketWithOptions(String::from("bar.sock"), options); +/// assert_eq!( +/// String::from_utf8(message.as_bytes()?)?, +/// r#"{"type":"AddSubscriberSocketWithOptions","content":["bar.sock",{"filter_state_changes":true}]}"#, +/// ); +/// +/// assert!(!SubscribeOptions::default().filter_state_changes); +/// +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Default, Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct SubscribeOptions { + /// Only emit notifications when the window manager state has changed + pub filter_state_changes: bool, +} + /// A message to the daemon, as it is written on its socket: JSON, with the variant's name in /// `type` and its arguments, if it has any, in `content`. /// @@ -304,6 +339,11 @@ pub enum SocketMessage { State, MonitorInformation, Query(StateQuery), + AddSubscriberSocket(String), + AddSubscriberSocketWithOptions(String, SubscribeOptions), + RemoveSubscriberSocket(String), + // AddSubscriberPipe(String), + // RemoveSubscriberPipe(String), } impl SocketMessage { diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index d0056428..b3ca5641 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -16,10 +16,25 @@ //! The daemon also listens on a socket, `komorebi.sock` in [`struct@DATA_DIR`], for the messages //! in [`core::SocketMessage`]: [`process_command`] reads them and answers, with the window //! manager's [`state::State`] for one. +//! +//! A program can subscribe to the daemon's notifications with a socket of its own in +//! [`struct@DATA_DIR`]: after each event and each message the window manager handles, +//! [`notify_subscribers`] sends every subscriber a [`Notification`] of it, with the state. +use crate::core::SocketMessage; +use crate::core::SubscribeOptions; +use crate::state::State; +use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; use lazy_static::lazy_static; +use parking_lot::Mutex; +use serde::Deserialize; +use serde::Serialize; +use std::collections::HashMap; +use std::io::Write; +use std::os::unix::net::UnixStream; use std::path::PathBuf; +use std::sync::Arc; use std::sync::atomic::AtomicI32; #[macro_use] @@ -47,9 +62,9 @@ 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 and its command socket: `$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. + /// KWin, its command socket and the sockets of its subscribers: `$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")) @@ -64,6 +79,15 @@ lazy_static! { pub static ref LOG_DIR: PathBuf = dirs::data_local_dir() .expect("there is no local data directory") .join("komorebi"); + /// The subscribers: the name of each one's socket, and its path in [`struct@DATA_DIR`] + pub static ref SUBSCRIPTION_SOCKETS: Arc>> = + Arc::new(Mutex::new(HashMap::new())); + /// The options of the subscribers that were added with options, by the name of their socket + /// + /// An entry is not removed with its subscriber: a subscriber that is added again under the + /// same name, without options, keeps the options it had. + pub static ref SUBSCRIPTION_SOCKET_OPTIONS: Arc>> = + Arc::new(Mutex::new(HashMap::new())); } /// The padding, in pixels, between the edge of a monitor's work area and the tiles of its @@ -72,3 +96,169 @@ pub static DEFAULT_WORKSPACE_PADDING: AtomicI32 = AtomicI32::new(5); /// The padding, in pixels, around each tile, for a monitor that sets none of its own. The default /// for this is 5. pub static DEFAULT_CONTAINER_PADDING: AtomicI32 = AtomicI32::new(5); + +/// The event or the message a [`Notification`] is about +/// +/// It is written as the [`WindowManagerEvent`] or the [`SocketMessage`] it carries, each with its +/// `type`, with no tag around it. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum NotificationEvent { + /// An event the compositor reported about a window + WindowManager(WindowManagerEvent), + /// A message the daemon took on its socket + Socket(SocketMessage), +} + +/// A notification that [`notify_subscribers`] sends each subscriber: an event or a message the +/// window manager handled, and its state after it +/// +/// # Example +/// +/// A subscriber reads a notification as JSON: +/// +/// ```rust +/// use komorebi::Notification; +/// use komorebi::NotificationEvent; +/// use komorebi::core::SocketMessage; +/// use komorebi::window_manager_event::WindowManagerEvent; +/// +/// let state = r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#; +/// +/// let shown = format!( +/// r#"{{"event":{{"type":"Show","content":[{{"type":"KWin","content":"WindowAdded"}},{{"id":7}}]}},"state":{state}}}"# +/// ); +/// let notification: Notification = serde_json::from_str(&shown)?; +/// assert!(matches!( +/// notification.event, +/// NotificationEvent::WindowManager(WindowManagerEvent::Show(_, window)) if window.id == 7 +/// )); +/// +/// let retiled = format!(r#"{{"event":{{"type":"Retile"}},"state":{state}}}"#); +/// let notification: Notification = serde_json::from_str(&retiled)?; +/// assert!(matches!( +/// notification.event, +/// NotificationEvent::Socket(SocketMessage::Retile) +/// )); +/// assert!(notification.state.mouse_follows_focus); +/// +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct Notification { + /// The event or the message the window manager handled + pub event: NotificationEvent, + /// The window manager's state after it + pub state: State, +} + +/// Sends `notification` to every subscriber in [`struct@SUBSCRIPTION_SOCKETS`], and removes the +/// subscribers whose socket cannot be connected to +/// +/// Each subscriber is sent the notification as JSON on a new connection to its socket, which is +/// closed after it. A subscriber with `filter_state_changes` in its [`SubscribeOptions`] is sent it +/// only if `state_has_been_modified`, or if the notification is about a window being shown or a +/// subscriber being added. +/// +/// A subscriber that cannot be connected to (its program has exited, or its socket was removed) +/// is removed, with its socket file, and is not tried again: it has to subscribe again. The +/// notification is written without a timeout, with the window manager locked, so a subscriber that +/// listens and never reads can hold up the window manager when a notification does not fit in the +/// socket's buffer. +/// +/// # Errors +/// +/// - The notification cannot be serialized. +/// - The notification cannot be written to a subscriber that was connected to. The subscribers +/// after it are not sent the notification, and none is removed. +/// +/// # Example +/// +/// ```rust +/// # let runtime = format!("/tmp/komorebi-notify-doc-{}", std::process::id()); +/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?; +/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the sockets are in it +/// use std::io::Read; +/// use std::os::unix::net::UnixListener; +/// +/// use komorebi::DATA_DIR; +/// use komorebi::Notification; +/// use komorebi::NotificationEvent; +/// use komorebi::SUBSCRIPTION_SOCKETS; +/// use komorebi::core::SocketMessage; +/// use komorebi::notify_subscribers; +/// use komorebi::state::State; +/// +/// // a subscriber that listens, and one whose program has exited +/// let bar = UnixListener::bind(DATA_DIR.join("bar.sock"))?; +/// SUBSCRIPTION_SOCKETS.lock().extend([ +/// (String::from("bar.sock"), DATA_DIR.join("bar.sock")), +/// (String::from("gone.sock"), DATA_DIR.join("gone.sock")), +/// ]); +/// +/// let state: State = serde_json::from_str( +/// r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#, +/// )?; +/// let event = NotificationEvent::Socket(SocketMessage::Retile); +/// notify_subscribers(Notification { event, state }, false)?; +/// +/// let mut json = String::new(); +/// bar.accept()?.0.read_to_string(&mut json)?; +/// assert!(json.starts_with(r#"{"event":{"type":"Retile"},"state":{"#), "{json}"); +/// assert!(!SUBSCRIPTION_SOCKETS.lock().contains_key("gone.sock")); +/// +/// # std::fs::remove_dir_all(&runtime)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn notify_subscribers( + notification: Notification, + state_has_been_modified: bool, +) -> eyre::Result<()> { + let is_override_event = matches!( + notification.event, + NotificationEvent::Socket(SocketMessage::AddSubscriberSocket(_)) + | NotificationEvent::Socket(SocketMessage::AddSubscriberSocketWithOptions(_, _)) + | NotificationEvent::WindowManager(WindowManagerEvent::Show(_, _)) + ); + + let notification = &serde_json::to_string(¬ification)?; + let mut stale_sockets = vec![]; + let mut sockets = SUBSCRIPTION_SOCKETS.lock(); + let options = SUBSCRIPTION_SOCKET_OPTIONS.lock(); + + for (socket, path) in &mut *sockets { + let apply_state_filter = (*options) + .get(socket) + .copied() + .unwrap_or_default() + .filter_state_changes; + + if !apply_state_filter || state_has_been_modified || is_override_event { + match UnixStream::connect(path) { + Ok(mut stream) => { + tracing::debug!("pushed notification to subscriber: {socket}"); + stream.write_all(notification.as_bytes())?; + } + Err(_) => { + stale_sockets.push(socket.clone()); + } + } + } + } + + for socket in stale_sockets { + tracing::warn!("removing stale subscription: {socket}"); + sockets.remove(&socket); + let socket_path = DATA_DIR.join(socket); + if let Err(error) = std::fs::remove_file(&socket_path) { + tracing::error!( + "could not remove stale subscriber socket file at {}: {error}", + socket_path.display() + ) + } + } + + Ok(()) +} diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 920791a7..71948819 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -13,6 +13,9 @@ //! //! It logs to standard output and to a file a day in [`struct@LOG_DIR`], which `komorebic log` //! follows. +//! +//! When it stops, it connects to the socket of each subscriber and closes the connection without +//! writing anything, so a subscriber sees the daemon stop as a connection with nothing on it. use clap::Parser; use clap::ValueEnum; @@ -27,6 +30,8 @@ use komorebi::window_manager::WindowManager; use komorebi::window_manager_event_listener; use parking_lot::Mutex; use serde::Deserialize; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; use std::sync::Arc; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::EnvFilter; @@ -191,6 +196,13 @@ fn main() -> eyre::Result<()> { backend::backend().shutdown(); + let sockets = komorebi::SUBSCRIPTION_SOCKETS.lock(); + for path in (*sockets).values() { + if let Ok(stream) = UnixStream::connect(path) { + stream.shutdown(Shutdown::Both)?; + } + } + let socket = DATA_DIR.join("komorebi.sock"); let _ = std::fs::remove_file(socket); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 37759873..ecd3721c 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -10,13 +10,24 @@ //! - **MonitorInformation**: the id, the name and the bounds of each monitor, as JSON. //! - **Query**: one value as text, the answer to a [`StateQuery`]. //! -//! The others answer nothing: **Retile** tiles the focused workspace of every monitor again, and -//! **Stop** stops the daemon ([`WindowManager::stop`]). +//! The others answer nothing: **Retile** tiles the focused workspace of every monitor again, +//! **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name of +//! its socket in the data directory, **RemoveSubscriberSocket** removes one, and **Stop** stops the +//! daemon ([`WindowManager::stop`]). +//! +//! Once a message has been handled, every subscriber is sent a notification of it +//! ([`notify_subscribers`]). +use crate::DATA_DIR; +use crate::Notification; +use crate::NotificationEvent; +use crate::SUBSCRIPTION_SOCKET_OPTIONS; +use crate::SUBSCRIPTION_SOCKETS; use crate::core::Layout; use crate::core::SocketMessage; use crate::core::StateQuery; use crate::monitor::MonitorInformation; +use crate::notify_subscribers; use crate::state::State; use crate::window_manager::WindowManager; use color_eyre::eyre; @@ -77,7 +88,10 @@ pub fn listen_for_commands(wm: Arc>) { } impl WindowManager { - /// Handles one message, and writes the answer to a question to `reply` + /// Handles one message, writes the answer to a question to `reply`, and sends the subscribers + /// a notification of the message + /// + /// A message that fails is not notified. /// /// # Errors /// @@ -85,6 +99,8 @@ impl WindowManager { /// - The window manager fails to retile, for one of the reasons /// [`WindowManager::retile_all`] gives. /// - The answer cannot be written to `reply`. + /// - `Stop` fails, for the reason [`WindowManager::stop`] gives. + /// - The notification cannot be sent, for one of the reasons [`notify_subscribers`] gives. #[tracing::instrument(skip(self, reply, message))] pub fn process_command( &mut self, @@ -93,6 +109,10 @@ impl WindowManager { ) -> eyre::Result<()> { tracing::info!("processing command: {message}"); + #[allow(clippy::useless_asref)] + // We don't have From implemented for &mut WindowManager + let initial_state = State::from(self.as_ref()); + match message { SocketMessage::Retile => self.retile_all()?, SocketMessage::State => { @@ -161,6 +181,23 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::AddSubscriberSocket(ref socket) => { + let mut sockets = SUBSCRIPTION_SOCKETS.lock(); + let socket_path = DATA_DIR.join(socket); + sockets.insert(socket.clone(), socket_path); + } + SocketMessage::AddSubscriberSocketWithOptions(ref socket, options) => { + let mut sockets = SUBSCRIPTION_SOCKETS.lock(); + let socket_path = DATA_DIR.join(socket); + sockets.insert(socket.clone(), socket_path); + + let mut socket_options = SUBSCRIPTION_SOCKET_OPTIONS.lock(); + socket_options.insert(socket.clone(), options); + } + SocketMessage::RemoveSubscriberSocket(ref socket) => { + let mut sockets = SUBSCRIPTION_SOCKETS.lock(); + sockets.remove(socket); + } SocketMessage::Stop => { self.stop()?; } @@ -168,6 +205,14 @@ impl WindowManager { self.update_known_window_ids(); + notify_subscribers( + Notification { + event: NotificationEvent::Socket(message.clone()), + state: self.as_ref().into(), + }, + initial_state.has_been_modified(self.as_ref()), + )?; + tracing::info!("processed command: {message}"); Ok(()) diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 8f051fd3..c497b131 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -15,9 +15,16 @@ //! 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. //! +//! Once an event about a managed window has been handled, every subscriber is sent a notification +//! of it ([`notify_subscribers`]). +//! //! [`Window::should_manage`]: crate::window::Window::should_manage +use crate::Notification; +use crate::NotificationEvent; use crate::backend::backend; +use crate::notify_subscribers; +use crate::state::State; use crate::window_manager::WindowManager; use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; @@ -63,6 +70,10 @@ fn should_refocus_after_destroy(foreground: Option) -> bool { impl WindowManager { /// Handle an event from the compositor, and log how long it took + /// + /// The subscribers are sent a notification of an event that was handled + /// ([`notify_subscribers`]), and a notification that cannot be sent is an error. An event + /// that fails, or is about a window komorebi does not manage, is not notified. pub fn process_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> { let started = std::time::Instant::now(); let result = self.handle_event(event); @@ -97,6 +108,10 @@ impl WindowManager { // last one finished self.update_known_window_ids(); + #[allow(clippy::useless_asref)] + // We don't have From implemented for &mut WindowManager + let initial_state = State::from(self.as_ref()); + match event { WindowManagerEvent::FocusChange(_, _) => { let mut is_on_current_workspace = false; @@ -189,6 +204,14 @@ impl WindowManager { self.update_known_window_ids(); + notify_subscribers( + Notification { + event: NotificationEvent::WindowManager(event), + state: self.as_ref().into(), + }, + initial_state.has_been_modified(self.as_ref()), + )?; + Ok(()) } } diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 885dc280..37cbcc23 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -1,9 +1,12 @@ //! [`State`], the window manager as the daemon shows it: every monitor, with its workspaces, their //! containers and the windows in them, and the settings that apply to all of them. //! -//! The daemon writes it as JSON in answer to [`SocketMessage::State`]. +//! The daemon writes it as JSON in answer to [`SocketMessage::State`], and sends it to its +//! subscribers in every [`Notification`]. [`State::has_been_modified`] decides whether an event or +//! a message changed it, for the subscribers that want a notification only then. //! //! [`SocketMessage::State`]: crate::core::SocketMessage::State +//! [`Notification`]: crate::Notification use crate::core::Rect; use crate::monitor::Monitor; @@ -98,3 +101,29 @@ impl From<&WindowManager> for State { } } } + +impl State { + /// Returns true if and only if the window manager's monitors (with their workspaces, + /// containers and windows), its work area offset or its mouse follows focus setting differ + /// from this state's + /// + /// A window is compared by its id only, so a window that moved or was renamed is not a + /// change. + pub fn has_been_modified(&self, wm: &WindowManager) -> bool { + let new = Self::from(wm); + + if self.monitors != new.monitors { + return true; + } + + if self.work_area_offset != new.work_area_offset { + return true; + } + + if self.mouse_follows_focus != new.mouse_follows_focus { + return true; + } + + false + } +} diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index b662efce..4e99ad3d 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -14,6 +14,7 @@ use crate::DATA_DIR; use crate::LibraryError; +use crate::SUBSCRIPTION_SOCKETS; use crate::backend::backend; use crate::container::Container; use crate::core::Rect; @@ -28,7 +29,9 @@ use color_eyre::eyre::OptionExt; use crossbeam_channel::Receiver; use std::collections::HashMap; use std::io::ErrorKind; +use std::net::Shutdown; use std::os::unix::net::UnixListener; +use std::os::unix::net::UnixStream; use std::path::PathBuf; #[derive(Debug)] @@ -49,6 +52,12 @@ pub struct WindowManager { impl_ring_elements!(WindowManager, Monitor); +impl AsRef for WindowManager { + fn as_ref(&self) -> &Self { + self + } +} + impl WindowManager { /// Returns a window manager with no monitors, which handles the events that arrive on /// `incoming` and listens on `custom_socket_path`, or on `komorebi.sock` in @@ -196,12 +205,24 @@ impl WindowManager { self.update_focused_workspace(false, false) } - /// Stops the daemon: removes the command socket, lets the backend give up what it set up in - /// the compositor, and exits the process with status 0 + /// Stops the daemon: connects to every subscriber and closes the connection without writing + /// anything, removes the command socket, lets the backend give up what it set up in the + /// compositor, and exits the process with status 0 + /// + /// # Errors + /// + /// A connection to a subscriber cannot be shut down. The daemon does not stop. #[tracing::instrument(skip(self))] pub fn stop(&mut self) -> eyre::Result<()> { tracing::info!("received stop command, terminating process"); + let sockets = SUBSCRIPTION_SOCKETS.lock(); + for path in (*sockets).values() { + if let Ok(stream) = UnixStream::connect(path) { + stream.shutdown(Shutdown::Both)?; + } + } + let socket = DATA_DIR.join("komorebi.sock"); let _ = std::fs::remove_file(socket); diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 5ef74b49..2e0c4805 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -5,6 +5,10 @@ //! is written and the answer is printed. The messages are [`komorebi_client::SocketMessage`]s, //! sent with [`komorebi_client::send_message`] and [`komorebi_client::send_query`]. //! +//! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens +//! on a socket in the daemon's data directory, to which the daemon sends a notification after each +//! event and each message it handles. +//! //! The others work without the daemon: `start` runs `komorebi` in the background, `log` follows //! its log, `data-directory` shows where its socket is, and `completions` prints a completion //! script for a shell. The hidden `docgen` writes the help of every subcommand as Markdown, wrapped @@ -47,6 +51,18 @@ gen_enum_subcommand_args! { Query: StateQuery, } +#[derive(Parser)] +struct SubscribeSocket { + /// Name of the socket to send event notifications to + socket: String, +} + +#[derive(Parser)] +struct UnsubscribeSocket { + /// Name of the socket to stop sending event notifications to + socket: String, +} + #[derive(Parser)] #[allow(clippy::struct_excessive_bools)] struct Start { @@ -100,6 +116,20 @@ enum SubCommand { /// Query the current window manager state #[clap(arg_required_else_help = true)] Query(Query), + /// Subscribe to komorebi events using a Unix Domain Socket + #[clap(arg_required_else_help = true)] + SubscribeSocket(SubscribeSocket), + /// Unsubscribe from komorebi events + #[clap(arg_required_else_help = true)] + UnsubscribeSocket(UnsubscribeSocket), + // /// Subscribe to komorebi events using a Named Pipe + // #[clap(arg_required_else_help = true)] + // #[clap(alias = "subscribe")] + // SubscribePipe(SubscribePipe), + // /// Unsubscribe from komorebi events + // #[clap(arg_required_else_help = true)] + // #[clap(alias = "unsubscribe")] + // UnsubscribePipe(UnsubscribePipe), /// Tail komorebi's process logs (cancel with Ctrl-C) Log, /// Force the retiling of all managed windows @@ -233,6 +263,12 @@ fn main() -> eyre::Result<()> { SubCommand::MonitorInformation => { print_query(&SocketMessage::MonitorInformation); } + SubCommand::SubscribeSocket(args) => { + send_message(&SocketMessage::AddSubscriberSocket(args.socket))?; + } + SubCommand::UnsubscribeSocket(args) => { + send_message(&SocketMessage::RemoveSubscriberSocket(args.socket))?; + } } Ok(()) diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index ce285a94..c50a99a5 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -121,6 +121,29 @@ fn stop_and_retile_send_their_message_and_print_nothing() { } } +#[test] +fn subscribe_socket_and_unsubscribe_socket_send_the_name_they_are_given() { + for (subcommand, message) in [ + ( + "subscribe-socket", + r#"{"type":"AddSubscriberSocket","content":"bar.sock"}"#, + ), + ( + "unsubscribe-socket", + r#"{"type":"RemoveSubscriberSocket","content":"bar.sock"}"#, + ), + ] { + let runtime = Runtime::new(); + let daemon = runtime.serve(""); + + let output = runtime.komorebic(&[subcommand, "bar.sock"]); + + assert!(output.status.success(), "{subcommand}: {output:?}"); + assert_eq!(daemon.join().unwrap(), message, "{subcommand}"); + assert_eq!(stdout(&output), "", "{subcommand}"); + } +} + #[test] fn without_a_daemon_a_question_fails() { let runtime = Runtime::new(); @@ -169,6 +192,8 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "start.md", "state.md", "stop.md", + "subscribe-socket.md", + "unsubscribe-socket.md", ] ); From a86e2bdc63c23a11c45e90d22771e1acf9d308da Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 15:44:59 -0700 Subject: [PATCH 017/255] build(nix): a NixOS module for komorebi On NixOS, running komorebi should take one flake input and one module line. The flake exports `services.komorebi` as nixosModules.default (and .komorebi). It adds the flake's overlay, which gains komorebi-full, installs komorebi and komorebic, and runs the daemon in every Plasma session as a systemd user unit, wanted by plasma-workspace.target and ordered after plasma-core.target, which Plasma orders after KWin. systemd starts a daemon that fails again; the exit status of a SIGTERM (130) counts as success, so a stopped unit is not failed. The unit's PATH is the one a terminal in the session has, instead of the few store paths NixOS gives a unit. The options are enable, package, logLevel and a read-only execStart, the command line the unit runs. There is no configFile: the daemon reads no configuration file yet, and an option that linked one would do nothing. nixos-module-eval evaluates seven scenarios as real NixOS systems and checks their assertions, the unit and execStart, with builtins.tryEval for the two that must not evaluate. Nothing in it builds a Linux package, so it runs on a Mac as well. The VM nodes import the module, so every suite runs komorebi as the module installs it. The headless node's komorebi@NAME runs execStart, which has --log-level, so the nodes set logLevel to debug and the suites stop passing it; latency, which times the daemon, keeps the default level. The session node starts the module's unit at login; render-smoke turns it off, since a tiled terminal would cover the desktop it looks at. A new fast suite, vm-module, logs in to Plasma and checks that the unit runs the daemon with the module's log level and PATH, that a window opened in the session is tiled, that a killed daemon is started again, and that a stop is not a failure. docs/installation.md covers NixOS first, and building from source on other distributions. There is no binary cache: the Komorebi license does not allow third parties to redistribute binaries. --- CONTRIBUTING.md | 13 ++ README.md | 34 ++- docs/dev/ARCHITECTURE.md | 49 ++++- docs/dev/DESIGN.md | 28 +++ docs/dev/PLATFORM.md | 6 + docs/dev/vm-tests.md | 44 ++-- docs/index.md | 6 +- docs/installation.md | 152 +++++++++++++ docs/usage/running-komorebi.md | 14 +- flake.nix | 40 +++- nix/nixos-module.nix | 96 +++++++++ nix/tests/nixos-module.nix | 215 +++++++++++++++++++ nix/tests/vm/default.nix | 20 +- nix/tests/vm/lib/komorebi_vm/daemon.py | 8 +- nix/tests/vm/lib/komorebi_vm/kde.py | 6 +- nix/tests/vm/lib/tests/test_kde.py | 4 +- nix/tests/vm/nodes/headless.nix | 31 ++- nix/tests/vm/nodes/session.nix | 5 +- nix/tests/vm/suites/client-geometry/test.py | 2 +- nix/tests/vm/suites/core-e2e/test.py | 2 +- nix/tests/vm/suites/kwin-events/test.py | 2 +- nix/tests/vm/suites/kwin-restart/test.py | 2 +- nix/tests/vm/suites/latency/default.nix | 2 + nix/tests/vm/suites/module/default.nix | 5 + nix/tests/vm/suites/module/test.py | 123 +++++++++++ nix/tests/vm/suites/render-smoke/default.nix | 2 + 26 files changed, 840 insertions(+), 71 deletions(-) create mode 100644 docs/installation.md create mode 100644 nix/nixos-module.nix create mode 100644 nix/tests/nixos-module.nix create mode 100644 nix/tests/vm/suites/module/default.nix create mode 100644 nix/tests/vm/suites/module/test.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 584b9072..a024a052 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,6 +59,19 @@ The messages between the bridge and the daemon are in both sides read. A change to a message changes the fixture, the bridge and the daemon in the same commit. +## The NixOS module + +[`nix/nixos-module.nix`](nix/nixos-module.nix) is `services.komorebi`, which the +flake exports as `nixosModules.default` with its overlay. A change to it comes +with a scenario in [`nix/tests/nixos-module.nix`](nix/tests/nixos-module.nix), +the `nixos-module-eval` check: each scenario is a real NixOS system that is +evaluated and never built, and its checks read the assertions, the unit and +the options it evaluates to. It runs on a Mac too, with `nix build +.#checks.aarch64-darwin.nixos-module-eval`. A change to what the unit does in a +session also changes the VM suite `module`, which logs in to Plasma on a machine +with the module and checks the daemon the unit runs. Every other VM suite runs +on machines built with the module too. + ## VM tests A change that needs a real KWin to be checked comes with a VM test, next to diff --git a/README.md b/README.md index abb6b4ee..0ceb1a95 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,15 @@ A tiling window manager for KDE Plasma on Wayland, in the family of decides where each window goes, and KWin, the window manager of Plasma, does the moving and the drawing. +## Installing it + +On NixOS, the flake's module, `services.komorebi`, installs `komorebi` and +`komorebic` and starts komorebi with every Plasma session: one flake input, +one module line and `services.komorebi.enable = true`. Elsewhere, both are +built from source. [`docs/installation.md`](docs/installation.md) has both +ways. There are no prebuilt binaries: the Komorebi license does not allow third +parties to redistribute them. + ## Running it locally ```sh @@ -83,14 +92,16 @@ a git dependency at the revision `Cargo.toml` pins. 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. +TOML and Nix formatting, the tests under `cargo nextest`, and +`nixos-module-eval`, which evaluates the NixOS module in real NixOS systems, on +Linux and on an Apple silicon Mac. 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. -The VM tests boot NixOS with Plasma and run a real KWin. `just vm NAME` runs -one; [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) has the details, including -how to run them on a Mac. +The VM tests boot NixOS with Plasma and run a real KWin, on machines configured +with the NixOS module, so every one of them runs komorebi as the module installs +it. `just vm NAME` runs one; [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) has +the details, including how to run them on a Mac. ## How it fits together @@ -125,10 +136,15 @@ listens on a socket of its own, and after each event and each message, the daemon connects to it and writes the event or the message with the state of the window manager. +On NixOS, the module [`nix/nixos-module.nix`](nix/nixos-module.nix) runs the +daemon as a systemd user unit that the Plasma session starts, and systemd +starts it again if it fails. + ## Documentation -The user guide starts at [`docs/index.md`](docs/index.md), and -[`docs/cli`](docs/cli) has a page for every `komorebic` subcommand, which +The user guide starts at [`docs/index.md`](docs/index.md), +[`docs/installation.md`](docs/installation.md) says how to install komorebi, +and [`docs/cli`](docs/cli) has a page for every `komorebic` subcommand, which `just docgen` writes from the subcommands' help. `cargo doc --workspace --no-deps --open` builds the API documentation. [`CONTRIBUTING.md`](CONTRIBUTING.md) says how to work on the code. diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 9cb61ff1..23c072a0 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -8,8 +8,8 @@ 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, the backend that reaches KWin, how an event about a window becomes a tile, how a message on the daemon's socket is -answered, and how subscribers are notified of both. It grows with the code: each part of the -daemon that is added has its place here. +answered, how subscribers are notified of both, and how the NixOS module runs the daemon. It +grows with the code: each part of the daemon that is added has its place here. ## Vocabulary @@ -45,6 +45,9 @@ daemon that is added has its place here. 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. +- **Module**: `services.komorebi`, the NixOS module ([`nixos-module.nix`]), which installs + komorebi and runs the daemon in every Plasma session as the systemd user unit + `komorebi.service`. ## Design @@ -227,6 +230,41 @@ channel of [`window_manager_event_listener`], and past 20 the backend drops them When the daemon stops ([`WindowManager::stop`], or `SIGINT` and `SIGTERM` in `main.rs`), it connects to each subscriber and shuts the connection down without writing anything. +## The NixOS module + +The flake exports one module under two names, `nixosModules.default` and +`nixosModules.komorebi`: [`nixos-module.nix`] and the flake's overlay, which builds +`komorebi-full` (both programs) with the flake's nixpkgs and Rust toolchain. Its options are +`enable`, `package` (by default `pkgs.komorebi-full`, from the overlay), `logLevel`, and +`execStart`, which is read-only: the module sets it to `bin/komorebi` of the package with +`--log-level`. With `services.komorebi.enable`, the module: + +- installs the package in the system profile; +- defines the user unit `komorebi.service`, which every user of the machine has. Plasma's + `plasma-workspace.target` wants it, so a Plasma session starts it at login, and it is ordered + after `plasma-core.target`, which Plasma orders after KWin's service, `plasma-kwin_wayland`; +- runs `execStart` in it, with `Restart=on-failure`, the exit status of a `SIGTERM` (130) + counted as success, and a `PATH` of `/run/wrappers/bin`, `/etc/profiles/per-user/%u/bin` and + `/run/current-system/sw/bin` instead of the store paths NixOS gives a unit; +- asserts that Plasma 6 is enabled. + +The VM tests run on machines built with it ([vm-tests.md](vm-tests.md)). Their headless node +runs the daemon in test sessions, with a template unit, `komorebi@NAME`, that runs the module's +`execStart` on the session's private bus. The session node logs in to Plasma, which starts the +module's unit. + +| Rule | Enforced by | Proof | Escape hatch | +|---|---|---|---| +| komorebi is enabled only on a machine with Plasma 6 | evaluation error: an assertion of the module | `nixos-module-eval` ("without Plasma 6, an assertion fails") | none | +| The log level is one the daemon accepts | evaluation error: `logLevel` is an enum of the daemon's `--log-level` values | `nixos-module-eval` ("a log level the daemon does not have does not evaluate") | none | +| The unit runs `execStart`, and nothing but the module sets it | evaluation error: the option is read-only | `nixos-module-eval` ("execStart cannot be set", "the unit runs execStart") | a unit of your own | +| `komorebi` and `komorebic` are on every user's `PATH` | the module installs the package in the system profile | `nixos-module-eval`; every VM suite runs `komorebic` | none | +| Every Plasma session starts komorebi, once KWin's service has started | systemd: the user unit is wanted by `plasma-workspace.target`, after `plasma-core.target` | `nixos-module-eval`, `vm-module` | `systemctl --user mask komorebi` | +| A daemon that fails or is killed is started again | systemd: `Restart=on-failure` | `vm-module` (`SIGKILL`) | none | +| A daemon that is told to stop stays stopped, and the unit is not failed | systemd: the exit statuses of `Stop` (0) and of `SIGTERM` (130) are successes | `vm-module` | none | +| The daemon has the `PATH` of a terminal in the session | the unit's environment, with NixOS's default `PATH` turned off | `nixos-module-eval`, `vm-module` | none | +| The VM suites run komorebi as the module installs it | framework path: the test nodes import the module, and `komorebi@NAME` runs its `execStart` | every VM suite | a suite's `node` can set `services.komorebi.enable = false` (`vm-render-smoke` does) | + ## The parts - [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the @@ -271,6 +309,8 @@ connects to each subscriber and shuts the connection down without writing anythi fake with `--fake-backend`, makes the window manager, which binds the socket, loads and tiles the desktop, starts the threads that listen on the socket and handle events, and waits to be stopped. +- [`nixos-module.nix`]: the NixOS module, which installs komorebi and runs the daemon as a + systemd user unit of every Plasma session. 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 @@ -429,7 +469,12 @@ A window is shown, and ends up on a tile: driven end to end against the fake. - [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket, from its start to a `Stop`. +- [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; + [`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix), its scenarios, evaluated in + real NixOS systems; and [`nix/tests/vm/suites/module`](../../nix/tests/vm/suites/module/test.py), + a Plasma session in which the module's unit runs the daemon. +[`nixos-module.nix`]: ../../nix/nixos-module.nix [`Backend`]: ../../komorebi/src/backend/mod.rs [`WindowInfo`]: ../../komorebi/src/backend/mod.rs [`MonitorInfo`]: ../../komorebi/src/backend/mod.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 1454bb66..7ee69a41 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -182,3 +182,31 @@ and komorebi for Mac sends the same notifications to Unix sockets, which is also ([its README](https://github.com/LGUG2Z/komorebi-for-mac#window-manager-event-subscriptions)). A subscriber here is a Unix socket, as on macOS. The named pipes that komorebi on Windows sends notifications to are not ported, since the socket subscribers do the same. + +## Why does the flake have a NixOS module? + +So that komorebi runs on NixOS with one flake input and one module line. The module installs +komorebi and starts it with every Plasma session, and it adds the flake's overlay to nixpkgs +itself, so a configuration needs nothing else to find the package. Its options follow those of +the nix-darwin module of komorebi for Mac: `enable`, `package` and `logLevel`. + +## Why does komorebi run as a systemd user unit? + +Because a user unit covers every user: it is defined once for the machine and runs for each +user who logs in. It is wanted by `plasma-workspace.target`, so it runs in Plasma sessions and +nowhere else, and it is ordered after `plasma-core.target`, which Plasma orders after KWin's +service: the daemon exits when KWin is not on the session bus. systemd starts a daemon that fails +again. + +## Why is there no binary cache? + +The Komorebi license does not allow third parties to redistribute binaries. There is no public +binary cache for komorebi, and every installation builds it from source. + +## Why do the VM tests run on machines built with the module? + +So that the tests exercise the module. Every VM suite boots a machine that imports +`nixosModules.default` and installs komorebi through it. The headless node runs the daemon with +the module's read-only `execStart`, and the session node runs the module's unit itself. A change +to the module that breaks how komorebi is installed or started fails the VM suites, and not only +`nixos-module-eval`. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index d56e38fe..34773adb 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -59,6 +59,12 @@ The same questions, for each place the daemon can be started: 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. +On NixOS, the module's user unit, `komorebi.service`, is wanted by `plasma-workspace.target` +and ordered after `plasma-core.target`, which Plasma orders after KWin's service, +`plasma-kwin_wayland.service`: the session starts the daemon once KWin's service has started +([installation.md](../installation.md)). The unit's `PATH` is `/run/wrappers/bin`, +`/etc/profiles/per-user//bin` and `/run/current-system/sw/bin`. + #### What komorebi does It connects to the session bus as `org.komorebi.Bridge`, writes the bridge to diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index 27c78e22..edc86552 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -37,7 +37,8 @@ A suite has two files: - `default.nix` sets `tier` (`"fast"` or `"slow"`), `kind` (the node it runs on) and `timeoutMinutes`, and may set `node`, a NixOS module that adds to the node - for this suite alone (more memory, the clients it starts). + for this suite alone (more memory, the clients it starts, the options of + `services.komorebi`). - `test.py` is the test, a Python script for the NixOS test driver. It is prefixed with `SCALE = `, how many times slower than KVM the machine is. @@ -47,23 +48,38 @@ A suite has two files: `kind` picks a file under [`nix/tests/vm/nodes`](../../nix/tests/vm/nodes). +Both nodes are built with the NixOS module, as a user's machine is: they import +`nixosModules.default`, which the generator passes to them, and enable +`services.komorebi`, which installs `komorebi` and `komorebic`, built from the +commit under test. `services.komorebi.logLevel` is `"debug"`, because the tests +read the daemon's debug log. A suite can change either option in its `node`: +`latency`, which times the daemon, runs it at `"info"`. +The checks of the module that need no machine are `nixos-module-eval` +([`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix)), and the +suite `module` checks its unit in a Plasma session. + `headless` is a machine with Plasma installed and no login. Each KWin a test starts is a pair of user units of the test user, `session-bus@NAME` (a private 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 with `komorebic`; it is not bound to -KWin's unit, so a test can restart KWin under a running daemon. +A third unit, `komorebi@NAME`, runs the daemon in a session: it is the module's +unit, `komorebi.service`, moved to the session's bus and Wayland socket, and runs +the module's `execStart` followed by the arguments the test gives. It is not +bound to KWin's unit, so a test can restart KWin under a running daemon. The +module's unit itself starts with a Plasma session, which this node does not +have. 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. `session` is the headless node plus a login: plasma-login-manager logs the test user in by itself, as in nixpkgs' own `plasma6` test, and Plasma draws on the -machine's display device. It is the node for anything that needs pixels. The -choice of login manager is made in +machine's display device. The login starts the module's unit, so komorebi runs +in the session from the start, as on a user's machine; `render-smoke`, which +checks that the session draws, turns it off. It is the node for anything that +needs pixels. The choice of login manager is made in [`nodes/session.nix`](../../nix/tests/vm/nodes/session.nix) and nowhere else; the file says how to switch to sddm, the other one that has been seen to work. Its display is 1280x800, because screenshots are taken of the machine's one @@ -100,9 +116,11 @@ the run. user would, and `wid_by_class` finds a window by its app id or X11 class. `Kde.headless(..., xwayland=True)` gives the session XWayland, for X11 clients. -- `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. +- `start_komorebi(*args)` starts the daemon in the session, with the module's + `execStart` and `args` after it (not `--log-level`, which `execStart` has), + `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. `restart_kwin()` stops the session's KWin and starts a new one on the same bus, as when the compositor of a running session crashes, and waits for it. - `komorebic(*args)` runs `komorebic` in the session and returns what it @@ -110,8 +128,8 @@ the run. `komorebic state` prints it, `managed(workspace)` the number of windows the daemon has on a workspace of the first monitor, and `focused_title(workspace)` the title of the window it has focused there. -- `daemon` reads the daemon's view of the desktop from that log, started with - `--log-level debug`: `daemon.events(log)` lists the window events it handled, +- `daemon` reads the daemon's view of the desktop from that log, at the debug + level the nodes set: `daemon.events(log)` lists the window events it handled, in order, `daemon.window_ids(log)` maps a window's title to the daemon's id for it, and `daemon.requests(log)` returns the frame the daemon last asked KWin for, for each window. @@ -179,4 +197,6 @@ 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. The daemon's log is -`/run/user/1000/komorebi-NAME.log`. +`/run/user/1000/komorebi-NAME.log`. On the session node, the daemon of the +module's unit logs to `journalctl --user -u komorebi`, with colors, and to +`~/.local/share/komorebi/komorebi_plaintext.log.DATE`, without. diff --git a/docs/index.md b/docs/index.md index 7a5f98a1..09f529d9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -28,8 +28,10 @@ key bindings --------> komorebic <------> komorebi ## Getting started -[Running komorebi](usage/running-komorebi.md) explains how to get the two programs, start and -stop the daemon, ask it what it is doing and read its log. +[Installing komorebi](installation.md) explains how to install the two programs: on NixOS with +the flake's module, which also starts komorebi with every Plasma session, and from source +anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to start and stop the +daemon, ask it what it is doing and read its log. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 00000000..58063c83 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,152 @@ +# Installing komorebi + +`komorebi` is two programs: `komorebi`, the daemon that tiles the windows, and `komorebic`, the +command line that controls it. The daemon runs in a KDE Plasma Wayland session with KWin 6.8 or +newer ([PLATFORM.md](dev/PLATFORM.md) has what it needs from the session). + +On NixOS, the repository's flake has a module that installs both programs and starts komorebi +with every Plasma session. On any other distribution, build them from source. + +There is no binary cache and there are no prebuilt binaries: the Komorebi license does not allow +third parties to redistribute binaries, so every installation builds komorebi from source. On +NixOS, Nix does that for you, the first time you switch to a configuration that has it. + +## NixOS + +### The module + +Add the repository to the inputs of your system's flake, and import its module, +`nixosModules.default`, into your configuration: + +```nix +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + komorebi.url = "github:LGUG2Z/komorebi-for-kde"; + }; + + outputs = + { nixpkgs, komorebi, ... }: + { + nixosConfigurations.HOSTNAME = nixpkgs.lib.nixosSystem { + modules = [ + komorebi.nixosModules.default + ./configuration.nix + ]; + }; + }; +} +``` + +Then enable it, next to Plasma, in `configuration.nix`: + +```nix +{ + services.desktopManager.plasma6.enable = true; + services.komorebi.enable = true; +} +``` + +The module adds the flake's overlay, which provides `pkgs.komorebi-full`, to your nixpkgs, so +nothing else is needed. komorebi is built with the flake's nixpkgs and the Rust toolchain that +the repository's `rust-toolchain.toml` selects, whatever nixpkgs your system uses. + +### What the module does + +- It installs `komorebi` and `komorebic` in the system profile, so they are on every user's + `PATH`. +- It defines a systemd user unit, `komorebi.service`, for every user of the machine. Plasma's + `plasma-workspace.target` starts it when a user logs in to a Plasma session, after + `plasma-core.target`, which Plasma orders after KWin. The unit runs the daemon with the `PATH` + of a terminal in the session. +- systemd starts the daemon again when it fails or is killed. When it is stopped (`komorebic + stop`, or `systemctl --user stop komorebi`), it stays stopped until the next login or + `systemctl --user start komorebi`. +- Without `services.desktopManager.plasma6.enable`, the configuration does not evaluate: an + assertion of the module fails, and its message names the option to set. + +### Options + +| Option | Default | What it does | +|---|---|---| +| `services.komorebi.enable` | `false` | Installs komorebi and starts it with every Plasma session. | +| `services.komorebi.package` | `pkgs.komorebi-full` | The package with `bin/komorebi` and `bin/komorebic`; the unit runs the first, and both are installed. | +| `services.komorebi.logLevel` | `"info"` | The daemon's `--log-level`: `"error"`, `"warn"`, `"info"`, `"debug"` or `"trace"`. | +| `services.komorebi.execStart` | read only | The command line the unit starts komorebi with, built from `package` and `logLevel`. A unit of your own that runs komorebi uses it to start komorebi the same way. | + +### Running it + +`plasma-workspace.target` starts komorebi when you log in. In a session that was already +running when you switched to the new configuration, start it yourself: + +```sh +systemctl --user start komorebi +systemctl --user status komorebi +journalctl --user -u komorebi +``` + +[`komorebic stop`](cli/stop.md) stops it until you start it again or log in again. +[`komorebic start`](cli/start.md) finds the daemon the unit runs and does nothing, and a second +`komorebi` in the same session exits: the session bus gives the name komorebi needs to one +daemon. [Running komorebi](usage/running-komorebi.md) has the rest: asking komorebi what it is +doing, and its log. + +### The packages without the module + +The flake's packages are `komorebi`, `komorebic`, and `komorebi-full`, which has both and is the +`default`. To install them without the unit, and start komorebi yourself: + +```sh +nix profile install github:LGUG2Z/komorebi-for-kde +``` + +On a NixOS configuration, the overlay, `overlays.default`, provides `pkgs.komorebi`, +`pkgs.komorebic` and `pkgs.komorebi-full` for `environment.systemPackages`. + +## Other distributions: from source + +You need a Plasma 6.8 (or newer) Wayland session, [rustup](https://rustup.rs) with the stable +toolchain, which `rust-toolchain.toml` selects, and a C compiler (`cc`): the crate that makes the +version string builds libgit2, and zlib when the system has none. Then: + +```sh +git clone https://github.com/LGUG2Z/komorebi-for-kde +cd komorebi-for-kde +cargo install --locked --path komorebi +cargo install --locked --path komorebic +``` + +`cargo` installs both in `~/.cargo/bin`, which has to be on your `PATH`. Start komorebi from a +terminal in your Plasma session with [`komorebic start`](cli/start.md). + +To start it with every Plasma session instead, write the unit the NixOS module defines, without +the NixOS paths, to `~/.config/systemd/user/komorebi.service`: + +```ini +[Unit] +Description=komorebi, the tiling window manager +After=plasma-core.target + +[Service] +ExecStart=%h/.cargo/bin/komorebi +Restart=on-failure +SuccessExitStatus=130 + +[Install] +WantedBy=plasma-workspace.target +``` + +and enable it with `systemctl --user enable komorebi`. At time of writing (2026-10-27), only the +module's unit has been run, on NixOS; this one has not been tried on another distribution. + +## Uninstalling + +Stop the daemon first, with `komorebic stop`. + +- With the module, remove `services.komorebi.enable` (or the module) from your configuration and + switch to it. +- From source, remove the unit if you wrote one (`systemctl --user disable komorebi`, then the + file), and the programs, with `cargo uninstall komorebi komorebic`. + +The daemon's logs are in `~/.local/share/komorebi` (`$XDG_DATA_HOME/komorebi`), which you can +delete. Its socket is in `$XDG_RUNTIME_DIR/komorebi`, which is removed when you log out. diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md index 0e0eb08f..cf0e8020 100644 --- a/docs/usage/running-komorebi.md +++ b/docs/usage/running-komorebi.md @@ -6,16 +6,22 @@ doing, and reading its log. ## Getting the two programs -On Linux, the flake's default package has both: in a checkout of the repository, -`nix build` leaves them in `result/bin`, and `nix profile install .` puts them on your -`PATH`. Without nix, build them with the Rust toolchain that `rust-toolchain.toml` -selects: +[Installing komorebi](../installation.md) covers NixOS, where the flake's module installs both +and starts the daemon with every Plasma session, and building them from source. In a checkout of +the repository, on Linux, `nix build` leaves them in `result/bin`, and `nix profile install .` +puts them on your `PATH`. Without nix, build them with the Rust toolchain that +`rust-toolchain.toml` selects: ```sh cargo build --release --locked export PATH="$PWD/target/release:$PATH" ``` +With the NixOS module, the daemon is the user unit `komorebi.service`, which starts when you log +in to Plasma. `systemctl --user start komorebi` starts it again after a `komorebic stop`, and +`journalctl --user -u komorebi` shows what it wrote. Everything else on this page applies to it +as it is. + ## Starting and stopping [`komorebic start`](../cli/start.md) runs the `komorebi` on your `PATH` in the background, diff --git a/flake.nix b/flake.nix index e7f51b82..f8d1cee1 100644 --- a/flake.nix +++ b/flake.nix @@ -123,12 +123,12 @@ pkgs = mkPkgs system; build = mkKomorebiPackages { inherit pkgs; }; isLinux = pkgs.stdenv.hostPlatform.isLinux; - # the daemon and komorebic each guest runs, built for the guest's system - komorebiFor = guestSystem: self.packages.${guestSystem}.komorebi-full; + # the guests install komorebi through the module, as a NixOS user does + komorebiModule = self.nixosModules.default; # a Mac runs the guests under HVF, which is slower than KVM vm = import ./nix/tests/vm { hostPkgs = pkgs; - inherit komorebiFor; + inherit komorebiModule; scale = if isLinux then 1 else 1.5; }; nightlyRustfmt = pkgs.rust-bin.nightly.latest.rustfmt; @@ -211,6 +211,15 @@ ''; vm-lib = vm.lib; + + # The NixOS module in real NixOS systems, evaluated and never built, so a Mac checks it + # too. A VM suite, `vm-module`, runs it. + nixos-module-eval = import ./nix/tests/nixos-module.nix { + inherit pkgs; + inherit (nixpkgs.lib) nixosSystem; + module = self.nixosModules.default; + komorebiFor = guestSystem: self.packages.${guestSystem}.komorebi-full; + }; } # The VM tests need QEMU with KVM, so only Linux checks them. A Mac runs the same tests # through legacyPackages..vm, see docs/dev/vm-tests.md. @@ -231,7 +240,7 @@ vmTcg = (import ./nix/tests/vm { hostPkgs = pkgs; - inherit komorebiFor; + inherit komorebiModule; scale = 8; }).suites; }; @@ -295,13 +304,24 @@ }; flake = { - overlays.default = final: _: { - inherit ((mkKomorebiPackages { pkgs = mkPkgs final.stdenv.hostPlatform.system; })) - komorebi - komorebic - ; - }; + overlays.default = + final: _: + let + build = mkKomorebiPackages { pkgs = mkPkgs final.stdenv.hostPlatform.system; }; + in + { + inherit (build) komorebi komorebic; + komorebi-full = build.fullBuild; + }; overlays.komorebi = self.overlays.default; + + # `services.komorebi`, with the overlay that provides its package, so that a NixOS + # configuration needs this flake as an input and one module line (docs/installation.md) + nixosModules.default = { + imports = [ ./nix/nixos-module.nix ]; + nixpkgs.overlays = [ self.overlays.default ]; + }; + nixosModules.komorebi = self.nixosModules.default; }; }; } diff --git a/nix/nixos-module.nix b/nix/nixos-module.nix new file mode 100644 index 00000000..69333f15 --- /dev/null +++ b/nix/nixos-module.nix @@ -0,0 +1,96 @@ +# `services.komorebi`: komorebi in the Plasma session of every user of a NixOS machine. The flake +# exports this module as `nixosModules.default` and `nixosModules.komorebi`, together with its +# overlay, which provides `pkgs.komorebi-full` (see docs/installation.md). What the module +# guarantees, and what enforces each guarantee, is in docs/dev/ARCHITECTURE.md; its tests are +# nix/tests/nixos-module.nix and the VM suite `module`. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.komorebi; +in +{ + options.services.komorebi = { + enable = lib.mkEnableOption "komorebi, the tiling window manager, in the Plasma session of every user"; + + package = lib.mkPackageOption pkgs "komorebi-full" { + extraDescription = '' + It must have `bin/komorebi`, which the unit runs, and `bin/komorebic`. The module installs + both in the system profile. + ''; + }; + + logLevel = lib.mkOption { + type = lib.types.enum [ + "error" + "warn" + "info" + "debug" + "trace" + ]; + default = "info"; + description = '' + How much the daemon logs: its `--log-level`. The log goes to the journal of the unit + (`journalctl --user -u komorebi`) and to the daemon's log files, which `komorebic log` + follows. + ''; + }; + + execStart = lib.mkOption { + type = lib.types.str; + readOnly = true; + description = '' + The command line the unit starts komorebi with: `bin/komorebi` of `package`, with + `logLevel`. The module sets it, and setting it anywhere else is an error. A unit of your + own that runs komorebi somewhere else, as the VM tests do in their headless sessions, + starts it with this, the way the module does. + ''; + }; + }; + + config = lib.mkMerge [ + { + services.komorebi.execStart = "${lib.getExe' cfg.package "komorebi"} --log-level ${cfg.logLevel}"; + } + + (lib.mkIf cfg.enable { + assertions = [ + { + assertion = config.services.desktopManager.plasma6.enable; + message = '' + services.komorebi needs Plasma 6: komorebi runs in a Plasma Wayland session, and the + session starts it. Set services.desktopManager.plasma6.enable = true. + ''; + } + ]; + + environment.systemPackages = [ cfg.package ]; + + # A user unit, so it runs for every user who logs in to Plasma. plasma-workspace.target is + # the target of a Plasma session's services, and plasma-core.target, which it requires, is + # ordered after KWin's service: the daemon exits when KWin is not on the session bus. + systemd.user.services.komorebi = { + description = "komorebi, the tiling window manager"; + wantedBy = [ "plasma-workspace.target" ]; + after = [ "plasma-core.target" ]; + # NixOS gives a unit a PATH made of a few store paths; this is the PATH a terminal in the + # user's session has + enableDefaultPath = false; + environment.PATH = lib.concatStringsSep ":" [ + "/run/wrappers/bin" + "/etc/profiles/per-user/%u/bin" + "/run/current-system/sw/bin" + ]; + serviceConfig = { + ExecStart = cfg.execStart; + Restart = "on-failure"; + # what komorebi exits with when it is stopped with SIGTERM, as systemd stops a unit + SuccessExitStatus = 130; + }; + }; + }) + ]; +} diff --git a/nix/tests/nixos-module.nix b/nix/tests/nixos-module.nix new file mode 100644 index 00000000..9544be83 --- /dev/null +++ b/nix/tests/nixos-module.nix @@ -0,0 +1,215 @@ +# `nixos-module-eval`: `services.komorebi` in real NixOS systems, evaluated and never built. Each +# scenario is a `nixosSystem` with the module, and the checks read what it evaluates to: the +# assertions, the unit the module defines, and its read-only `execStart`. A scenario that must +# not evaluate is caught with `builtins.tryEval`. Nothing here builds a Linux package (the +# derivation below gets only check names and booleans), so a Mac runs it too. +{ + pkgs, + # nixpkgs' `lib.nixosSystem` + nixosSystem, + # the module, as the flake exports it, with its overlay + module, + # the flake's komorebi-full for a system, which the overlay has to provide + komorebiFor, +}: +let + inherit (pkgs) lib; + + # the systems are of the host's architecture + system = "${pkgs.stdenv.hostPlatform.parsed.cpu.name}-linux"; + + # enough of a machine for every NixOS assertion to hold, since no scenario is ever built + machine = { + nixpkgs.hostPlatform = system; + boot.loader.grub.enable = false; + fileSystems."/" = { + device = "/dev/vda"; + fsType = "ext4"; + }; + system.stateVersion = lib.trivial.release; + }; + + plasma = { + services.desktopManager.plasma6.enable = true; + }; + + eval = + scenario: + (nixosSystem { + modules = [ + module + machine + scenario + ]; + }).config; + + enabled = eval { + imports = [ plasma ]; + services.komorebi.enable = true; + }; + + disabled = eval plasma; + + withoutPlasma = eval { services.komorebi.enable = true; }; + + debug = eval { + imports = [ plasma ]; + services.komorebi = { + enable = true; + logLevel = "debug"; + }; + }; + + # a package that is not the overlay's: any package will do, since nothing is built + otherPackage = eval ( + { pkgs, ... }: + { + imports = [ plasma ]; + services.komorebi = { + enable = true; + package = pkgs.hello; + }; + } + ); + + unknownLevel = eval { + imports = [ plasma ]; + services.komorebi = { + enable = true; + logLevel = "verbose"; + }; + }; + + execStartSet = eval { + imports = [ plasma ]; + services.komorebi = { + enable = true; + execStart = "/bin/true"; + }; + }; + + failed = config: map (a: a.message) (lib.filter (a: !a.assertion) config.assertions); + unit = config: config.systemd.user.services.komorebi; + evaluates = value: (builtins.tryEval value).success; + + checks = [ + { + name = "enabled with Plasma 6, every assertion holds"; + ok = failed enabled == [ ]; + got = failed enabled; + } + { + name = "the unit is started by plasma-workspace.target"; + ok = (unit enabled).wantedBy == [ "plasma-workspace.target" ]; + got = (unit enabled).wantedBy; + } + { + name = "the unit starts after plasma-core.target"; + ok = lib.elem "plasma-core.target" (unit enabled).after; + got = (unit enabled).after; + } + { + name = "the unit is restarted when it fails"; + ok = (unit enabled).serviceConfig.Restart == "on-failure"; + } + { + name = "the unit counts the exit status of a SIGTERM (130) as success"; + ok = (unit enabled).serviceConfig.SuccessExitStatus == 130; + } + { + name = "the unit runs execStart"; + ok = (unit enabled).serviceConfig.ExecStart == enabled.services.komorebi.execStart; + got = (unit enabled).serviceConfig.ExecStart; + } + { + name = "execStart is bin/komorebi of the package, at the info level"; + ok = + enabled.services.komorebi.execStart + == "${enabled.services.komorebi.package}/bin/komorebi --log-level info"; + got = enabled.services.komorebi.execStart; + } + { + name = "the default package is the flake's komorebi-full, from the overlay"; + ok = enabled.services.komorebi.package.outPath == (komorebiFor system).outPath; + } + { + name = "the unit has the PATH of the user's session"; + ok = + (unit enabled).environment.PATH + == "/run/wrappers/bin:/etc/profiles/per-user/%u/bin:/run/current-system/sw/bin"; + got = (unit enabled).environment.PATH; + } + { + name = "the package is installed in the system profile"; + ok = lib.elem enabled.services.komorebi.package enabled.environment.systemPackages; + } + { + name = "disabled, every assertion holds"; + ok = failed disabled == [ ]; + got = failed disabled; + } + { + name = "disabled, there is no unit"; + ok = !(disabled.systemd.user.services ? komorebi); + } + { + name = "disabled, nothing is installed"; + ok = !(lib.elem disabled.services.komorebi.package disabled.environment.systemPackages); + } + { + name = "without Plasma 6, an assertion fails and names the option to set"; + ok = lib.any (lib.hasInfix "services.desktopManager.plasma6.enable = true") (failed withoutPlasma); + got = failed withoutPlasma; + } + { + name = "logLevel reaches execStart and the unit"; + ok = + debug.services.komorebi.execStart + == "${debug.services.komorebi.package}/bin/komorebi --log-level debug" + && (unit debug).serviceConfig.ExecStart == debug.services.komorebi.execStart; + got = (unit debug).serviceConfig.ExecStart; + } + { + name = "another package is the one the unit runs and the one installed"; + ok = + (unit otherPackage).serviceConfig.ExecStart + == "${otherPackage.services.komorebi.package}/bin/komorebi --log-level info" + && lib.elem otherPackage.services.komorebi.package otherPackage.environment.systemPackages; + got = (unit otherPackage).serviceConfig.ExecStart; + } + { + name = "a log level the daemon does not have does not evaluate"; + ok = !(evaluates unknownLevel.services.komorebi.logLevel); + } + { + name = "execStart cannot be set"; + ok = !(evaluates execStartSet.services.komorebi.execStart); + } + ]; + + failures = lib.filter (check: !check.ok) checks; + + # what a failed check got, without the store paths' context: this derivation must not depend on + # a Linux package + show = + check: + check.name + + lib.optionalString (check ? got) ( + ": got " + builtins.unsafeDiscardStringContext (builtins.toJSON check.got) + ); +in +pkgs.runCommand "nixos-module-eval" { } ( + if failures == [ ] then + '' + ${lib.concatMapStringsSep "\n" (check: "echo ${lib.escapeShellArg "ok: ${check.name}"}") checks} + echo "${toString (lib.length checks)} checks of services.komorebi passed" + touch $out + '' + else + '' + ${lib.concatMapStringsSep "\n" ( + check: "echo ${lib.escapeShellArg "FAILED: ${show check}"}" + ) failures} + exit 1 + '' +) diff --git a/nix/tests/vm/default.nix b/nix/tests/vm/default.nix index 245f72cb..5d15e3f2 100644 --- a/nix/tests/vm/default.nix +++ b/nix/tests/vm/default.nix @@ -2,21 +2,19 @@ # (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. `komorebiFor` -# returns the package of `komorebi` and `komorebic` for a system, and the guests get the one of -# their own. `scale` says how much slower than KVM that machine is (1 for KVM, 1.5 for HVF on a -# Mac, 8 for TCG), and every wait in the suites is multiplied by it. +# `hostPkgs` is the pkgs of the machine that runs QEMU; the guests are always Linux. +# `komorebiModule` is the flake's NixOS module, `services.komorebi`, which every node imports: its +# overlay builds `komorebi` and `komorebic` for the guest's system. `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, + komorebiModule, 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: @@ -80,8 +78,10 @@ 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; + # the nodes import the module, `komorebiModule`, which adds its overlay to nixpkgs: the test + # framework's pkgs, which cannot be changed, would refuse it + node.specialArgs = { inherit komorebiModule; }; + node.pkgsReadOnly = false; nodes.machine = { # a suite's `node`, if it has one, adds to the node of its kind diff --git a/nix/tests/vm/lib/komorebi_vm/daemon.py b/nix/tests/vm/lib/komorebi_vm/daemon.py index abd7957b..5546bfc2 100644 --- a/nix/tests/vm/lib/komorebi_vm/daemon.py +++ b/nix/tests/vm/lib/komorebi_vm/daemon.py @@ -1,10 +1,10 @@ """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, every focus -change KWin reports names the window by the daemon's id and its title, and -every frame the daemon asks KWin for is a debug line. +([`Kde.komorebi_log`](komorebi_vm.kde.Kde.komorebi_log)), at the debug level +the test nodes set (`services.komorebi.logLevel`): every event it handles is an +info line, every focus change KWin reports names the window by the daemon's id +and its title, and every frame the daemon asks KWin for is a debug line. """ import re diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index b7eae826..e07c3e32 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -218,8 +218,10 @@ class Kde: 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. + The unit runs the NixOS module's `execStart` with `args` after it, against this + session's bus and KWin, and writes its log to a file that [`Kde.komorebi_log`][] reads, + emptied on every start. `execStart` already has `--log-level`, from the node's + `services.komorebi.logLevel` (debug), and `komorebi` refuses a second one. """ words = shlex.quote(" ".join(args)) self.as_user(f"echo KOMOREBI_ARGS={words} > {self.runtime}/komorebi-{self.name}.env") diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index 9e246032..21dbe48a 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -139,10 +139,10 @@ def test_shot_returns_the_screenshot_as_rgb(machine: FakeMachine) -> None: def test_start_komorebi_writes_the_arguments_and_starts_the_unit(machine: FakeMachine) -> None: - Kde(machine, "main").start_komorebi("--log-level", "debug") + Kde(machine, "main").start_komorebi("--fake-backend") 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 "echo KOMOREBI_ARGS=--fake-backend > /run/user/1000/komorebi-main.env" in scripts assert "systemctl --user start komorebi@main.service" in scripts diff --git a/nix/tests/vm/nodes/headless.nix b/nix/tests/vm/nodes/headless.nix index bd0ccb22..f731b53f 100644 --- a/nix/tests/vm/nodes/headless.nix +++ b/nix/tests/vm/nodes/headless.nix @@ -1,23 +1,35 @@ # 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. `komorebi@NAME` runs the daemon -# in a session; `komorebi` is the package of the daemon and `komorebic`, which the test framework -# passes in. +# cannot draw: pixel and pointer tests use the session node instead. +# +# komorebi comes from the NixOS module, `komorebiModule`, which the test framework passes in: the +# node imports it and enables `services.komorebi` as a user's machine does, which installs +# `komorebi` and `komorebic`. The module's unit starts with a Plasma session, and this node has +# none; `komorebi@NAME` runs the module's `execStart` in a test session instead. { config, lib, pkgs, - komorebi, + komorebiModule, ... }: { - imports = [ ./options.nix ]; + imports = [ + ./options.nix + komorebiModule + ]; # KWin, its plugins and the environment a session expects services.desktopManager.plasma6.enable = true; hardware.graphics.enable = true; + # A suite can change either in its `node`. The tests read the daemon's debug log. + services.komorebi = { + enable = lib.mkDefault true; + logLevel = lib.mkDefault "debug"; + }; + users.users.komorebi = { isNormalUser = true; uid = 1000; @@ -40,7 +52,6 @@ kdotool kdePackages.libkscreen kdePackages.qttools - komorebi ]; systemd.user.services = { @@ -70,7 +81,8 @@ }; }; - # Not bound to KWin's unit: a test restarts KWin under a running daemon + # The module's unit, moved to the test session's bus and Wayland socket. 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" ]; @@ -86,10 +98,11 @@ NO_COLOR = "1"; }; serviceConfig = { - # the library writes KOMOREBI_ARGS (the log level) before it starts the unit + # the library writes KOMOREBI_ARGS (what follows the module's command line) 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'"; + ExecStart = "${pkgs.runtimeShell} -c 'exec ${config.services.komorebi.execStart} $${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/nodes/session.nix b/nix/tests/vm/nodes/session.nix index ebc68060..73d75042 100644 --- a/nix/tests/vm/nodes/session.nix +++ b/nix/tests/vm/nodes/session.nix @@ -1,5 +1,8 @@ # A real Plasma Wayland session that logs in by itself, on a machine that can draw. Everything the -# headless node has is here too, so a test can still start a virtual KWin next to it. +# headless node has is here too, so a test can still start a virtual KWin next to it. The module's +# unit, `komorebi.service`, starts komorebi in the session when the user logs in, as on a user's +# machine; a suite that wants the session without it sets `services.komorebi.enable = false` in +# its `node`. # # The choice of login manager is made here and nowhere else. nixpkgs' own `plasma6` test uses # plasma-login-manager, so that is what this node follows; sddm with a Wayland greeter is the other diff --git a/nix/tests/vm/suites/client-geometry/test.py b/nix/tests/vm/suites/client-geometry/test.py index 6055401e..bb435781 100644 --- a/nix/tests/vm/suites/client-geometry/test.py +++ b/nix/tests/vm/suites/client-geometry/test.py @@ -32,7 +32,7 @@ machine.wait_for_unit("user@1000.service") checks = Checks() kde = Kde.headless(machine, "main", size=(W, H), xwayland=True, scale=SCALE) kde.as_user("mkdir -p /tmp/firefox-profile") -kde.start_komorebi("--log-level", "debug") +kde.start_komorebi() checks.check( "the daemon loaded its script into KWin", kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30), diff --git a/nix/tests/vm/suites/core-e2e/test.py b/nix/tests/vm/suites/core-e2e/test.py index 231508b9..8fdbb315 100644 --- a/nix/tests/vm/suites/core-e2e/test.py +++ b/nix/tests/vm/suites/core-e2e/test.py @@ -74,7 +74,7 @@ def report(titles: list[str]) -> None: print("== 1. start") -kde.start_komorebi("--log-level", "debug") +kde.start_komorebi() checks.check( "the daemon loaded its script into KWin", kde.wait_for(lambda: "loaded the KWin bridge script" in daemon_log(), timeout=30), diff --git a/nix/tests/vm/suites/kwin-events/test.py b/nix/tests/vm/suites/kwin-events/test.py index df38a6d3..c6e082bc 100644 --- a/nix/tests/vm/suites/kwin-events/test.py +++ b/nix/tests/vm/suites/kwin-events/test.py @@ -29,7 +29,7 @@ checks.check( ) before = kde.wid("before") -kde.start_komorebi("--log-level", "debug") +kde.start_komorebi() checks.check( "the daemon loaded its script into KWin", kde.wait_for(lambda: "loaded the KWin bridge script" in daemon_log(), timeout=30), diff --git a/nix/tests/vm/suites/kwin-restart/test.py b/nix/tests/vm/suites/kwin-restart/test.py index eaac35a7..def9ad61 100644 --- a/nix/tests/vm/suites/kwin-restart/test.py +++ b/nix/tests/vm/suites/kwin-restart/test.py @@ -83,7 +83,7 @@ def restart(old: list[str], loaded: int) -> None: print("== 1. three windows are tiled") -kde.start_komorebi("--log-level", "debug") +kde.start_komorebi() checks.check( "the daemon loaded its script into KWin", kde.wait_for(lambda: loads() == 1, timeout=30) ) diff --git a/nix/tests/vm/suites/latency/default.nix b/nix/tests/vm/suites/latency/default.nix index a4ba7be3..a4fe5777 100644 --- a/nix/tests/vm/suites/latency/default.nix +++ b/nix/tests/vm/suites/latency/default.nix @@ -6,5 +6,7 @@ { pkgs, ... }: { environment.systemPackages = [ pkgs.dbus ]; + # this suite times the daemon, so it runs at the default log level, as a user's does + services.komorebi.logLevel = "info"; }; } diff --git a/nix/tests/vm/suites/module/default.nix b/nix/tests/vm/suites/module/default.nix new file mode 100644 index 00000000..7fae097d --- /dev/null +++ b/nix/tests/vm/suites/module/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "session"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/module/test.py b/nix/tests/vm/suites/module/test.py new file mode 100644 index 00000000..0fa30990 --- /dev/null +++ b/nix/tests/vm/suites/module/test.py @@ -0,0 +1,123 @@ +# The NixOS module runs komorebi in a real Plasma session: nothing in this test starts the daemon. +# What only a real session can tell: that logging in starts the module's user unit through +# `plasma-workspace.target`, that the daemon it runs reaches KWin from there and tiles a window +# opened in the session, that it runs with the module's log level and the PATH of the user's +# session, that systemd starts it again when it is killed, and that a clean stop is not a failure. +# The options and the unit the module writes are checked without a machine by `nixos-module-eval` +# (`nix/tests/nixos-module.nix`). +import json + +from komorebi_vm import Checks, Kde, Rect, daemon + +UNIT = "komorebi.service" +# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for +CELL = 24 +# the daemon's log of the day, without colors, which the unit's journal has +LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" + +start_all() +machine.wait_for_unit("multi-user.target") + +checks = Checks() +kde = Kde.session(machine, scale=SCALE) + + +def active() -> bool: + return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 + + +def failed() -> bool: + return kde.run(f"systemctl --user is-failed --quiet {UNIT}")[0] == 0 + + +def main_pid() -> str: + return kde.sh(f"systemctl --user show --property MainPID --value {UNIT}").strip() + + +def answering() -> bool: + return kde.run("komorebic monitor-information")[0] == 0 + + +def managed_titles() -> list[str]: + """The titles of the windows komorebi has on the first workspace of the first monitor.""" + workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] + return [ + window["details"]["title"] + for container in workspace["containers"]["elements"] + for window in container["windows"]["elements"] + ] + + +def daemon_log() -> str: + return machine.execute(f"cat {LOG}")[1] + + +print("== 1. logging in starts komorebi") +checks.check("the session started the module's unit", kde.wait_for(active, timeout=60)) +checks.check("its daemon answers komorebic", kde.wait_for(answering, timeout=60)) + +pid = main_pid() +command = kde.sh(f"tr '\\0' ' ' < /proc/{pid}/cmdline").split() +print(f" the unit runs: {' '.join(command)}") +checks.check("the unit runs bin/komorebi", command[0].endswith("/bin/komorebi")) +checks.check("... at the module's log level", command[1:] == ["--log-level", "debug"]) +environment = kde.sh(f"tr '\\0' '\\n' < /proc/{pid}/environ").splitlines() +path = next((line[len("PATH=") :] for line in environment if line.startswith("PATH=")), "") +checks.check( + "... with the PATH of the user's session", + path.split(":") + == ["/run/wrappers/bin", "/etc/profiles/per-user/komorebi/bin", "/run/current-system/sw/bin"], +) + +print("== 2. a window opened in the session is tiled") +width = json.loads(kde.komorebic("monitor-information"))[0]["size"]["right"] + + +def asked() -> Rect | None: + return daemon.asked(daemon_log(), "tiled") + + +def tiled() -> bool: + """KWin has the window where komorebi asked, and that is a tile across the screen.""" + want, wid = asked(), kde.wid("tiled") + if want is None or wid == "": + return False + have = kde.rect(wid) + return ( + (have.x, have.y) == (want.x, want.y) + and 0 <= want.w - have.w < CELL + and 0 <= want.h - have.h < CELL + and want.w > width // 2 + ) + + +kde.spawn("foot -T tiled sleep 3000") +checks.check("the window opens", kde.wait_for(lambda: kde.wid("tiled") != "", timeout=60)) +checks.check("komorebi manages it", kde.wait_for(lambda: "tiled" in managed_titles(), timeout=30)) +checks.check("KWin has it on its tile", kde.wait_for(tiled, timeout=30)) +print(f" asked {asked()}, has {kde.rect(kde.wid('tiled'))}") + +print("== 3. systemd starts a komorebi that was killed again") +kde.systemctl("kill", "--signal=SIGKILL", UNIT) +checks.check( + "the unit runs a new daemon", + kde.wait_for(lambda: active() and main_pid() not in ("0", pid), timeout=30), +) +checks.check("... which answers komorebic", kde.wait_for(answering, timeout=60)) +checks.check( + "... and manages the window again", + kde.wait_for(lambda: "tiled" in managed_titles(), timeout=30), +) + +print("== 4. a stop is not a failure") +kde.systemctl("stop", UNIT) +checks.check("stopped with SIGTERM, the unit is inactive", not active()) +checks.check("... and not failed", not failed()) +kde.systemctl("start", UNIT) +checks.check("started again, its daemon answers", kde.wait_for(answering, timeout=60)) +kde.komorebic("stop") +checks.check("komorebic stop stops the unit", kde.wait_for(lambda: not active(), timeout=30)) +checks.check("... which is not failed", not failed()) +checks.check("... and not started again", not kde.wait_for(active, timeout=5)) + +checks.finish() diff --git a/nix/tests/vm/suites/render-smoke/default.nix b/nix/tests/vm/suites/render-smoke/default.nix index 743bab13..73d4e563 100644 --- a/nix/tests/vm/suites/render-smoke/default.nix +++ b/nix/tests/vm/suites/render-smoke/default.nix @@ -2,4 +2,6 @@ tier = "slow"; kind = "session"; timeoutMinutes = 10; + # the session draws without komorebi: a tiled terminal would cover the desktop this test looks at + node.services.komorebi.enable = false; } From 20f93ba8c46930416191dbae03fb6b6d80f6ae83 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 15:36:59 -0700 Subject: [PATCH 018/255] feat(wm): focus in a direction A tiling window manager is driven from the keyboard, and the first thing a key has to do is move the focus. `komorebic focus left|right|up|down` gives the focus to the window whose tile is on that side of the focused one, as the layout sees it, and `komorebic cycle-focus next|previous` to the next or the previous window in the workspace's order, wrapping around. Neither moves a window: the focus changes, the tiles stay. The pointer follows the focus, through KWin's "Move Mouse to Focus", unless `mouse-follows-focus disable` (or `toggle-mouse-follows-focus`) says not to. Focusing towards a side with no window fails and changes nothing. Crossing into the next monitor, as komorebi does on the other platforms, comes with more than one monitor; so do eager-focus and the parts that depend on the monocle, maximized and floating windows. The VM test now drives the focus with komorebic in a real KWin and checks that KWin and komorebi agree on the focused window afterwards. --- README.md | 9 +- docs/cli/cycle-focus.md | 14 ++ docs/cli/focus.md | 14 ++ docs/cli/mouse-follows-focus.md | 14 ++ docs/cli/toggle-mouse-follows-focus.md | 10 ++ docs/dev/ARCHITECTURE.md | 42 +++++- docs/index.md | 1 + docs/usage/focusing-windows.md | 57 ++++++++ komorebi/src/core/mod.rs | 11 +- komorebi/src/monitor.rs | 25 ++++ komorebi/src/process_command.rs | 31 +++- komorebi/src/window_manager.rs | 131 ++++++++++++++++- komorebi/src/workspace.rs | 25 ++++ komorebi/tests/focus.rs | 191 +++++++++++++++++++++++++ komorebic/src/main.rs | 47 ++++++ komorebic/tests/cli.rs | 53 +++++++ nix/tests/vm/suites/core-e2e/test.py | 38 ++++- 17 files changed, 693 insertions(+), 20 deletions(-) create mode 100644 docs/cli/cycle-focus.md create mode 100644 docs/cli/focus.md create mode 100644 docs/cli/mouse-follows-focus.md create mode 100644 docs/cli/toggle-mouse-follows-focus.md create mode 100644 docs/usage/focusing-windows.md create mode 100644 komorebi/tests/focus.rs diff --git a/README.md b/README.md index 0ceb1a95..decc406d 100644 --- a/README.md +++ b/README.md @@ -36,8 +36,8 @@ with one monitor and no windows instead. While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in `$XDG_RUNTIME_DIR/komorebi` (the local data directory when there is no runtime directory): a message can ask for the state of the window manager, ask which -monitor, workspace or container has the focus, retile every monitor, or stop -the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +monitor, workspace or container has the focus, give the focus to another +window, retile every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, the command line, is how a person sends them. `komorebic start` runs the `komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma session: @@ -129,7 +129,10 @@ tiles the workspace in front again. Everything else reaches the daemon as a message on its socket: one JSON `SocketMessage` per line, handled one at a time with the window manager -locked. A message that asks a question is answered on the same connection. +locked. A message that asks a question is answered on the same connection. A +message that gives an order changes the model the way an event does: `focus` +and `cycle-focus` give the focus to the container on one side of the focused +one in the layout, or to the next one in the workspace's order. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/cycle-focus.md b/docs/cli/cycle-focus.md new file mode 100644 index 00000000..6cb38ec3 --- /dev/null +++ b/docs/cli/cycle-focus.md @@ -0,0 +1,14 @@ +```text +Change focus to the window in the specified cycle direction + +Usage: cycle-focus + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus.md b/docs/cli/focus.md new file mode 100644 index 00000000..f3883b76 --- /dev/null +++ b/docs/cli/focus.md @@ -0,0 +1,14 @@ +```text +Change focus to the window in the specified direction + +Usage: focus + +Arguments: + + [possible values: left, right, up, down] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/mouse-follows-focus.md b/docs/cli/mouse-follows-focus.md new file mode 100644 index 00000000..bfb906a3 --- /dev/null +++ b/docs/cli/mouse-follows-focus.md @@ -0,0 +1,14 @@ +```text +Enable or disable mouse follows focus on all workspaces + +Usage: mouse-follows-focus + +Arguments: + + [possible values: enable, disable] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-mouse-follows-focus.md b/docs/cli/toggle-mouse-follows-focus.md new file mode 100644 index 00000000..94b51a28 --- /dev/null +++ b/docs/cli/toggle-mouse-follows-focus.md @@ -0,0 +1,10 @@ +```text +Toggle mouse follows focus on all workspaces + +Usage: toggle-mouse-follows-focus + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 23c072a0..706dc404 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -8,8 +8,9 @@ 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, the backend that reaches KWin, how an event about a window becomes a tile, how a message on the daemon's socket is -answered, how subscribers are notified of both, and how the NixOS module runs the daemon. It -grows with the code: each part of the daemon that is added has its place here. +answered, how subscribers are notified of both, what the orders a message gives do, and how the +NixOS module runs the daemon. It grows with the code: each part of the daemon that is added has +its place here. ## Vocabulary @@ -26,7 +27,10 @@ grows with the code: each part of the daemon that is added has its place here. - **Event**: what the compositor reports about a window: it was shown, destroyed, given the focus, minimized or restored ([`WindowManagerEvent`]). - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order - (retile, stop) or a question (the state, the monitors, one [`StateQuery`]). + (focus a window, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). +- **Direction**: where an order goes from the focused container: a side of its tile + ([`OperationDirection`]), or the next or the previous container of the workspace + ([`CycleDirection`]). - **State**: the window manager's monitors, workspaces, containers and windows, and its settings, as the daemon answers a `State` message with them ([`State`]). - **Subscriber**: a program that listens on a socket of its own in [`DATA_DIR`] and has @@ -230,6 +234,26 @@ channel of [`window_manager_event_listener`], and past 20 the backend drops them When the daemon stops ([`WindowManager::stop`], or `SIGINT` and `SIGTERM` in `main.rs`), it connects to each subscriber and shuts the connection down without writing anything. +## Commands + +A message that gives an order is a call to a method of the [`WindowManager`] from +[`WindowManager::process_command`]. An order that goes somewhere takes one of two kinds of +direction, both from `komorebi-layouts`: + +- An [`OperationDirection`] (left, right, up, down) is a side of the focused container's tile. + The workspace asks its layout which container is on that side + ([`Workspace::new_idx_for_direction`]). A layout answers from the index of the focused + container and the number of containers, not from where the windows are. +- A [`CycleDirection`] (next, previous) follows the order of the workspace's containers, and + wraps around at both ends ([`Workspace::new_idx_for_cycle_direction`]). + +`FocusWindow` and `CycleFocusWindow` focus another container of the focused workspace and give +its window the focus with the backend's `focus` ([`WindowManager::focus_container_in_direction`], +[`WindowManager::focus_container_in_cycle_direction`]). They retile nothing. When there is no +container in that direction, the message fails and changes nothing. Whether the pointer follows +the focus is [`WindowManager::mouse_follows_focus`], which `MouseFollowsFocus` and +`ToggleMouseFollowsFocus` set. + ## The NixOS module The flake exports one module under two names, `nixosModules.default` and @@ -280,7 +304,7 @@ module's unit. changes its containers. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized - window out). + window out, move the focus). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -362,6 +386,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | Messages are handled one at a time, and in order on one connection | framework path: [`read_commands_uds`] reads a connection line by line and handles each message with the window manager locked | `the_messages_on_one_connection_are_handled_in_order` | none | | A socket left behind by a daemon that did not stop cleanly does not keep the next one from starting | framework path: [`WindowManager::new`] removes the file before it binds | `a_socket_file_left_behind_is_replaced` | none | | A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | +| Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | 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 | @@ -469,6 +494,8 @@ A window is shown, and ends up on a tile: driven end to end against the fake. - [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket, from its start to a `Stop`. +- [`komorebi/tests/focus.rs`](../../komorebi/tests/focus.rs): the focus commands against the + fake. - [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; [`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix), its scenarios, evaluated in real NixOS systems; and [`nix/tests/vm/suites/module`](../../nix/tests/vm/suites/module/test.py), @@ -494,6 +521,13 @@ A window is shown, and ends up on a tile: [`WindowManager`]: ../../komorebi/src/window_manager.rs [`WindowManager::process_event`]: ../../komorebi/src/process_event.rs [`WindowManager::update_focused_workspace`]: ../../komorebi/src/window_manager.rs +[`WindowManager::focus_container_in_direction`]: ../../komorebi/src/window_manager.rs +[`WindowManager::focus_container_in_cycle_direction`]: ../../komorebi/src/window_manager.rs +[`WindowManager::mouse_follows_focus`]: ../../komorebi/src/window_manager.rs +[`Workspace::new_idx_for_direction`]: ../../komorebi/src/workspace.rs +[`Workspace::new_idx_for_cycle_direction`]: ../../komorebi/src/workspace.rs +[`OperationDirection`]: ../../komorebi/src/core/mod.rs +[`CycleDirection`]: ../../komorebi/src/core/mod.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 diff --git a/docs/index.md b/docs/index.md index 09f529d9..64b3fdfb 100644 --- a/docs/index.md +++ b/docs/index.md @@ -32,6 +32,7 @@ key bindings --------> komorebic <------> komorebi the flake's module, which also starts komorebi with every Plasma session, and from source anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to start and stop the daemon, ask it what it is doing and read its log. +[Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/focusing-windows.md b/docs/usage/focusing-windows.md new file mode 100644 index 00000000..599d306f --- /dev/null +++ b/docs/usage/focusing-windows.md @@ -0,0 +1,57 @@ +# Focusing windows + +komorebi gives the focus to another window of the focused workspace when it is told to. It +moves no window to do it: the windows stay on their tiles, and KWin makes the chosen one the +active window. + +## In a direction + +[`komorebic focus`](../cli/focus.md) focuses the window whose tile is on one side of the +focused one: `left`, `right`, `up` or `down`. Which tile is on which side is the layout's +business. In the BSP layout with three windows, for example, the first window has the left +half, and `focus right` from it goes to the window at the top right. + +```sh +komorebic focus left +komorebic focus down +komorebic focus up +komorebic focus right +``` + +When there is no tile on that side, nothing happens, and the daemon logs "there is no container +in this direction". + +## In order + +[`komorebic cycle-focus`](../cli/cycle-focus.md) focuses the next or the previous window in the +order of the workspace, which is the order in which the windows were opened, each new one +after the window that had the focus. It wraps around: `next` from the last window is the +first. + +```sh +komorebic cycle-focus next +komorebic cycle-focus previous +``` + +## The pointer + +By default the pointer moves to the middle of the window that is given the focus. komorebi asks +KWin to do it with its "Move Mouse to Focus" shortcut, so the pointer follows only in a session +that has KWin's global shortcuts (a headless KWin has none). +[`komorebic mouse-follows-focus`](../cli/mouse-follows-focus.md) turns this on or off, and +[`komorebic toggle-mouse-follows-focus`](../cli/toggle-mouse-follows-focus.md) switches between +the two: + +```sh +komorebic mouse-follows-focus disable +komorebic toggle-mouse-follows-focus +``` + +The setting is in the daemon's state as `mouse_follows_focus`, and it lasts until the daemon +stops. + +## Binding them to keys + +komorebi reads no keys. Bind the commands to keys in Plasma's System Settings, under Keyboard, +Shortcuts, as custom shortcuts that run a command: for example `Meta+H` for +`komorebic focus left` and `Meta+L` for `komorebic focus right`. diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index f5c474ae..155ea46d 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -8,7 +8,9 @@ //! //! [`SocketMessage`] is every message the daemon takes on its socket, [`StateQuery`] every //! question [`SocketMessage::Query`] can ask, and [`SubscribeOptions`] what a subscriber can ask -//! of its notifications. +//! of its notifications. A message that goes somewhere takes the directions of the layouts: an +//! [`OperationDirection`] is a side of the focused tile, and a [`CycleDirection`] the next or the +//! previous container in the order of the workspace. use clap::ValueEnum; use color_eyre::eyre; @@ -334,11 +336,18 @@ pub struct SubscribeOptions { #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(tag = "type", content = "content")] pub enum SocketMessage { + // Window / Container Commands + FocusWindow(OperationDirection), + CycleFocusWindow(CycleDirection), Stop, Retile, State, MonitorInformation, Query(StateQuery), + MouseFollowsFocus(bool), + ToggleMouseFollowsFocus, + // RemoveTitleBar(ApplicationIdentifier, String), + // ToggleTitleBars, AddSubscriberSocket(String), AddSubscriberSocketWithOptions(String, SubscribeOptions), RemoveSubscriberSocket(String), diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 6bfa64a6..e6208fab 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -58,6 +58,31 @@ pub struct Monitor { pub workspace_padding: Option, } +/// Returns a monitor with one empty workspace, the way [`Monitor::new`] makes one, from owned +/// names +pub fn new( + id: u32, + size: Rect, + work_area_size: Rect, + device: String, + serial_number_id: String, +) -> Monitor { + let mut workspaces = Ring::default(); + workspaces.elements_mut().push_back(Workspace::default()); + + Monitor { + id, + device, + serial_number_id, + size, + work_area_size, + work_area_offset: None, + workspaces, + container_padding: None, + workspace_padding: None, + } +} + impl Monitor { #[allow(clippy::field_reassign_with_default)] pub fn new( diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index ecd3721c..c1f4c923 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -10,10 +10,18 @@ //! - **MonitorInformation**: the id, the name and the bounds of each monitor, as JSON. //! - **Query**: one value as text, the answer to a [`StateQuery`]. //! -//! The others answer nothing: **Retile** tiles the focused workspace of every monitor again, -//! **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name of -//! its socket in the data directory, **RemoveSubscriberSocket** removes one, and **Stop** stops the -//! daemon ([`WindowManager::stop`]). +//! The others answer nothing: +//! +//! - **FocusWindow** and **CycleFocusWindow** give the focus to the container on one side of the +//! focused one, or to the next or the previous one in the workspace +//! ([`WindowManager::focus_container_in_direction`], +//! [`WindowManager::focus_container_in_cycle_direction`]). +//! - **MouseFollowsFocus** and **ToggleMouseFollowsFocus** set whether the pointer is moved to +//! the window that is given the focus. +//! - **Retile** tiles the focused workspace of every monitor again. +//! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name +//! of its socket in the data directory, and **RemoveSubscriberSocket** removes one. +//! - **Stop** stops the daemon ([`WindowManager::stop`]). //! //! Once a message has been handled, every subscriber is sent a notification of it //! ([`notify_subscribers`]). @@ -96,6 +104,9 @@ impl WindowManager { /// # Errors /// /// - A query about the focused monitor, workspace or container when there is none. + /// - The focus cannot be moved, for one of the reasons + /// [`WindowManager::focus_container_in_direction`] and + /// [`WindowManager::focus_container_in_cycle_direction`] give. /// - The window manager fails to retile, for one of the reasons /// [`WindowManager::retile_all`] gives. /// - The answer cannot be written to `reply`. @@ -114,6 +125,12 @@ impl WindowManager { let initial_state = State::from(self.as_ref()); match message { + SocketMessage::FocusWindow(direction) => { + self.focus_container_in_direction(direction)?; + } + SocketMessage::CycleFocusWindow(direction) => { + self.focus_container_in_cycle_direction(direction)?; + } SocketMessage::Retile => self.retile_all()?, SocketMessage::State => { let state = match serde_json::to_string_pretty(&State::from(&*self)) { @@ -181,6 +198,12 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::MouseFollowsFocus(enable) => { + self.mouse_follows_focus = enable; + } + SocketMessage::ToggleMouseFollowsFocus => { + self.mouse_follows_focus = !self.mouse_follows_focus; + } SocketMessage::AddSubscriberSocket(ref socket) => { let mut sockets = SUBSCRIPTION_SOCKETS.lock(); let socket_path = DATA_DIR.join(socket); diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 4e99ad3d..6a36c32a 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -7,8 +7,10 @@ //! again ([`WindowManager::update_focused_workspace`]). //! //! It also owns the daemon's command socket, which [`listen_for_commands`] reads -//! ([`WindowManager::process_command`]), and stops the daemon when it is asked to -//! ([`WindowManager::stop`]). +//! ([`WindowManager::process_command`]), carries out the orders that come in on it, such as +//! moving the focus ([`WindowManager::focus_container_in_direction`], +//! [`WindowManager::focus_container_in_cycle_direction`]), and stops the daemon when it is asked +//! to ([`WindowManager::stop`]). //! //! [`listen_for_commands`]: crate::process_command::listen_for_commands @@ -17,6 +19,8 @@ use crate::LibraryError; use crate::SUBSCRIPTION_SOCKETS; use crate::backend::backend; use crate::container::Container; +use crate::core::CycleDirection; +use crate::core::OperationDirection; use crate::core::Rect; use crate::desktop; use crate::monitor::Monitor; @@ -26,6 +30,7 @@ use crate::window_manager_event::WindowManagerEvent; use crate::workspace::Workspace; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use color_eyre::eyre::bail; use crossbeam_channel::Receiver; use std::collections::HashMap; use std::io::ErrorKind; @@ -40,6 +45,7 @@ pub struct WindowManager { /// The socket the daemon takes messages on, `komorebi.sock` in [`struct@DATA_DIR`] unless /// [`WindowManager::new`] was given another path pub command_listener: UnixListener, + /// Whether the pointer is moved to the window that is given the focus, which is the default 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 @@ -112,6 +118,48 @@ impl WindowManager { Ok(()) } + /// Gives the focus to the window of the container whose tile is on the `direction` side of + /// the focused one, and the pointer follows it if [`WindowManager::mouse_follows_focus`] is + /// set + /// + /// Nothing is retiled: the focus moves, the windows stay where they are. + /// + /// # Errors + /// + /// - There is no focused workspace, or no container on that side of the focused one. + /// - The backend refuses to focus the window. + #[tracing::instrument(skip(self))] + pub fn focus_container_in_direction( + &mut self, + direction: OperationDirection, + ) -> eyre::Result<()> { + let mouse_follows_focus = self.mouse_follows_focus; + + let workspace = self.focused_workspace()?; + + tracing::info!("focusing container"); + + let new_idx = workspace.new_idx_for_direction(direction); + + // if there is no container in that direction for this workspace + match new_idx { + None => bail!("there is no container in this direction"), + Some(idx) => { + let workspace = self.focused_workspace_mut()?; + workspace.focus_container(idx); + } + } + + let ws = self.focused_workspace_mut()?; + if !ws.is_empty() + && let Ok(focused_window) = self.focused_window() + { + focused_window.focus(mouse_follows_focus)?; + } + + Ok(()) + } + #[tracing::instrument(skip(self))] pub fn update_focused_workspace( &mut self, @@ -256,6 +304,36 @@ impl WindowManager { Ok(()) } + /// Gives the focus to the window of the next (or the previous) container of the focused + /// workspace, wrapping around at the ends, and the pointer follows it if + /// [`WindowManager::mouse_follows_focus`] is set + /// + /// # Errors + /// + /// - There is no focused workspace, or it has no containers. + /// - The backend refuses to focus the window. + #[tracing::instrument(skip(self))] + pub fn focus_container_in_cycle_direction( + &mut self, + direction: CycleDirection, + ) -> eyre::Result<()> { + tracing::info!("focusing container"); + + let mouse_follows_focus = self.mouse_follows_focus; + + let workspace = self.focused_workspace_mut()?; + + let new_idx = workspace + .new_idx_for_cycle_direction(direction) + .ok_or_eyre("this is not a valid direction from the current position")?; + + workspace.focus_container(new_idx); + + self.focused_window_mut()?.focus(mouse_follows_focus)?; + + Ok(()) + } + pub fn update_known_window_ids(&mut self) { tracing::trace!("updating list of known window_ids"); let mut known_window_ids = HashMap::new(); @@ -281,6 +359,7 @@ mod tests { use super::*; use crate::backend::fake::FakeBackend; use crate::backend::with_backend; + use crate::monitor; use crossbeam_channel::Sender; use crossbeam_channel::bounded; use std::path::PathBuf; @@ -328,6 +407,54 @@ mod tests { let (_wm, _test_context) = setup_window_manager(); } + #[test] + fn test_focus_container_in_cycle_direction() { + let (mut wm, _test_context) = setup_window_manager(); + + // Create a monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + let workspace = m.focused_workspace_mut().unwrap(); + + for i in 0..4 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + workspace.add_container_to_back(container); + } + assert_eq!(workspace.containers().len(), 4); + + workspace.focus_container(0); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + + // container focus should be on the second container + wm.focus_container_in_cycle_direction(CycleDirection::Next) + .ok(); + assert_eq!(wm.focused_container_idx().unwrap(), 1); + + // container focus should be on the third container + wm.focus_container_in_cycle_direction(CycleDirection::Next) + .ok(); + assert_eq!(wm.focused_container_idx().unwrap(), 2); + + // container focus should be on the second container + wm.focus_container_in_cycle_direction(CycleDirection::Previous) + .ok(); + assert_eq!(wm.focused_container_idx().unwrap(), 1); + + // container focus should be on the first container + wm.focus_container_in_cycle_direction(CycleDirection::Previous) + .ok(); + assert_eq!(wm.focused_container_idx().unwrap(), 0); + } + #[test] fn a_socket_file_left_behind_is_replaced() -> eyre::Result<()> { let socket_path = PathBuf::from(format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4())); diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 6af1e023..f21e0da0 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -6,8 +6,10 @@ //! falls back to come from the monitor it is on ([`WorkspaceGlobals`]). use crate::container::Container; +use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::OperationDirection; use crate::core::Rect; use crate::lockable_sequence::LockableSequence; use crate::ring::Ring; @@ -67,6 +69,29 @@ impl Workspace { self.focus_container(j); } + /// Returns the index of the container whose tile is on the `direction` side of the focused + /// one in the workspace's layout, or `None` when there is none on that side + pub fn new_idx_for_direction(&self, direction: OperationDirection) -> Option { + let len = NonZeroUsize::new(self.containers().len())?; + + direction.destination( + self.layout.as_boxed_direction().as_ref(), + None, + self.focused_container_idx(), + len, + None, + ) + } + + /// Returns the index of the container after (or before) the focused one, wrapping around at + /// the ends, or `None` when the workspace has no containers + pub fn new_idx_for_cycle_direction(&self, direction: CycleDirection) -> Option { + Option::from(direction.next_idx( + self.focused_container_idx(), + NonZeroUsize::new(self.containers().len())?, + )) + } + pub fn container_idx_for_window(&self, window_id: u32) -> Option { let mut idx = None; for (i, x) in self.containers().iter().enumerate() { diff --git a/komorebi/tests/focus.rs b/komorebi/tests/focus.rs new file mode 100644 index 00000000..648616d1 --- /dev/null +++ b/komorebi/tests/focus.rs @@ -0,0 +1,191 @@ +//! Moving the focus with `focus` and `cycle-focus`, against an in-memory desktop: the messages go +//! in through [`WindowManager::process_command`], and what comes out is the window the backend is +//! asked to focus and whether the pointer goes with it. +//! +//! Window ids are in the 19_000s. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::CycleDirection; +use komorebi::core::OperationDirection; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor, and a window for each of +/// `ids`, opened in that order. The last one has the focus, and the commands it took to get there +/// are cleared. +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmf-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + wm + }); + + fake.clear_commands(); + (fake, wm) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn focused(wm: &WindowManager) -> u32 { + wm.focused_window().unwrap().id +} + +#[test] +fn focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing() { + let (fake, mut wm) = desktop_with(&[19_001, 19_002]); + let tiles = (fake.rect_of(19_001), fake.rect_of(19_002)); + assert_eq!(focused(&wm), 19_002); + + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Left), + ); + + assert_eq!(focused(&wm), 19_001); + assert_eq!(fake.commands(), [Command::Focus(19_001, true)]); + + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Right), + ); + + assert_eq!(focused(&wm), 19_002); + assert_eq!( + fake.commands(), + [Command::Focus(19_001, true), Command::Focus(19_002, true)] + ); + assert_eq!((fake.rect_of(19_001), fake.rect_of(19_002)), tiles); +} + +#[test] +fn focus_towards_a_side_with_no_window_is_an_error_and_changes_nothing() { + // the two windows are side by side: there is nothing above them + let (fake, mut wm) = desktop_with(&[19_011, 19_012]); + + let result = with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::FocusWindow(OperationDirection::Up), + Vec::new(), + ) + }); + + assert_eq!( + result.map_err(|error| error.to_string()), + Err(String::from("there is no container in this direction")) + ); + assert_eq!(focused(&wm), 19_012); + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); +} + +#[test] +fn cycle_focus_goes_round_the_containers_in_order() { + let (fake, mut wm) = desktop_with(&[19_021, 19_022, 19_023]); + assert_eq!(focused(&wm), 19_023); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(CycleDirection::Next), + ); + assert_eq!(focused(&wm), 19_021, "next from the last is the first"); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(CycleDirection::Next), + ); + assert_eq!(focused(&wm), 19_022); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(CycleDirection::Previous), + ); + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(CycleDirection::Previous), + ); + assert_eq!(focused(&wm), 19_023, "previous from the first is the last"); + + assert_eq!( + fake.commands(), + [ + Command::Focus(19_021, true), + Command::Focus(19_022, true), + Command::Focus(19_021, true), + Command::Focus(19_023, true), + ] + ); +} + +#[test] +fn cycle_focus_on_an_empty_workspace_is_an_error() { + let (fake, mut wm) = desktop_with(&[]); + + let result = with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::CycleFocusWindow(CycleDirection::Next), + Vec::new(), + ) + }); + + assert!(result.is_err()); + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); +} + +#[test] +fn without_mouse_follows_focus_the_pointer_stays_where_it_is() { + let (fake, mut wm) = desktop_with(&[19_031, 19_032]); + + send(&fake, &mut wm, SocketMessage::MouseFollowsFocus(false)); + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Left), + ); + send(&fake, &mut wm, SocketMessage::ToggleMouseFollowsFocus); + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Right), + ); + + assert_eq!( + fake.commands(), + [Command::Focus(19_031, false), Command::Focus(19_032, true)] + ); + assert!(wm.mouse_follows_focus); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 2e0c4805..d09856d2 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -5,6 +5,9 @@ //! is written and the answer is printed. The messages are [`komorebi_client::SocketMessage`]s, //! sent with [`komorebi_client::send_message`] and [`komorebi_client::send_query`]. //! +//! `focus` and `cycle-focus` give the focus to another window of the focused workspace, and +//! `mouse-follows-focus` and `toggle-mouse-follows-focus` set whether the pointer goes with it. +//! //! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens //! on a socket in the daemon's data directory, to which the daemon sends a notification after each //! event and each message it handles. @@ -17,8 +20,11 @@ use chrono::Utc; use clap::CommandFactory; use clap::Parser; +use clap::ValueEnum; use color_eyre::eyre; use fs_tail::TailedFile; +use komorebi_client::CycleDirection; +use komorebi_client::OperationDirection; use komorebi_client::SocketMessage; use komorebi_client::StateQuery; use komorebi_client::send_message; @@ -32,6 +38,21 @@ use std::process::Stdio; use std::time::Duration; use sysinfo::ProcessesToUpdate; +#[derive(Copy, Clone, ValueEnum)] +enum BooleanState { + Enable, + Disable, +} + +impl From for bool { + fn from(b: BooleanState) -> Self { + match b { + BooleanState::Enable => true, + BooleanState::Disable => false, + } + } +} + macro_rules! gen_enum_subcommand_args { // SubCommand Pattern: Enum Type ( $( $name:ident: $element:ty ),+ $(,)? ) => { @@ -48,6 +69,9 @@ macro_rules! gen_enum_subcommand_args { } gen_enum_subcommand_args! { + Focus: OperationDirection, + CycleFocus: CycleDirection, + MouseFollowsFocus: BooleanState, Query: StateQuery, } @@ -132,8 +156,19 @@ enum SubCommand { // UnsubscribePipe(UnsubscribePipe), /// Tail komorebi's process logs (cancel with Ctrl-C) Log, + /// Change focus to the window in the specified direction + #[clap(arg_required_else_help = true)] + Focus(Focus), + /// Change focus to the window in the specified cycle direction + #[clap(arg_required_else_help = true)] + CycleFocus(CycleFocus), /// Force the retiling of all managed windows Retile, + /// Enable or disable mouse follows focus on all workspaces + #[clap(arg_required_else_help = true)] + MouseFollowsFocus(MouseFollowsFocus), + /// Toggle mouse follows focus on all workspaces + ToggleMouseFollowsFocus, } fn print_query(message: &SocketMessage) { @@ -251,6 +286,12 @@ fn main() -> eyre::Result<()> { println!("{line}"); } } + SubCommand::Focus(args) => { + send_message(&SocketMessage::FocusWindow(args.operation_direction))?; + } + SubCommand::CycleFocus(args) => { + send_message(&SocketMessage::CycleFocusWindow(args.cycle_direction))?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } @@ -263,6 +304,12 @@ fn main() -> eyre::Result<()> { SubCommand::MonitorInformation => { print_query(&SocketMessage::MonitorInformation); } + SubCommand::ToggleMouseFollowsFocus => { + send_message(&SocketMessage::ToggleMouseFollowsFocus)?; + } + SubCommand::MouseFollowsFocus(args) => { + send_message(&SocketMessage::MouseFollowsFocus(args.boolean_state.into()))?; + } SubCommand::SubscribeSocket(args) => { send_message(&SocketMessage::AddSubscriberSocket(args.socket))?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index c50a99a5..1e25859e 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -144,6 +144,55 @@ fn subscribe_socket_and_unsubscribe_socket_send_the_name_they_are_given() { } } +/// Runs `komorebic` with `args` against a daemon that answers nothing, and checks that it wrote +/// `message` on the socket, printed nothing and exited with status 0 +fn sends(args: &[&str], message: &str) { + let runtime = Runtime::new(); + let daemon = runtime.serve(""); + + let output = runtime.komorebic(args); + + assert!(output.status.success(), "{args:?}: {output:?}"); + assert_eq!(daemon.join().unwrap(), message, "{args:?}"); + assert_eq!(stdout(&output), "", "{args:?}"); +} + +#[test] +fn focus_and_cycle_focus_send_the_direction_they_are_given() { + sends( + &["focus", "left"], + r#"{"type":"FocusWindow","content":"Left"}"#, + ); + sends( + &["focus", "down"], + r#"{"type":"FocusWindow","content":"Down"}"#, + ); + sends( + &["cycle-focus", "next"], + r#"{"type":"CycleFocusWindow","content":"Next"}"#, + ); + sends( + &["cycle-focus", "previous"], + r#"{"type":"CycleFocusWindow","content":"Previous"}"#, + ); +} + +#[test] +fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { + sends( + &["mouse-follows-focus", "enable"], + r#"{"type":"MouseFollowsFocus","content":true}"#, + ); + sends( + &["mouse-follows-focus", "disable"], + r#"{"type":"MouseFollowsFocus","content":false}"#, + ); + sends( + &["toggle-mouse-follows-focus"], + r#"{"type":"ToggleMouseFollowsFocus"}"#, + ); +} + #[test] fn without_a_daemon_a_question_fails() { let runtime = Runtime::new(); @@ -184,15 +233,19 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { pages, [ "completions.md", + "cycle-focus.md", "data-directory.md", + "focus.md", "log.md", "monitor-information.md", + "mouse-follows-focus.md", "query.md", "retile.md", "start.md", "state.md", "stop.md", "subscribe-socket.md", + "toggle-mouse-follows-focus.md", "unsubscribe-socket.md", ] ); diff --git a/nix/tests/vm/suites/core-e2e/test.py b/nix/tests/vm/suites/core-e2e/test.py index 8fdbb315..269c27a6 100644 --- a/nix/tests/vm/suites/core-e2e/test.py +++ b/nix/tests/vm/suites/core-e2e/test.py @@ -2,8 +2,9 @@ # reach KWin through the held call and that KWin carries them out, so that each window is where # the daemon asked for it (`komorebi/tests/wm_events.rs` checks the window manager's side against # the fake), that the daemon and KWin agree on which window has the focus, that `komorebic` reaches -# the daemon of a session and reads its state, and that `komorebic stop` gives KWin back what the -# daemon set up in it. A window manager that agrees with itself proves nothing, so what the daemon +# the daemon of a session and reads its state, that `komorebic focus` and `cycle-focus` move KWin's +# focus (`komorebi/tests/focus.rs` checks which window they pick), and that `komorebic stop` gives +# KWin back what the daemon set up in it. A window manager that agrees with itself proves nothing, so what the daemon # believes is read from its debug log and from `komorebic state`, and what KWin has through kdotool. import json @@ -108,7 +109,32 @@ checks.check("KWin focused win1", kde.wait_for(lambda: kde.title(kde.active()) = checks.check("... and the daemon followed", kde.wait_for(focus_agrees)) checks.check("... and its state says so", kde.wait_for(state_agrees)) -print("== 4. minimize and restore") +print("== 4. the focus moves on komorebic's commands") +kde.komorebic("focus", "right") +checks.check( + "after 'focus right' KWin has given the focus to another window", + kde.wait_for(lambda: kde.title(kde.active()) not in ("", "win1")), +) +checks.check("... and komorebi's state focuses the same one", kde.wait_for(state_agrees)) +kde.komorebic("focus", "left") +checks.check( + "'focus left' gives it back to win1", kde.wait_for(lambda: kde.title(kde.active()) == "win1") +) +checks.check("... and komorebi's state says so", kde.wait_for(state_agrees)) +kde.komorebic("cycle-focus", "next") +checks.check( + "'cycle-focus next' focuses win2, the next container in komorebi's order", + kde.wait_for(lambda: kde.title(kde.active()) == "win2"), +) +checks.check("... and komorebi's state says so", kde.wait_for(state_agrees)) +kde.komorebic("cycle-focus", "previous") +checks.check( + "'cycle-focus previous' goes back to win1", + kde.wait_for(lambda: kde.title(kde.active()) == "win1"), +) +checks.check("moving the focus moved no window", all(where_asked(t) for t in titles)) + +print("== 5. minimize and restore") kde.minimize(kde.wid("win2")) two = ["win1", "win3"] checks.check( @@ -135,7 +161,7 @@ checks.check( ) report(titles) -print("== 5. close") +print("== 6. close") kde.close(kde.wid("win3")) checks.check("KWin closed win3", kde.wait_for(lambda: kde.wid("win3") == "", timeout=10)) checks.check( @@ -152,7 +178,7 @@ report(["win1", "win2"]) checks.check("komorebi manages the two that are left", kde.wait_for(lambda: kde.managed() == 2)) checks.check("KWin carried out every command", "the bridge could not do" not in daemon_log()) -print("== 6. KWin restarts under the daemon") +print("== 7. KWin restarts under the daemon") kde.restart_kwin() checks.check( "the daemon loaded its script into the new KWin", @@ -173,7 +199,7 @@ checks.check( ) report(["afterwards"]) -print("== 7. komorebic stop") +print("== 8. komorebic stop") kde.komorebic("stop") checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running())) checks.check("its socket is gone", kde.run(f"test -e {kde.runtime}/komorebi/komorebi.sock")[0] != 0) From 1bbb534844daa4419c3a93cf4105e10f3a224fe7 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 15:45:13 -0700 Subject: [PATCH 019/255] feat(wm): move and cycle containers With the focus moving, the next thing a key has to do is move the focused window. `komorebic move left|right|up|down` swaps the focused container with the one whose tile is on that side, as the layout sees it, and `komorebic cycle-move next|previous` with the next or the previous one in the workspace's order. The workspace is tiled again, the window that moved keeps the focus, and the pointer follows it. The swap goes through the lockable sequence, so a lock stays with its index: the container moved onto a locked index is locked in its place. Moving towards a side with no window fails and moves nothing. Moving into the next monitor comes with more than one monitor, and the floating layer's own move with the floating layer. The VM test moves a window in a real KWin and back, and checks that KWin has every window where komorebi asked. --- README.md | 7 +- docs/cli/cycle-move.md | 14 +++ docs/cli/move.md | 14 +++ docs/dev/ARCHITECTURE.md | 21 +++- docs/index.md | 3 +- docs/usage/moving-windows.md | 38 ++++++ komorebi/src/core/mod.rs | 2 + komorebi/src/process_command.rs | 13 ++ komorebi/src/window_manager.rs | 71 ++++++++++- komorebi/tests/moving.rs | 177 +++++++++++++++++++++++++++ komorebic/src/main.rs | 15 +++ komorebic/tests/cli.rs | 15 +++ nix/tests/vm/suites/core-e2e/test.py | 41 ++++++- 13 files changed, 417 insertions(+), 14 deletions(-) create mode 100644 docs/cli/cycle-move.md create mode 100644 docs/cli/move.md create mode 100644 docs/usage/moving-windows.md create mode 100644 komorebi/tests/moving.rs diff --git a/README.md b/README.md index decc406d..1f2874e8 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,8 @@ While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in `$XDG_RUNTIME_DIR/komorebi` (the local data directory when there is no runtime directory): a message can ask for the state of the window manager, ask which monitor, workspace or container has the focus, give the focus to another -window, retile every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +window, move the focused window to another tile, retile every monitor, or stop +the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, the command line, is how a person sends them. `komorebic start` runs the `komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma session: @@ -132,7 +133,9 @@ Everything else reaches the daemon as a message on its socket: one JSON locked. A message that asks a question is answered on the same connection. A message that gives an order changes the model the way an event does: `focus` and `cycle-focus` give the focus to the container on one side of the focused -one in the layout, or to the next one in the workspace's order. +one in the layout, or to the next one in the workspace's order, and `move` and +`cycle-move` swap the focused container with that one and tile the workspace +again. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/cycle-move.md b/docs/cli/cycle-move.md new file mode 100644 index 00000000..a06970e2 --- /dev/null +++ b/docs/cli/cycle-move.md @@ -0,0 +1,14 @@ +```text +Move the focused window in the specified cycle direction + +Usage: cycle-move + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move.md b/docs/cli/move.md new file mode 100644 index 00000000..08f1ef61 --- /dev/null +++ b/docs/cli/move.md @@ -0,0 +1,14 @@ +```text +Move the focused window in the specified direction + +Usage: move + +Arguments: + + [possible values: left, right, up, down] + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 706dc404..9ea8b995 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -27,7 +27,7 @@ its place here. - **Event**: what the compositor reports about a window: it was shown, destroyed, given the focus, minimized or restored ([`WindowManagerEvent`]). - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order - (focus a window, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). + (focus a window, move it, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). - **Direction**: where an order goes from the focused container: a side of its tile ([`OperationDirection`]), or the next or the previous container of the workspace ([`CycleDirection`]). @@ -254,6 +254,14 @@ container in that direction, the message fails and changes nothing. Whether the the focus is [`WindowManager::mouse_follows_focus`], which `MouseFollowsFocus` and `ToggleMouseFollowsFocus` set. +`MoveWindow` and `CycleMoveWindow` swap the focused container with the container in that +direction ([`WindowManager::move_container_in_direction`], +[`WindowManager::move_container_in_cycle_direction`]), and tile the workspace again: the window +that moved takes the other's tile, keeps the focus, and the pointer follows it. The swap goes +through `LockableSequence`, so a lock stays with its index: the container swapped onto a locked +index is locked in its place. When there is no container in that direction, the message fails +and nothing moves. + ## The NixOS module The flake exports one module under two names, `nixosModules.default` and @@ -304,7 +312,7 @@ module's unit. changes its containers. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized - window out, move the focus). + window out, move the focus, move the focused container). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -386,6 +394,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | Messages are handled one at a time, and in order on one connection | framework path: [`read_commands_uds`] reads a connection line by line and handles each message with the window manager locked | `the_messages_on_one_connection_are_handled_in_order` | none | | A socket left behind by a daemon that did not stop cleanly does not keep the next one from starting | framework path: [`WindowManager::new`] removes the file before it binds | `a_socket_file_left_behind_is_replaced` | none | | A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | +| A container moved onto a locked index is locked in its place, and the lock leaves the container that moved away | framework path: [`Workspace::swap_containers`] swaps through `LockableSequence`, which keeps the lock with the index | `test_swap_respecting_locks_various_cases`, `a_lock_stays_with_its_index_when_a_window_is_moved_onto_it` | `containers_mut()` is the `VecDeque` itself | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | 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 | @@ -494,8 +503,9 @@ A window is shown, and ends up on a tile: driven end to end against the fake. - [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket, from its start to a `Stop`. -- [`komorebi/tests/focus.rs`](../../komorebi/tests/focus.rs): the focus commands against the - fake. +- [`komorebi/tests/focus.rs`](../../komorebi/tests/focus.rs) and + [`komorebi/tests/moving.rs`](../../komorebi/tests/moving.rs): the focus and move commands + against the fake. - [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; [`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix), its scenarios, evaluated in real NixOS systems; and [`nix/tests/vm/suites/module`](../../nix/tests/vm/suites/module/test.py), @@ -524,6 +534,9 @@ A window is shown, and ends up on a tile: [`WindowManager::focus_container_in_direction`]: ../../komorebi/src/window_manager.rs [`WindowManager::focus_container_in_cycle_direction`]: ../../komorebi/src/window_manager.rs [`WindowManager::mouse_follows_focus`]: ../../komorebi/src/window_manager.rs +[`WindowManager::move_container_in_direction`]: ../../komorebi/src/window_manager.rs +[`WindowManager::move_container_in_cycle_direction`]: ../../komorebi/src/window_manager.rs +[`Workspace::swap_containers`]: ../../komorebi/src/workspace.rs [`Workspace::new_idx_for_direction`]: ../../komorebi/src/workspace.rs [`Workspace::new_idx_for_cycle_direction`]: ../../komorebi/src/workspace.rs [`OperationDirection`]: ../../komorebi/src/core/mod.rs diff --git a/docs/index.md b/docs/index.md index 64b3fdfb..7c39a4a0 100644 --- a/docs/index.md +++ b/docs/index.md @@ -32,7 +32,8 @@ key bindings --------> komorebic <------> komorebi the flake's module, which also starts komorebi with every Plasma session, and from source anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to start and stop the daemon, ask it what it is doing and read its log. -[Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window. +[Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window, +and [Moving windows](usage/moving-windows.md) how to move the focused window to another tile. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/moving-windows.md b/docs/usage/moving-windows.md new file mode 100644 index 00000000..09237554 --- /dev/null +++ b/docs/usage/moving-windows.md @@ -0,0 +1,38 @@ +# Moving windows + +komorebi moves the focused window to another tile of its workspace when it is told to. The +window swaps places with the window on that tile, the workspace is tiled again, and the window +that moved keeps the focus. + +## In a direction + +[`komorebic move`](../cli/move.md) swaps the focused window with the window whose tile is on one +side of it: `left`, `right`, `up` or `down`. As with +[`komorebic focus`](focusing-windows.md#in-a-direction), the layout decides which tile is on +which side. + +```sh +komorebic move left +komorebic move down +komorebic move up +komorebic move right +``` + +When there is no tile on that side, nothing moves, and the daemon logs "there is no container +in this direction". + +## In order + +[`komorebic cycle-move`](../cli/cycle-move.md) swaps the focused window with the next or the +previous window in the order of the workspace, and wraps around: `next` from the last window +swaps it with the first. + +```sh +komorebic cycle-move next +komorebic cycle-move previous +``` + +## The pointer + +The pointer follows the window that moved, unless +[mouse follows focus](focusing-windows.md#the-pointer) is off. diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 155ea46d..91985bf9 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -338,7 +338,9 @@ pub struct SubscribeOptions { pub enum SocketMessage { // Window / Container Commands FocusWindow(OperationDirection), + MoveWindow(OperationDirection), CycleFocusWindow(CycleDirection), + CycleMoveWindow(CycleDirection), Stop, Retile, State, diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index c1f4c923..0b0bba22 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -16,6 +16,10 @@ //! focused one, or to the next or the previous one in the workspace //! ([`WindowManager::focus_container_in_direction`], //! [`WindowManager::focus_container_in_cycle_direction`]). +//! - **MoveWindow** and **CycleMoveWindow** swap the focused container with the one on one side +//! of it, or with the next or the previous one, and tile the workspace again +//! ([`WindowManager::move_container_in_direction`], +//! [`WindowManager::move_container_in_cycle_direction`]). //! - **MouseFollowsFocus** and **ToggleMouseFollowsFocus** set whether the pointer is moved to //! the window that is given the focus. //! - **Retile** tiles the focused workspace of every monitor again. @@ -107,6 +111,9 @@ impl WindowManager { /// - The focus cannot be moved, for one of the reasons /// [`WindowManager::focus_container_in_direction`] and /// [`WindowManager::focus_container_in_cycle_direction`] give. + /// - The focused container cannot be moved, for one of the reasons + /// [`WindowManager::move_container_in_direction`] and + /// [`WindowManager::move_container_in_cycle_direction`] give. /// - The window manager fails to retile, for one of the reasons /// [`WindowManager::retile_all`] gives. /// - The answer cannot be written to `reply`. @@ -128,9 +135,15 @@ impl WindowManager { SocketMessage::FocusWindow(direction) => { self.focus_container_in_direction(direction)?; } + SocketMessage::MoveWindow(direction) => { + self.move_container_in_direction(direction)?; + } SocketMessage::CycleFocusWindow(direction) => { self.focus_container_in_cycle_direction(direction)?; } + SocketMessage::CycleMoveWindow(direction) => { + self.move_container_in_cycle_direction(direction)?; + } SocketMessage::Retile => self.retile_all()?, SocketMessage::State => { let state = match serde_json::to_string_pretty(&State::from(&*self)) { diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 6a36c32a..15c4ff4e 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -9,7 +9,9 @@ //! It also owns the daemon's command socket, which [`listen_for_commands`] reads //! ([`WindowManager::process_command`]), carries out the orders that come in on it, such as //! moving the focus ([`WindowManager::focus_container_in_direction`], -//! [`WindowManager::focus_container_in_cycle_direction`]), and stops the daemon when it is asked +//! [`WindowManager::focus_container_in_cycle_direction`]) and moving the focused container +//! ([`WindowManager::move_container_in_direction`], +//! [`WindowManager::move_container_in_cycle_direction`]), and stops the daemon when it is asked //! to ([`WindowManager::stop`]). //! //! [`listen_for_commands`]: crate::process_command::listen_for_commands @@ -160,6 +162,44 @@ impl WindowManager { Ok(()) } + /// Swaps the focused container with the one whose tile is on the `direction` side of it, so + /// that the focused window takes that tile, and tiles the workspace again + /// + /// The container keeps the focus, and the pointer follows it if + /// [`WindowManager::mouse_follows_focus`] is set. A lock stays with its index: a container + /// that is swapped onto the index of a locked one is locked in its place + /// ([`Workspace::swap_containers`]). + /// + /// # Errors + /// + /// - There is no focused workspace, or no container on that side of the focused one. + /// - The workspace cannot be tiled, or the backend refuses to focus the window. + #[tracing::instrument(skip(self))] + pub fn move_container_in_direction( + &mut self, + direction: OperationDirection, + ) -> eyre::Result<()> { + let workspace = self.focused_workspace()?; + + tracing::info!("moving container"); + + let origin_container_idx = workspace.focused_container_idx(); + let target_container_idx = workspace.new_idx_for_direction(direction); + + match target_container_idx { + None => bail!("there is no container in this direction"), + Some(new_idx) => { + let workspace = self.focused_workspace_mut()?; + workspace.swap_containers(origin_container_idx, new_idx); + workspace.focus_container(new_idx); + } + } + + self.update_focused_workspace(self.mouse_follows_focus, true)?; + + Ok(()) + } + #[tracing::instrument(skip(self))] pub fn update_focused_workspace( &mut self, @@ -334,6 +374,35 @@ impl WindowManager { Ok(()) } + /// Swaps the focused container with the next (or the previous) one of the focused + /// workspace, wrapping around at the ends, and tiles the workspace again + /// + /// The container keeps the focus, and the pointer follows it if + /// [`WindowManager::mouse_follows_focus`] is set. + /// + /// # Errors + /// + /// - There is no focused workspace, or it has no containers. + /// - The workspace cannot be tiled, or the backend refuses to focus the window. + #[tracing::instrument(skip(self))] + pub fn move_container_in_cycle_direction( + &mut self, + direction: CycleDirection, + ) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + + tracing::info!("moving container"); + + let current_idx = workspace.focused_container_idx(); + let new_idx = workspace + .new_idx_for_cycle_direction(direction) + .ok_or_eyre("this is not a valid direction from the current position")?; + + workspace.swap_containers(current_idx, new_idx); + workspace.focus_container(new_idx); + self.update_focused_workspace(self.mouse_follows_focus, true) + } + pub fn update_known_window_ids(&mut self) { tracing::trace!("updating list of known window_ids"); let mut known_window_ids = HashMap::new(); diff --git a/komorebi/tests/moving.rs b/komorebi/tests/moving.rs new file mode 100644 index 00000000..9fad1850 --- /dev/null +++ b/komorebi/tests/moving.rs @@ -0,0 +1,177 @@ +//! Moving the focused window with `move` and `cycle-move`, against an in-memory desktop: the +//! messages go in through [`WindowManager::process_command`], and what comes out is the order of +//! the containers, where the backend is asked to put each window, and which window has the +//! focus. +//! +//! Window ids are in the 20_000s. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::CycleDirection; +use komorebi::core::OperationDirection; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor, and a window for each of +/// `ids`, opened in that order. The last one has the focus, and the commands it took to get there +/// are cleared. +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmm-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + wm + }); + + fake.clear_commands(); + (fake, wm) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +/// The window of each container of the focused workspace, in order +fn order(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().unwrap().id) + .collect() +} + +fn focused(wm: &WindowManager) -> u32 { + wm.focused_window().unwrap().id +} + +#[test] +fn move_swaps_the_focused_window_with_the_one_on_that_side() { + let (fake, mut wm) = desktop_with(&[20_001, 20_002]); + let (left, right) = (fake.rect_of(20_001), fake.rect_of(20_002)); + + send( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Left), + ); + + assert_eq!(order(&wm), [20_002, 20_001]); + assert_eq!( + focused(&wm), + 20_002, + "the window that moved keeps the focus" + ); + assert_eq!(fake.rect_of(20_002), left); + assert_eq!(fake.rect_of(20_001), right); + assert!( + fake.commands().contains(&Command::Focus(20_002, true)), + "{:?}", + fake.commands() + ); + + send( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Right), + ); + + assert_eq!(order(&wm), [20_001, 20_002]); + assert_eq!((fake.rect_of(20_001), fake.rect_of(20_002)), (left, right)); +} + +#[test] +fn move_towards_a_side_with_no_window_is_an_error_and_moves_nothing() { + // the two windows are side by side: there is nothing below them + let (fake, mut wm) = desktop_with(&[20_011, 20_012]); + + let result = with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::MoveWindow(OperationDirection::Down), + Vec::new(), + ) + }); + + assert_eq!( + result.map_err(|error| error.to_string()), + Err(String::from("there is no container in this direction")) + ); + assert_eq!(order(&wm), [20_011, 20_012]); + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); +} + +#[test] +fn cycle_move_swaps_with_the_next_container_and_wraps_around() { + let (fake, mut wm) = desktop_with(&[20_021, 20_022, 20_023]); + let first_tile = fake.rect_of(20_021); + + send( + &fake, + &mut wm, + SocketMessage::CycleMoveWindow(CycleDirection::Next), + ); + + assert_eq!( + order(&wm), + [20_023, 20_022, 20_021], + "next from the last is the first" + ); + assert_eq!(focused(&wm), 20_023); + assert_eq!(fake.rect_of(20_023), first_tile); + + send( + &fake, + &mut wm, + SocketMessage::CycleMoveWindow(CycleDirection::Previous), + ); + + assert_eq!( + order(&wm), + [20_021, 20_022, 20_023], + "previous from the first is the last" + ); + assert_eq!(focused(&wm), 20_023); +} + +#[test] +fn a_lock_stays_with_its_index_when_a_window_is_moved_onto_it() { + let (fake, mut wm) = desktop_with(&[20_031, 20_032]); + wm.focused_workspace_mut().unwrap().containers_mut()[0].locked = true; + + send( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Left), + ); + + let containers = wm.focused_workspace().unwrap().containers(); + assert_eq!(order(&wm), [20_032, 20_031]); + assert!(containers[0].locked, "the first index is still locked"); + assert!(!containers[1].locked, "the window that was locked is not"); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index d09856d2..78892efe 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -7,6 +7,7 @@ //! //! `focus` and `cycle-focus` give the focus to another window of the focused workspace, and //! `mouse-follows-focus` and `toggle-mouse-follows-focus` set whether the pointer goes with it. +//! `move` and `cycle-move` move the focused window to another tile. //! //! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens //! on a socket in the daemon's data directory, to which the daemon sends a notification after each @@ -70,7 +71,9 @@ macro_rules! gen_enum_subcommand_args { gen_enum_subcommand_args! { Focus: OperationDirection, + Move: OperationDirection, CycleFocus: CycleDirection, + CycleMove: CycleDirection, MouseFollowsFocus: BooleanState, Query: StateQuery, } @@ -159,9 +162,15 @@ enum SubCommand { /// Change focus to the window in the specified direction #[clap(arg_required_else_help = true)] Focus(Focus), + /// Move the focused window in the specified direction + #[clap(arg_required_else_help = true)] + Move(Move), /// Change focus to the window in the specified cycle direction #[clap(arg_required_else_help = true)] CycleFocus(CycleFocus), + /// Move the focused window in the specified cycle direction + #[clap(arg_required_else_help = true)] + CycleMove(CycleMove), /// Force the retiling of all managed windows Retile, /// Enable or disable mouse follows focus on all workspaces @@ -289,9 +298,15 @@ fn main() -> eyre::Result<()> { SubCommand::Focus(args) => { send_message(&SocketMessage::FocusWindow(args.operation_direction))?; } + SubCommand::Move(args) => { + send_message(&SocketMessage::MoveWindow(args.operation_direction))?; + } SubCommand::CycleFocus(args) => { send_message(&SocketMessage::CycleFocusWindow(args.cycle_direction))?; } + SubCommand::CycleMove(args) => { + send_message(&SocketMessage::CycleMoveWindow(args.cycle_direction))?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 1e25859e..41ae4097 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -177,6 +177,19 @@ fn focus_and_cycle_focus_send_the_direction_they_are_given() { ); } +#[test] +fn move_and_cycle_move_send_the_direction_they_are_given() { + sends( + &["move", "right"], + r#"{"type":"MoveWindow","content":"Right"}"#, + ); + sends(&["move", "up"], r#"{"type":"MoveWindow","content":"Up"}"#); + sends( + &["cycle-move", "previous"], + r#"{"type":"CycleMoveWindow","content":"Previous"}"#, + ); +} + #[test] fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { sends( @@ -234,11 +247,13 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { [ "completions.md", "cycle-focus.md", + "cycle-move.md", "data-directory.md", "focus.md", "log.md", "monitor-information.md", "mouse-follows-focus.md", + "move.md", "query.md", "retile.md", "start.md", diff --git a/nix/tests/vm/suites/core-e2e/test.py b/nix/tests/vm/suites/core-e2e/test.py index 269c27a6..912d9fdf 100644 --- a/nix/tests/vm/suites/core-e2e/test.py +++ b/nix/tests/vm/suites/core-e2e/test.py @@ -3,8 +3,9 @@ # the daemon asked for it (`komorebi/tests/wm_events.rs` checks the window manager's side against # the fake), that the daemon and KWin agree on which window has the focus, that `komorebic` reaches # the daemon of a session and reads its state, that `komorebic focus` and `cycle-focus` move KWin's -# focus (`komorebi/tests/focus.rs` checks which window they pick), and that `komorebic stop` gives -# KWin back what the daemon set up in it. A window manager that agrees with itself proves nothing, so what the daemon +# focus (`komorebi/tests/focus.rs` checks which window they pick), that `komorebic move` and +# `cycle-move` swap windows between their tiles (`komorebi/tests/moving.rs`), and that +# `komorebic stop` gives KWin back what the daemon set up in it. A window manager that agrees with itself proves nothing, so what the daemon # believes is read from its debug log and from `komorebic state`, and what KWin has through kdotool. import json @@ -69,6 +70,12 @@ def state_agrees() -> bool: return active != "" and kde.title(active) == kde.focused_title() +def at(title: str) -> tuple[int, int]: + """Where KWin has the window: foot rounds its size to its cells, but not its position.""" + r = kde.rect(kde.wid(title)) + return (r.x, r.y) + + def report(titles: list[str]) -> None: for title in titles: print(f" {title}: asked {asked(title)}, has {kde.rect(kde.wid(title))}") @@ -134,7 +141,29 @@ checks.check( ) checks.check("moving the focus moved no window", all(where_asked(t) for t in titles)) -print("== 5. minimize and restore") +print("== 5. the windows move on komorebic's commands") +left, top_right = at("win1"), at("win2") +kde.komorebic("move", "right") +checks.check( + "after 'move right' win1 and win2 have swapped tiles", + kde.wait_for(lambda: at("win1") == top_right and at("win2") == left, timeout=20), +) +checks.check( + "... every window is where the daemon asked for it", + kde.wait_for(lambda: all(where_asked(t) for t in titles), timeout=20), +) +checks.check( + "... and win1 keeps the focus", + kde.wait_for(lambda: kde.title(kde.active()) == "win1" and state_agrees()), +) +kde.komorebic("cycle-move", "previous") +checks.check( + "'cycle-move previous' puts win1 and win2 back", + kde.wait_for(lambda: at("win1") == left and at("win2") == top_right, timeout=20), +) +report(titles) + +print("== 6. minimize and restore") kde.minimize(kde.wid("win2")) two = ["win1", "win3"] checks.check( @@ -161,7 +190,7 @@ checks.check( ) report(titles) -print("== 6. close") +print("== 7. close") kde.close(kde.wid("win3")) checks.check("KWin closed win3", kde.wait_for(lambda: kde.wid("win3") == "", timeout=10)) checks.check( @@ -178,7 +207,7 @@ report(["win1", "win2"]) checks.check("komorebi manages the two that are left", kde.wait_for(lambda: kde.managed() == 2)) checks.check("KWin carried out every command", "the bridge could not do" not in daemon_log()) -print("== 7. KWin restarts under the daemon") +print("== 8. KWin restarts under the daemon") kde.restart_kwin() checks.check( "the daemon loaded its script into the new KWin", @@ -199,7 +228,7 @@ checks.check( ) report(["afterwards"]) -print("== 8. komorebic stop") +print("== 9. komorebic stop") kde.komorebic("stop") checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running())) checks.check("its socket is gone", kde.run(f"test -e {kde.runtime}/komorebi/komorebi.sock")[0] != 0) From 41c32aad8ea945139cefd8e1611fe2d7331cae7d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 15:54:21 -0700 Subject: [PATCH 020/255] feat(wm): layouts Every workspace started in BSP and stayed there. `komorebic change-layout` gives the focused workspace one of the layouts of komorebi-layouts, `cycle-layout next|previous` steps through them, and `flip-layout` mirrors the tiles along an axis, on top of the flip there is. A flip mirrors the tiles, not the order of the containers, and the directions of focus and move are flipped with it, so `focus left` still goes to the tile on the left. `toggle-tiling` turns the tiling of the focused workspace off and on: while it is off, no window of the workspace is moved, and the windows that open are taken in and tiled once it is on again. `preselect-direction` reserves the place on one side of the focused window for the next window: an empty container holds it, the layout gives it a tile, and the next window takes it. `cancel-preselect` gives it back. A new VM suite, vm-commands, after the spike's m8 script, runs every layout with five, three, two and one windows against a real KWin with two outputs, and then every komorebic command there is, checking after each that the daemon is alive, answers, and has every window KWin has, and that KWin has the windows where the daemon asked. Every command that comes later adds its line to that sweep. --- README.md | 8 +- docs/cli/cancel-preselect.md | 10 + docs/cli/change-layout.md | 23 ++ docs/cli/cycle-layout.md | 14 + docs/cli/flip-layout.md | 17 ++ docs/cli/preselect-direction.md | 14 + docs/cli/toggle-tiling.md | 10 + docs/dev/ARCHITECTURE.md | 38 ++- docs/dev/vm-tests.md | 5 +- docs/index.md | 3 +- docs/usage/layouts.md | 80 ++++++ komorebi/src/container.rs | 15 ++ komorebi/src/core/mod.rs | 10 + komorebi/src/monitor.rs | 11 +- komorebi/src/process_command.rs | 37 +++ komorebi/src/state.rs | 3 + komorebi/src/window_manager.rs | 201 ++++++++++++++ komorebi/src/workspace.rs | 145 ++++++---- komorebi/tests/layouts.rs | 322 +++++++++++++++++++++++ komorebic/src/main.rs | 50 +++- komorebic/tests/cli.rs | 32 +++ nix/tests/vm/lib/komorebi_vm/kde.py | 9 + nix/tests/vm/lib/tests/test_kde.py | 16 ++ nix/tests/vm/suites/commands/default.nix | 5 + nix/tests/vm/suites/commands/test.py | 216 +++++++++++++++ 25 files changed, 1224 insertions(+), 70 deletions(-) create mode 100644 docs/cli/cancel-preselect.md create mode 100644 docs/cli/change-layout.md create mode 100644 docs/cli/cycle-layout.md create mode 100644 docs/cli/flip-layout.md create mode 100644 docs/cli/preselect-direction.md create mode 100644 docs/cli/toggle-tiling.md create mode 100644 docs/usage/layouts.md create mode 100644 komorebi/tests/layouts.rs create mode 100644 nix/tests/vm/suites/commands/default.nix create mode 100644 nix/tests/vm/suites/commands/test.py diff --git a/README.md b/README.md index 1f2874e8..90970b17 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,8 @@ While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in `$XDG_RUNTIME_DIR/komorebi` (the local data directory when there is no runtime directory): a message can ask for the state of the window manager, ask which monitor, workspace or container has the focus, give the focus to another -window, move the focused window to another tile, retile every monitor, or stop -the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +window, move the focused window to another tile, change the layout, retile +every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, the command line, is how a person sends them. `komorebic start` runs the `komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma session: @@ -135,7 +135,9 @@ message that gives an order changes the model the way an event does: `focus` and `cycle-focus` give the focus to the container on one side of the focused one in the layout, or to the next one in the workspace's order, and `move` and `cycle-move` swap the focused container with that one and tile the workspace -again. +again. `change-layout`, `cycle-layout` and `flip-layout` tile the workspace in +another layout, `toggle-tiling` stops it moving windows and starts it again, +and `preselect-direction` reserves a tile for the next window. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/cancel-preselect.md b/docs/cli/cancel-preselect.md new file mode 100644 index 00000000..6b074090 --- /dev/null +++ b/docs/cli/cancel-preselect.md @@ -0,0 +1,10 @@ +```text +Cancel a workspace preselect set by the preselect-direction command, if one exists + +Usage: cancel-preselect + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/change-layout.md b/docs/cli/change-layout.md new file mode 100644 index 00000000..55bd2f4c --- /dev/null +++ b/docs/cli/change-layout.md @@ -0,0 +1,23 @@ +```text +Set the layout on the focused workspace + +Usage: change-layout + +Arguments: + + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/cycle-layout.md b/docs/cli/cycle-layout.md new file mode 100644 index 00000000..4652d060 --- /dev/null +++ b/docs/cli/cycle-layout.md @@ -0,0 +1,14 @@ +```text +Cycle between available layouts + +Usage: cycle-layout + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/flip-layout.md b/docs/cli/flip-layout.md new file mode 100644 index 00000000..1c79e459 --- /dev/null +++ b/docs/cli/flip-layout.md @@ -0,0 +1,17 @@ +```text +Flip the layout on the focused workspace + +Usage: flip-layout + +Arguments: + + Possible values: + - horizontal: Horizontal axis + - vertical: Vertical axis + - horizontal-and-vertical: Both horizontal and vertical axes + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/preselect-direction.md b/docs/cli/preselect-direction.md new file mode 100644 index 00000000..3d5697cf --- /dev/null +++ b/docs/cli/preselect-direction.md @@ -0,0 +1,14 @@ +```text +Preselect the specified direction for the next window to be spawned on supported layouts + +Usage: preselect-direction + +Arguments: + + [possible values: left, right, up, down] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-tiling.md b/docs/cli/toggle-tiling.md new file mode 100644 index 00000000..6c8d4daa --- /dev/null +++ b/docs/cli/toggle-tiling.md @@ -0,0 +1,10 @@ +```text +Toggle window tiling on the focused workspace + +Usage: toggle-tiling + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 9ea8b995..5aa3d1d6 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -27,7 +27,7 @@ its place here. - **Event**: what the compositor reports about a window: it was shown, destroyed, given the focus, minimized or restored ([`WindowManagerEvent`]). - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order - (focus a window, move it, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). + (focus a window, move it, change the layout, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). - **Direction**: where an order goes from the focused container: a side of its tile ([`OperationDirection`]), or the next or the previous container of the workspace ([`CycleDirection`]). @@ -262,6 +262,22 @@ through `LockableSequence`, so a lock stays with its index: the container swappe index is locked in its place. When there is no container in that direction, the message fails and nothing moves. +`ChangeLayout` and `CycleLayout` set the focused workspace's [`Layout`], and `FlipLayout` +mirrors it along an axis, on top of the flip it has ([`Workspace::layout_flip`]); each tiles +the workspace again ([`WindowManager::change_workspace_layout_default`], +[`WindowManager::cycle_layout`], [`WindowManager::flip_layout`]). A flip mirrors the tiles, +not the order of the containers, and a direction is flipped with them, so `focus left` on a +flipped layout goes to the tile on the left. `ToggleTiling` turns the workspace's tiling off +and on ([`Workspace::tile`]): with it off, [`Workspace::update`] moves no window, the workspace +still takes the windows that open into containers, and they are tiled when it is turned on. + +`PreselectDirection` reserves the index on one side of the focused container for the next +window ([`WindowManager::preselect_container_in_direction`]). The workspace inserts an empty +container there ([`Container::preselect`]), which [`Workspace::update`] keeps and the layout +gives a tile, and [`Workspace::new_container_for_window`] puts the next window in it. +`CancelPreselect` removes it. A workspace reserves one place at a time, and the grid layout +none. + ## The NixOS module The flake exports one module under two names, `nixosModules.default` and @@ -312,7 +328,7 @@ module's unit. changes its containers. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized - window out, move the focus, move the focused container). + window out, move the focus, move the focused container, change the layout). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -395,6 +411,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A socket left behind by a daemon that did not stop cleanly does not keep the next one from starting | framework path: [`WindowManager::new`] removes the file before it binds | `a_socket_file_left_behind_is_replaced` | none | | A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | | A container moved onto a locked index is locked in its place, and the lock leaves the container that moved away | framework path: [`Workspace::swap_containers`] swaps through `LockableSequence`, which keeps the lock with the index | `test_swap_respecting_locks_various_cases`, `a_lock_stays_with_its_index_when_a_window_is_moved_onto_it` | `containers_mut()` is the `VecDeque` itself | +| A workspace whose tiling is off moves no window | framework path: [`Workspace::update`] returns before the layout when [`Workspace::tile`] is false | `with_tiling_off_no_window_is_moved_until_it_is_back_on` | none | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | 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 | @@ -503,9 +520,12 @@ A window is shown, and ends up on a tile: driven end to end against the fake. - [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket, from its start to a `Stop`. -- [`komorebi/tests/focus.rs`](../../komorebi/tests/focus.rs) and - [`komorebi/tests/moving.rs`](../../komorebi/tests/moving.rs): the focus and move commands - against the fake. +- [`komorebi/tests/focus.rs`](../../komorebi/tests/focus.rs), + [`komorebi/tests/moving.rs`](../../komorebi/tests/moving.rs) and + [`komorebi/tests/layouts.rs`](../../komorebi/tests/layouts.rs): the focus, move and layout + commands against the fake. +- [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, + and every `komorebic` command, against a real KWin with two outputs. - [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; [`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix), its scenarios, evaluated in real NixOS systems; and [`nix/tests/vm/suites/module`](../../nix/tests/vm/suites/module/test.py), @@ -537,6 +557,14 @@ A window is shown, and ends up on a tile: [`WindowManager::move_container_in_direction`]: ../../komorebi/src/window_manager.rs [`WindowManager::move_container_in_cycle_direction`]: ../../komorebi/src/window_manager.rs [`Workspace::swap_containers`]: ../../komorebi/src/workspace.rs +[`Workspace::layout_flip`]: ../../komorebi/src/workspace.rs +[`Workspace::tile`]: ../../komorebi/src/workspace.rs +[`Layout`]: ../../komorebi/src/core/mod.rs +[`Container::preselect`]: ../../komorebi/src/container.rs +[`WindowManager::change_workspace_layout_default`]: ../../komorebi/src/window_manager.rs +[`WindowManager::cycle_layout`]: ../../komorebi/src/window_manager.rs +[`WindowManager::flip_layout`]: ../../komorebi/src/window_manager.rs +[`WindowManager::preselect_container_in_direction`]: ../../komorebi/src/window_manager.rs [`Workspace::new_idx_for_direction`]: ../../komorebi/src/workspace.rs [`Workspace::new_idx_for_cycle_direction`]: ../../komorebi/src/workspace.rs [`OperationDirection`]: ../../komorebi/src/core/mod.rs diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index edc86552..dbd17385 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -126,8 +126,9 @@ the run. - `komorebic(*args)` runs `komorebic` in the session and returns what it printed, failing the test if it fails. `state()` is the daemon's state as `komorebic state` prints it, `managed(workspace)` the number of windows the - daemon has on a workspace of the first monitor, and `focused_title(workspace)` - the title of the window it has focused there. + daemon has on a workspace of the first monitor, `managed_all()` the number it + has on every workspace of every monitor, and `focused_title(workspace)` the + title of the window it has focused there. - `daemon` reads the daemon's view of the desktop from that log, at the debug level the nodes set: `daemon.events(log)` lists the window events it handled, in order, `daemon.window_ids(log)` maps a window's title to the daemon's id diff --git a/docs/index.md b/docs/index.md index 7c39a4a0..8da35f5d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -33,7 +33,8 @@ the flake's module, which also starts komorebi with every Plasma session, and fr anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to start and stop the daemon, ask it what it is doing and read its log. [Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window, -and [Moving windows](usage/moving-windows.md) how to move the focused window to another tile. +[Moving windows](usage/moving-windows.md) how to move the focused window to another tile, and +[Layouts](usage/layouts.md) how to change the arrangement of the tiles. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/layouts.md b/docs/usage/layouts.md new file mode 100644 index 00000000..1d01b011 --- /dev/null +++ b/docs/usage/layouts.md @@ -0,0 +1,80 @@ +# Layouts + +The layout of a workspace turns its work area and the number of its containers into one tile +for each container. Every workspace starts with the BSP layout. A command that changes the +layout tiles the focused workspace again at once. + +## The layouts + +These are the layouts of `komorebi-layouts`, in the order `cycle-layout next` goes through them: + +| Layout | `komorebic` name | The tiles | +|---|---|---| +| BSP | `bsp` | each new tile splits the last one in two, alternately side by side and one above the other | +| Columns | `columns` | side by side, as wide as each other | +| Rows | `rows` | one above the other, as high as each other | +| Vertical stack | `vertical-stack` | the first on the left half, the others stacked on the right | +| Horizontal stack | `horizontal-stack` | the first on the top half, the others side by side below it | +| Ultrawide vertical stack | `ultrawide-vertical-stack` | the first in the middle, the second on the left, the others stacked on the right | +| Grid | `grid` | columns of tiles, as even as the number of containers allows | +| Right main vertical stack | `right-main-vertical-stack` | the first on the right half, the others stacked on the left | +| Scrolling | `scrolling` | columns side by side | + +## Changing the layout + +[`komorebic change-layout`](../cli/change-layout.md) gives the focused workspace the layout it +names, and [`komorebic cycle-layout`](../cli/cycle-layout.md) the next or the previous one in +the table above: + +```sh +komorebic change-layout vertical-stack +komorebic cycle-layout next +komorebic cycle-layout previous +``` + +`cycle-layout next` goes from the scrolling layout back to BSP. Going backwards, +`komorebi-layouts` leaves the scrolling layout out: `cycle-layout previous` goes from BSP to the +right main vertical stack. + +[`komorebic query focused-workspace-layout`](../cli/query.md) prints the layout of the focused +workspace. + +## Flipping the layout + +[`komorebic flip-layout`](../cli/flip-layout.md) mirrors the tiles of the focused workspace: +`horizontal` swaps left and right, `vertical` top and bottom, and `horizontal-and-vertical` +both. A flip is added to the one the workspace has, so the same flip twice puts the layout +back. + +```sh +komorebic flip-layout horizontal +komorebic flip-layout horizontal +``` + +The containers keep their order, and the directions of [`focus`](focusing-windows.md) and +[`move`](moving-windows.md) are the ones on the screen: after `flip-layout horizontal`, +`focus left` goes to the tile on the left. + +## Turning tiling off + +[`komorebic toggle-tiling`](../cli/toggle-tiling.md) turns the tiling of the focused workspace +off, and on again. While it is off, komorebi moves none of its windows: they stay where they +are, and can be moved by hand. Windows that open on the workspace are still taken into it, and +when tiling is turned back on, every window is tiled again. `query focused-workspace-layout` +prints `None` while tiling is off. + +## Preselecting a tile + +[`komorebic preselect-direction`](../cli/preselect-direction.md) reserves the place on one side +of the focused window for the next window that opens on the workspace. The layout gives the +reserved place a tile at once, empty until the window opens. +[`komorebic cancel-preselect`](../cli/cancel-preselect.md) gives the place up. + +```sh +komorebic preselect-direction left +komorebic cancel-preselect +``` + +The place is a position in the order of the workspace, so where its tile is depends on the +layout. A workspace reserves one place at a time: a second `preselect-direction` is ignored +until the window opens or the place is given up. The grid layout has no preselection. diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs index f7bf047f..b7176388 100644 --- a/komorebi/src/container.rs +++ b/komorebi/src/container.rs @@ -47,6 +47,21 @@ impl Lockable for Container { } impl Container { + /// Returns the empty container that holds the place a preselection reserved + /// ([`Workspace::preselect_container_idx`](crate::workspace::Workspace::preselect_container_idx)) + pub fn preselect() -> Self { + Self { + id: "PRESELECT".to_string(), + locked: false, + windows: Default::default(), + } + } + + /// Returns true if and only if this is the container of a preselection + pub fn is_preselect(&self) -> bool { + self.id == "PRESELECT" + } + pub fn contains_window(&self, window_id: u32) -> bool { for window in self.windows() { if window.id == window_id { diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 91985bf9..0c08554f 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -339,8 +339,18 @@ pub enum SocketMessage { // Window / Container Commands FocusWindow(OperationDirection), MoveWindow(OperationDirection), + PreselectDirection(OperationDirection), + CancelPreselect, CycleFocusWindow(CycleDirection), CycleMoveWindow(CycleDirection), + // Current Workspace Commands + ChangeLayout(DefaultLayout), + CycleLayout(CycleDirection), + // ChangeLayoutCustom(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + FlipLayout(Axis), + // Monitor and Workspace Commands + // MonitorIndexPreference(usize, i32, i32, i32, i32), + ToggleTiling, Stop, Retile, State, diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index e6208fab..c7c52cf7 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -212,10 +212,15 @@ impl Monitor { } } - /// The layout of the focused workspace, if the monitor has one + /// The layout of the focused workspace, if the monitor has one and its tiling is on pub fn focused_workspace_layout(&self) -> Option { - self.focused_workspace() - .map(|workspace| workspace.layout.clone()) + self.focused_workspace().and_then(|workspace| { + if workspace.tile { + Some(workspace.layout.clone()) + } else { + None + } + }) } } diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 0b0bba22..7c21c0d3 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -20,6 +20,13 @@ //! of it, or with the next or the previous one, and tile the workspace again //! ([`WindowManager::move_container_in_direction`], //! [`WindowManager::move_container_in_cycle_direction`]). +//! - **ChangeLayout**, **CycleLayout** and **FlipLayout** give the focused workspace another +//! layout, or mirror it, and **ToggleTiling** turns its tiling off and on +//! ([`WindowManager::change_workspace_layout_default`], [`WindowManager::cycle_layout`], +//! [`WindowManager::flip_layout`], [`WindowManager::toggle_tiling`]). +//! - **PreselectDirection** reserves the place on one side of the focused container for the next +//! window ([`WindowManager::preselect_container_in_direction`]), unless a place is reserved +//! already, and **CancelPreselect** gives the reserved place up. //! - **MouseFollowsFocus** and **ToggleMouseFollowsFocus** set whether the pointer is moved to //! the window that is given the focus. //! - **Retile** tiles the focused workspace of every monitor again. @@ -114,6 +121,8 @@ impl WindowManager { /// - The focused container cannot be moved, for one of the reasons /// [`WindowManager::move_container_in_direction`] and /// [`WindowManager::move_container_in_cycle_direction`] give. + /// - There is no focused workspace to change the layout or the tiling of, or to preselect a + /// place in, or it cannot be tiled again. /// - The window manager fails to retile, for one of the reasons /// [`WindowManager::retile_all`] gives. /// - The answer cannot be written to `reply`. @@ -135,6 +144,28 @@ impl WindowManager { SocketMessage::FocusWindow(direction) => { self.focus_container_in_direction(direction)?; } + SocketMessage::PreselectDirection(direction) => { + let focused_workspace = self.focused_workspace()?; + let mut update = false; + + if focused_workspace.preselected_container_idx.is_some() { + tracing::warn!( + "ignoring command as this workspace already has a direction preselect set" + ); + } else { + self.preselect_container_in_direction(direction)?; + update = true; + } + + if update { + self.focused_workspace_mut()?.update()?; + } + } + SocketMessage::CancelPreselect => { + let focused_workspace = self.focused_workspace_mut()?; + focused_workspace.cancel_preselect(); + focused_workspace.update()?; + } SocketMessage::MoveWindow(direction) => { self.move_container_in_direction(direction)?; } @@ -144,7 +175,13 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::FlipLayout(layout_flip) => self.flip_layout(layout_flip)?, + SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, + SocketMessage::CycleLayout(direction) => self.cycle_layout(direction)?, SocketMessage::Retile => self.retile_all()?, + SocketMessage::ToggleTiling => { + self.toggle_tiling()?; + } SocketMessage::State => { let state = match serde_json::to_string_pretty(&State::from(&*self)) { Ok(state) => state, diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 37cbcc23..68e2d91d 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -80,9 +80,12 @@ impl From<&WindowManager> for State { .map(|workspace| Workspace { containers: workspace.containers.clone(), layout: workspace.layout.clone(), + layout_flip: workspace.layout_flip, workspace_padding: workspace.workspace_padding, container_padding: workspace.container_padding, + tile: workspace.tile, globals: workspace.globals, + preselected_container_idx: None, }) .collect::>(); ws.focus(monitor.workspaces.focused_idx()); diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 15c4ff4e..171f18ed 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -21,7 +21,10 @@ use crate::LibraryError; use crate::SUBSCRIPTION_SOCKETS; use crate::backend::backend; use crate::container::Container; +use crate::core::Axis; use crate::core::CycleDirection; +use crate::core::DefaultLayout; +use crate::core::Layout; use crate::core::OperationDirection; use crate::core::Rect; use crate::desktop; @@ -120,6 +123,59 @@ impl WindowManager { Ok(()) } + /// Reserves the place on the `direction` side of the focused container for the next window + /// that opens on the focused workspace ([`Workspace::preselect_container_idx`]) + /// + /// The grid layout has no preselection: there, and where there is no container on that side, + /// nothing is reserved. + /// + /// # Errors + /// + /// There is no focused workspace. + #[tracing::instrument(skip(self))] + pub fn preselect_container_in_direction( + &mut self, + direction: OperationDirection, + ) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + let focused_idx = workspace.focused_container_idx(); + + if matches!(workspace.layout, Layout::Default(DefaultLayout::Grid)) { + tracing::warn!("preselection is not supported on the grid layout"); + return Ok(()); + } + + tracing::info!("preselecting container"); + + let new_idx = workspace.new_idx_for_direction(direction); + + match new_idx { + Some(new_idx) => { + let adjusted_idx = match direction { + OperationDirection::Left | OperationDirection::Up => { + if focused_idx.abs_diff(new_idx) == 1 { + new_idx + 1 + } else { + new_idx + } + } + + _ => new_idx, + }; + + workspace.preselect_container_idx(adjusted_idx); + } + + None => { + tracing::debug!( + "this is not a valid preselection direction from the current position" + ) + } + } + + Ok(()) + } + /// Gives the focus to the window of the container whose tile is on the `direction` side of /// the focused one, and the pointer follows it if [`WindowManager::mouse_follows_focus`] is /// set @@ -223,6 +279,21 @@ impl WindowManager { Ok(()) } + /// Gives the focused workspace the layout `layout` and tiles it again + /// + /// # Errors + /// + /// There is no focused workspace, or it cannot be tiled. + #[tracing::instrument(skip(self))] + pub fn change_workspace_layout_default(&mut self, layout: DefaultLayout) -> eyre::Result<()> { + tracing::info!("changing layout"); + + let workspace = self.focused_workspace_mut()?; + + workspace.layout = Layout::Default(layout); + self.update_focused_workspace(self.mouse_follows_focus, false) + } + pub fn focused_workspace_idx(&self) -> eyre::Result { Ok(self .focused_monitor() @@ -344,6 +415,99 @@ impl WindowManager { Ok(()) } + /// Mirrors the layout of the focused workspace along `layout_flip`, on top of the way it is + /// mirrored already, and tiles the workspace again + /// + /// Flipping along an axis the layout is already flipped along undoes that flip, so flipping + /// twice along the same axis puts the layout back. + /// + /// # Errors + /// + /// There is no focused workspace, or it cannot be tiled. + #[tracing::instrument(skip(self))] + pub fn flip_layout(&mut self, layout_flip: Axis) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + + tracing::info!("flipping layout"); + + #[allow(clippy::match_same_arms)] + match workspace.layout_flip { + None => { + workspace.layout_flip = Option::from(layout_flip); + } + Some(current_layout_flip) => { + match current_layout_flip { + Axis::Horizontal => match layout_flip { + Axis::Horizontal => workspace.layout_flip = None, + Axis::Vertical => { + workspace.layout_flip = Option::from(Axis::HorizontalAndVertical) + } + Axis::HorizontalAndVertical => { + workspace.layout_flip = Option::from(Axis::HorizontalAndVertical) + } + }, + Axis::Vertical => match layout_flip { + Axis::Horizontal => { + workspace.layout_flip = Option::from(Axis::HorizontalAndVertical) + } + Axis::Vertical => workspace.layout_flip = None, + Axis::HorizontalAndVertical => { + workspace.layout_flip = Option::from(Axis::HorizontalAndVertical) + } + }, + Axis::HorizontalAndVertical => match layout_flip { + Axis::Horizontal => workspace.layout_flip = Option::from(Axis::Vertical), + Axis::Vertical => workspace.layout_flip = Option::from(Axis::Horizontal), + Axis::HorizontalAndVertical => workspace.layout_flip = None, + }, + }; + } + } + + self.update_focused_workspace(false, false) + } + + /// Gives the focused workspace the next (or the previous) layout, in the order of + /// [`DefaultLayout`], and tiles it again + /// + /// # Errors + /// + /// There is no focused workspace, or it cannot be tiled. + #[tracing::instrument(skip(self))] + pub fn cycle_layout(&mut self, direction: CycleDirection) -> eyre::Result<()> { + tracing::info!("cycling layout"); + + let workspace = self.focused_workspace_mut()?; + + match workspace.layout { + Layout::Default(current) => { + let new_layout = match direction { + CycleDirection::Previous => current.cycle_previous(), + CycleDirection::Next => current.cycle_next(), + }; + + tracing::info!("next layout: {new_layout}"); + workspace.layout = Layout::Default(new_layout); + } + } + + self.update_focused_workspace(self.mouse_follows_focus, false) + } + + /// Turns the tiling of the focused workspace off, or back on and tiles it again + /// + /// While its tiling is off, the workspace keeps its containers and moves no window. + /// + /// # Errors + /// + /// There is no focused workspace, or it cannot be tiled. + #[tracing::instrument(skip(self))] + pub fn toggle_tiling(&mut self) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + workspace.tile = !workspace.tile; + self.update_focused_workspace(false, false) + } + /// Gives the focus to the window of the next (or the previous) container of the focused /// workspace, wrapping around at the ends, and the pointer follows it if /// [`WindowManager::mouse_follows_focus`] is set @@ -524,6 +688,43 @@ mod tests { assert_eq!(wm.focused_container_idx().unwrap(), 0); } + #[test] + fn test_toggle_tiling() { + let (mut wm, _context) = setup_window_manager(); + + { + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + let workspace = m.focused_workspace_mut().unwrap(); + + // Tiling state should be true + assert!(workspace.tile); + + // Add monitor to workspace + wm.monitors_mut().push_back(m); + } + + { + // Tiling state should be false + wm.toggle_tiling().unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert!(!workspace.tile); + } + + { + // Tiling state should be true + wm.toggle_tiling().unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert!(workspace.tile); + } + } + #[test] fn a_socket_file_left_behind_is_replaced() -> eyre::Result<()> { let socket_path = PathBuf::from(format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4())); diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index f21e0da0..92e403a0 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -6,6 +6,7 @@ //! falls back to come from the monitor it is on ([`WorkspaceGlobals`]). use crate::container::Container; +use crate::core::Axis; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; @@ -26,10 +27,14 @@ use std::num::NonZeroUsize; pub struct Workspace { pub containers: Ring, pub layout: Layout, + pub layout_flip: Option, pub workspace_padding: Option, pub container_padding: Option, + pub tile: bool, #[serde(skip)] pub globals: WorkspaceGlobals, + #[serde(skip_serializing_if = "Option::is_none")] + pub preselected_container_idx: Option, } impl_ring_elements!(Workspace, Container); @@ -41,7 +46,10 @@ impl Default for Workspace { workspace_padding: None, container_padding: None, layout: Layout::Default(DefaultLayout::BSP), + layout_flip: None, globals: Default::default(), + tile: true, + preselected_container_idx: None, } } } @@ -69,6 +77,22 @@ impl Workspace { self.focus_container(j); } + /// Reserves the index `insertion_idx` for the next window: an empty container is inserted + /// there, which the layout gives a tile, and [`Workspace::new_container_for_window`] puts the + /// next window in it + pub fn preselect_container_idx(&mut self, insertion_idx: usize) { + self.preselected_container_idx = Some(insertion_idx); + self.insert_container_at_idx(insertion_idx, Container::preselect()); + } + + /// Removes the container a preselection reserved, if there is one + pub fn cancel_preselect(&mut self) { + if let Some(idx) = self.preselected_container_idx { + self.containers_mut().remove_respecting_locks(idx); + self.preselected_container_idx = None; + } + } + /// Returns the index of the container whose tile is on the `direction` side of the focused /// one in the workspace's layout, or `None` when there is none on that side pub fn new_idx_for_direction(&self, direction: OperationDirection) -> Option { @@ -76,7 +100,7 @@ impl Workspace { direction.destination( self.layout.as_boxed_direction().as_ref(), - None, + self.layout_flip, self.focused_container_idx(), len, None, @@ -124,10 +148,16 @@ impl Workspace { Ok(()) } - /// Puts the window in a container of its own, after the focused container (at the start of an - /// empty workspace), and focuses that container + /// Puts the window in a container of its own, and focuses that container: in the container a + /// preselection reserved, if there is one, and otherwise after the focused container (at the + /// start of an empty workspace) pub fn new_container_for_window(&mut self, window: &Window) -> eyre::Result<()> { - let next_idx = if self.containers().is_empty() { + let next_idx = if let Some(idx) = self.preselected_container_idx { + let next = idx; + self.preselected_container_idx = None; + self.remove_container_by_idx(next); + next + } else if self.containers().is_empty() { 0 } else { self.focused_container_idx() + 1 @@ -291,14 +321,16 @@ impl Workspace { /// Tiles the workspace: asks the layout for a tile per container in the work area, less the /// offset and the workspace padding, and puts every window of each container on its tile. /// - /// Containers that have no windows left are dropped first, and so is a window that is in more - /// than one container. A tile is clamped to the work area, so it cannot bleed onto a - /// neighboring monitor. + /// Containers that have no windows left are dropped first, except the one a preselection + /// reserved, and so is a window that is in more than one container. A tile is clamped to the + /// work area, so it cannot bleed onto a neighboring monitor. A workspace whose tiling is off + /// ([`Workspace::tile`] is false) moves no window. pub fn update(&mut self) -> eyre::Result<()> { // make sure we are never holding on to empty containers self.prune_duplicate_windows()?; let focused_container_idx = self.focused_container_idx(); - self.containers_mut().retain(|c| !c.windows().is_empty()); + self.containers_mut() + .retain(|c| c.is_preselect() || !c.windows().is_empty()); // make sure we are never focused on a no longer existent final empty container if focused_container_idx >= self.containers().len() { @@ -331,63 +363,66 @@ impl Workspace { adjusted_work_area.add_padding(workspace_padding); - // the backend batches the commands this produces and sends them together - let result = (|| -> eyre::Result<()> { - if !self.containers().is_empty() { - let mut layouts = self.layout.as_boxed_arrangement().calculate( - &adjusted_work_area, - NonZeroUsize::new(self.containers().len()).ok_or_eyre( - "there must be at least one container to calculate a workspace layout", - )?, - Some(container_padding), - None, - &[], - self.focused_container_idx(), - None, - &[], - ); + if self.tile { + // the backend batches the commands this produces and sends them together + let result = (|| -> eyre::Result<()> { + if !self.containers().is_empty() { + let mut layouts = self.layout.as_boxed_arrangement().calculate( + &adjusted_work_area, + NonZeroUsize::new(self.containers().len()).ok_or_eyre( + "there must be at least one container to calculate a workspace layout", + )?, + Some(container_padding), + self.layout_flip, + &[], + self.focused_container_idx(), + None, + &[], + ); - let containers = self.containers_mut(); + let containers = self.containers_mut(); - for (i, container) in containers.iter_mut().enumerate() { - if let Some(layout) = layouts.get_mut(i) { - // Every tile is clamped to the work area so it cannot bleed onto an - // adjacent monitor. + for (i, container) in containers.iter_mut().enumerate() { + if let Some(layout) = layouts.get_mut(i) { + // Every tile is clamped to the work area so it cannot bleed onto an + // adjacent monitor. - // horizontal - if layout.left < adjusted_work_area.left { - layout.right -= adjusted_work_area.left - layout.left; - layout.left = adjusted_work_area.left; - } - let max_right_edge = adjusted_work_area.left + adjusted_work_area.right; - let current_right_edge = layout.left + layout.right; - if current_right_edge > max_right_edge { - layout.right = max_right_edge - layout.left; - } + // horizontal + if layout.left < adjusted_work_area.left { + layout.right -= adjusted_work_area.left - layout.left; + layout.left = adjusted_work_area.left; + } + let max_right_edge = adjusted_work_area.left + adjusted_work_area.right; + let current_right_edge = layout.left + layout.right; + if current_right_edge > max_right_edge { + layout.right = max_right_edge - layout.left; + } - // vertical - if layout.top < adjusted_work_area.top { - layout.bottom -= adjusted_work_area.top - layout.top; - layout.top = adjusted_work_area.top; - } - let max_bottom_edge = adjusted_work_area.top + adjusted_work_area.bottom; - let current_bottom_edge = layout.top + layout.bottom; - if current_bottom_edge > max_bottom_edge { - layout.bottom = max_bottom_edge - layout.top; - } + // vertical + if layout.top < adjusted_work_area.top { + layout.bottom -= adjusted_work_area.top - layout.top; + layout.top = adjusted_work_area.top; + } + let max_bottom_edge = + adjusted_work_area.top + adjusted_work_area.bottom; + let current_bottom_edge = layout.top + layout.bottom; + if current_bottom_edge > max_bottom_edge { + layout.bottom = max_bottom_edge - layout.top; + } - for window in container.windows_mut() { - if let Err(error) = window.set_position(layout) { - tracing::warn!("failed to set window position: {error}") + for window in container.windows_mut() { + if let Err(error) = window.set_position(layout) { + tracing::warn!("failed to set window position: {error}") + } } } } } - } - Ok(()) - })(); + Ok(()) + })(); - result?; + result?; + } Ok(()) } diff --git a/komorebi/tests/layouts.rs b/komorebi/tests/layouts.rs new file mode 100644 index 00000000..7553a123 --- /dev/null +++ b/komorebi/tests/layouts.rs @@ -0,0 +1,322 @@ +//! Changing, cycling and flipping the layout of the focused workspace, turning its tiling off and +//! on, and preselecting the place of the next window, against an in-memory desktop: the messages +//! go in through [`WindowManager::process_command`], and what comes out is where the backend is +//! asked to put each window. +//! +//! Window ids are in the 21_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::Axis; +use komorebi::core::CycleDirection; +use komorebi::core::DefaultLayout; +use komorebi::core::OperationDirection; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::core::StateQuery; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor, and a window for each of +/// `ids`, opened in that order. The last one has the focus. +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kml-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + for &id in ids { + open(&fake, &mut wm, id); + } + wm + }); + + (fake, wm) +} + +fn open(fake: &Arc, wm: &mut WindowManager, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn layout(fake: &Arc, wm: &mut WindowManager) -> String { + let mut reply = Vec::new(); + with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::Query(StateQuery::FocusedWorkspaceLayout), + &mut reply, + ) + }) + .unwrap(); + String::from_utf8(reply).unwrap() +} + +fn rects(fake: &FakeBackend, ids: &[u32]) -> Vec { + ids.iter().map(|&id| fake.rect_of(id).unwrap()).collect() +} + +/// The window of each container of the focused workspace, in order (0 for an empty container) +fn order(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().map_or(0, |window| window.id)) + .collect() +} + +#[test] +fn change_layout_tiles_the_workspace_again_in_the_layout_it_names() { + let ids = [21_001, 21_002, 21_003]; + let (fake, mut wm) = desktop_with(&ids); + assert_eq!(layout(&fake, &mut wm), "BSP"); + + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Columns), + ); + + assert_eq!(layout(&fake, &mut wm), "Columns"); + let tiles = rects(&fake, &ids); + assert!( + tiles + .iter() + .all(|tile| tile.top == tiles[0].top && tile.bottom == tiles[0].bottom), + "columns are as high as each other: {tiles:?}" + ); + assert!( + tiles[0].left < tiles[1].left && tiles[1].left < tiles[2].left, + "the columns are in the order of the containers: {tiles:?}" + ); +} + +#[test] +fn cycle_layout_goes_through_the_layouts_in_order_and_wraps_around() { + let (fake, mut wm) = desktop_with(&[21_011]); + + send( + &fake, + &mut wm, + SocketMessage::CycleLayout(CycleDirection::Next), + ); + assert_eq!(layout(&fake, &mut wm), "Columns"); + + send( + &fake, + &mut wm, + SocketMessage::CycleLayout(CycleDirection::Previous), + ); + assert_eq!(layout(&fake, &mut wm), "BSP"); + + let mut seen = vec![]; + for _ in 0..9 { + send( + &fake, + &mut wm, + SocketMessage::CycleLayout(CycleDirection::Next), + ); + seen.push(layout(&fake, &mut wm)); + } + assert_eq!( + seen, + [ + "Columns", + "Rows", + "VerticalStack", + "HorizontalStack", + "UltrawideVerticalStack", + "Grid", + "RightMainVerticalStack", + "Scrolling", + "BSP", + ], + "the one after the last is the first" + ); + + // komorebi-layouts leaves the scrolling layout out going backwards + send( + &fake, + &mut wm, + SocketMessage::CycleLayout(CycleDirection::Previous), + ); + assert_eq!(layout(&fake, &mut wm), "RightMainVerticalStack"); +} + +#[test] +fn flip_layout_mirrors_the_tiles_and_the_same_flip_again_puts_them_back() { + let ids = [21_021, 21_022]; + let (fake, mut wm) = desktop_with(&ids); + let before = rects(&fake, &ids); + assert!(before[0].left < before[1].left); + + send(&fake, &mut wm, SocketMessage::FlipLayout(Axis::Horizontal)); + + let flipped = rects(&fake, &ids); + assert_eq!( + flipped[0].left, before[1].left, + "the first window has the right tile" + ); + assert_eq!( + flipped[1].left, before[0].left, + "the second window has the left tile" + ); + + send(&fake, &mut wm, SocketMessage::FlipLayout(Axis::Horizontal)); + + assert_eq!(rects(&fake, &ids), before); +} + +#[test] +fn with_tiling_off_no_window_is_moved_until_it_is_back_on() { + let ids = [21_031, 21_032]; + let (fake, mut wm) = desktop_with(&ids); + let tiles = rects(&fake, &ids); + + send(&fake, &mut wm, SocketMessage::ToggleTiling); + assert_eq!(layout(&fake, &mut wm), "None"); + + let by_hand = Rect { + left: 300, + top: 300, + right: 400, + bottom: 400, + }; + fake.move_window_by_user(21_031, by_hand); + open(&fake, &mut wm, 21_033); + send(&fake, &mut wm, SocketMessage::Retile); + + assert_eq!( + fake.rect_of(21_031), + Some(by_hand), + "moved back by the retile" + ); + assert_eq!( + fake.rect_of(21_033).map(|rect| (rect.right, rect.bottom)), + Some((800, 600)), + "the new window keeps the size it opened with" + ); + assert_eq!( + order(&wm), + [21_031, 21_032, 21_033], + "it is in a container all the same" + ); + + send(&fake, &mut wm, SocketMessage::ToggleTiling); + + assert_eq!(layout(&fake, &mut wm), "BSP"); + assert_ne!(fake.rect_of(21_031), Some(by_hand)); + assert_ne!( + rects(&fake, &ids), + tiles, + "three windows share the work area now" + ); +} + +#[test] +fn preselect_reserves_a_tile_that_the_next_window_takes() { + let ids = [21_041, 21_042]; + let (fake, mut wm) = desktop_with(&ids); + let before = rects(&fake, &ids); + + send( + &fake, + &mut wm, + SocketMessage::PreselectDirection(OperationDirection::Left), + ); + + assert_eq!( + order(&wm), + [21_041, 0, 21_042], + "an empty container holds the place" + ); + assert_ne!( + fake.rect_of(21_042), + Some(before[1]), + "the reserved tile takes room" + ); + + open(&fake, &mut wm, 21_043); + + assert_eq!(order(&wm), [21_041, 21_043, 21_042]); + assert_eq!( + wm.focused_workspace().unwrap().preselected_container_idx, + None + ); +} + +#[test] +fn cancel_preselect_gives_the_reserved_tile_back() { + let ids = [21_051, 21_052]; + let (fake, mut wm) = desktop_with(&ids); + let before = rects(&fake, &ids); + + send( + &fake, + &mut wm, + SocketMessage::PreselectDirection(OperationDirection::Left), + ); + send(&fake, &mut wm, SocketMessage::CancelPreselect); + + assert_eq!(order(&wm), ids); + assert_eq!(rects(&fake, &ids), before); +} + +#[test] +fn a_second_preselect_is_ignored_while_a_place_is_reserved() { + let (fake, mut wm) = desktop_with(&[21_061, 21_062]); + + send( + &fake, + &mut wm, + SocketMessage::PreselectDirection(OperationDirection::Left), + ); + send( + &fake, + &mut wm, + SocketMessage::PreselectDirection(OperationDirection::Left), + ); + + assert_eq!(order(&wm), [21_061, 0, 21_062]); +} + +#[test] +fn the_grid_layout_has_no_preselect() { + let (fake, mut wm) = desktop_with(&[21_071, 21_072]); + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Grid), + ); + + send( + &fake, + &mut wm, + SocketMessage::PreselectDirection(OperationDirection::Left), + ); + + assert_eq!(order(&wm), [21_071, 21_072]); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 78892efe..c1c970b9 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -7,7 +7,10 @@ //! //! `focus` and `cycle-focus` give the focus to another window of the focused workspace, and //! `mouse-follows-focus` and `toggle-mouse-follows-focus` set whether the pointer goes with it. -//! `move` and `cycle-move` move the focused window to another tile. +//! `move` and `cycle-move` move the focused window to another tile. `change-layout`, +//! `cycle-layout` and `flip-layout` change the layout of the focused workspace, `toggle-tiling` +//! turns its tiling off and on, and `preselect-direction` and `cancel-preselect` reserve the +//! place of the next window and give it up. //! //! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens //! on a socket in the daemon's data directory, to which the daemon sends a notification after each @@ -24,7 +27,9 @@ use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; use fs_tail::TailedFile; +use komorebi_client::Axis; use komorebi_client::CycleDirection; +use komorebi_client::DefaultLayout; use komorebi_client::OperationDirection; use komorebi_client::SocketMessage; use komorebi_client::StateQuery; @@ -72,8 +77,13 @@ macro_rules! gen_enum_subcommand_args { gen_enum_subcommand_args! { Focus: OperationDirection, Move: OperationDirection, + PreselectDirection: OperationDirection, CycleFocus: CycleDirection, CycleMove: CycleDirection, + FlipLayout: Axis, + ChangeLayout: DefaultLayout, + CycleLayout: CycleDirection, + // WatchConfiguration: BooleanState, MouseFollowsFocus: BooleanState, Query: StateQuery, } @@ -165,14 +175,34 @@ enum SubCommand { /// Move the focused window in the specified direction #[clap(arg_required_else_help = true)] Move(Move), + /// Preselect the specified direction for the next window to be spawned on supported layouts + #[clap(arg_required_else_help = true)] + PreselectDirection(PreselectDirection), + /// Cancel a workspace preselect set by the preselect-direction command, if one exists + CancelPreselect, /// Change focus to the window in the specified cycle direction #[clap(arg_required_else_help = true)] CycleFocus(CycleFocus), /// Move the focused window in the specified cycle direction #[clap(arg_required_else_help = true)] CycleMove(CycleMove), + /// Set the layout on the focused workspace + #[clap(arg_required_else_help = true)] + ChangeLayout(ChangeLayout), + /// Cycle between available layouts + #[clap(arg_required_else_help = true)] + CycleLayout(CycleLayout), + // /// Load a custom layout from file for the focused workspace + // #[clap(hide = true)] + // #[clap(arg_required_else_help = true)] + // LoadCustomLayout(LoadCustomLayout), + /// Flip the layout on the focused workspace + #[clap(arg_required_else_help = true)] + FlipLayout(FlipLayout), /// Force the retiling of all managed windows Retile, + /// Toggle window tiling on the focused workspace + ToggleTiling, /// Enable or disable mouse follows focus on all workspaces #[clap(arg_required_else_help = true)] MouseFollowsFocus(MouseFollowsFocus), @@ -301,15 +331,33 @@ fn main() -> eyre::Result<()> { SubCommand::Move(args) => { send_message(&SocketMessage::MoveWindow(args.operation_direction))?; } + SubCommand::PreselectDirection(args) => { + send_message(&SocketMessage::PreselectDirection(args.operation_direction))?; + } + SubCommand::CancelPreselect => { + send_message(&SocketMessage::CancelPreselect)?; + } SubCommand::CycleFocus(args) => { send_message(&SocketMessage::CycleFocusWindow(args.cycle_direction))?; } SubCommand::CycleMove(args) => { send_message(&SocketMessage::CycleMoveWindow(args.cycle_direction))?; } + SubCommand::ChangeLayout(args) => { + send_message(&SocketMessage::ChangeLayout(args.default_layout))?; + } + SubCommand::CycleLayout(args) => { + send_message(&SocketMessage::CycleLayout(args.cycle_direction))?; + } + SubCommand::FlipLayout(args) => { + send_message(&SocketMessage::FlipLayout(args.axis))?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } + SubCommand::ToggleTiling => { + send_message(&SocketMessage::ToggleTiling)?; + } SubCommand::State => { print_query(&SocketMessage::State); } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 41ae4097..b052d92a 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -190,6 +190,32 @@ fn move_and_cycle_move_send_the_direction_they_are_given() { ); } +#[test] +fn the_layout_subcommands_send_the_layout_axis_or_direction_they_are_given() { + sends( + &["change-layout", "vertical-stack"], + r#"{"type":"ChangeLayout","content":"VerticalStack"}"#, + ); + sends( + &["change-layout", "bsp"], + r#"{"type":"ChangeLayout","content":"BSP"}"#, + ); + sends( + &["cycle-layout", "next"], + r#"{"type":"CycleLayout","content":"Next"}"#, + ); + sends( + &["flip-layout", "horizontal-and-vertical"], + r#"{"type":"FlipLayout","content":"HorizontalAndVertical"}"#, + ); + sends(&["toggle-tiling"], r#"{"type":"ToggleTiling"}"#); + sends( + &["preselect-direction", "up"], + r#"{"type":"PreselectDirection","content":"Up"}"#, + ); + sends(&["cancel-preselect"], r#"{"type":"CancelPreselect"}"#); +} + #[test] fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { sends( @@ -245,15 +271,20 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { assert_eq!( pages, [ + "cancel-preselect.md", + "change-layout.md", "completions.md", "cycle-focus.md", + "cycle-layout.md", "cycle-move.md", "data-directory.md", + "flip-layout.md", "focus.md", "log.md", "monitor-information.md", "mouse-follows-focus.md", "move.md", + "preselect-direction.md", "query.md", "retile.md", "start.md", @@ -261,6 +292,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "stop.md", "subscribe-socket.md", "toggle-mouse-follows-focus.md", + "toggle-tiling.md", "unsubscribe-socket.md", ] ); diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index e07c3e32..17960b28 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -288,6 +288,15 @@ class Kde: containers = self._workspace(workspace)["containers"]["elements"] return sum(len(container["windows"]["elements"]) for container in containers) + def managed_all(self) -> int: + """The number of windows the daemon has, in the containers of every workspace it has.""" + return sum( + len(container["windows"]["elements"]) + for monitor in self.state()["monitors"]["elements"] + for workspace in monitor["workspaces"]["elements"] + for container in workspace["containers"]["elements"] + ) + def monitor_bridge(self, path: str) -> None: """Starts recording the bridge's traffic on the session bus to `path`, in the background. diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index 21dbe48a..cc684f7e 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -381,6 +381,22 @@ def test_managed_counts_the_windows_of_every_container_of_the_workspace( assert kde.managed(1) == 1 +def test_managed_all_counts_the_windows_of_every_workspace_of_every_monitor( + machine: FakeMachine, +) -> None: + first = {"id": 1, "workspaces": {"elements": [workspace(container("a", "b"))], "focused": 0}} + second = { + "id": 2, + "workspaces": {"elements": [workspace(container("c")), workspace()], "focused": 0}, + } + machine.reply( + "komorebic state", + output=json.dumps({"monitors": {"elements": [first, second], "focused": 0}}), + ) + + assert Kde(machine, "main").managed_all() == 3 + + def test_managed_is_zero_for_a_workspace_without_containers(machine: FakeMachine) -> None: machine.reply("komorebic state", output=a_state(workspace())) diff --git a/nix/tests/vm/suites/commands/default.nix b/nix/tests/vm/suites/commands/default.nix new file mode 100644 index 00000000..b51bc717 --- /dev/null +++ b/nix/tests/vm/suites/commands/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 15; +} diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py new file mode 100644 index 00000000..2f6eac41 --- /dev/null +++ b/nix/tests/vm/suites/commands/test.py @@ -0,0 +1,216 @@ +# Every layout, and a sweep of komorebic's commands, against a real headless KWin with two outputs. +# +# After each command the same things have to be true: komorebi is alive, it can still say what it +# knows (`komorebic state`), and every window it has is a window KWin has. After each layout, the +# windows are inside the outputs and do not lie on each other. A command is also expected to be +# understood (exit status 0). The Rust tests check what each command does against the fake; this +# suite checks that none of them breaks the daemon in a real session, and that what the daemon +# asks KWin for is what KWin carries out. Every command `komorebic` has is in the sweep. +import shlex + +from komorebi_vm import Checks, Kde, daemon + +W, H = 1920, 1080 +OUTPUTS = 2 +# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for +CELL = 24 +LAYOUTS = [ + "bsp", + "columns", + "rows", + "vertical-stack", + "horizontal-stack", + "ultrawide-vertical-stack", + "grid", + "right-main-vertical-stack", + "scrolling", +] + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(W, H), outputs=OUTPUTS, scale=SCALE) + + +def live_windows() -> list[str]: + """The ids of the windows KWin has: every client of this suite is a foot.""" + return kde.run("kdotool search --class foot")[1].split() + + +def healthy() -> int: + """0 when komorebi is running, answers `komorebic state` and has every window KWin has. + + Otherwise the reason: 1 not running, 2 no state, 3 not the windows KWin has. + """ + if not kde.komorebi_running(): + return 1 + status, _ = kde.run("komorebic state") + if status != 0: + return 2 + if kde.managed_all() != len(live_windows()): + return 3 + return 0 + + +def outside_or_overlapping() -> list[str]: + """The windows that are outside the outputs, or on another window (2 pixels are allowed).""" + rects = {wid: kde.rect(wid) for wid in live_windows()} + bad = [] + for wid, r in rects.items(): + if r.x < -1 or r.y < -1 or r.x + r.w > W * OUTPUTS + 1 or r.y + r.h > H + 1: + bad.append(f"{kde.title(wid)} outside at {r}") + ids = list(rects) + for i, a in enumerate(ids): + for b in ids[i + 1 :]: + ra, rb = rects[a], rects[b] + if ( + ra.x < rb.x + rb.w - 2 + and rb.x < ra.x + ra.w - 2 + and ra.y < rb.y + rb.h - 2 + and rb.y < ra.y + ra.h - 2 + ): + bad.append(f"{kde.title(a)} on {kde.title(b)}") + return bad + + +def open_window(n: int) -> None: + title = f"win{n}" + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda: kde.wid(title) != "", timeout=30) + + +def close_window(n: int) -> None: + title = f"win{n}" + kde.close(kde.wid(title)) + kde.wait_for(lambda: kde.wid(title) == "", timeout=10) + + +def where_asked(wid: str) -> str | None: + """None when KWin has the window where the daemon last asked, else what is wrong.""" + title = kde.title(wid) + want, have = daemon.asked(kde.komorebi_log(), title), kde.rect(wid) + if want is None: + return f"{title}: the daemon never asked for a frame" + if (have.x, have.y) != (want.x, want.y) or not ( + 0 <= want.w - have.w < CELL and 0 <= want.h - have.h < CELL + ): + return f"{title}: asked {want}, has {have}" + return None + + +print("== 1. start, and five windows on the first output") +kde.start_komorebi() +checks.check( + "the daemon answers komorebic, with both outputs", + kde.wait_for( + lambda: kde.run("komorebic monitor-information")[0] == 0 + and len(kde.state()["monitors"]["elements"]) == OUTPUTS, + timeout=30, + ), +) +for n in range(1, 6): + open_window(n) +checks.check( + "five windows, and komorebi has all five", + kde.wait_for(lambda: kde.managed() == 5 and healthy() == 0, timeout=20), +) + +print("== 2. every layout, with five, three, two and one windows") +for layout in LAYOUTS: + kde.komorebic("change-layout", layout) + verdict = [] + for keep in (5, 3, 2, 1): + while kde.managed() > keep: + close_window(kde.managed()) + kde.wait_for(lambda: healthy() == 0, timeout=10) + # the daemon retiles on the close; give KWin the time to carry it out + kde.wait_for(lambda: all(where_asked(w) is None for w in live_windows()), timeout=10) + # the scrolling layout is a strip whose columns can be past the edge of the output + if layout != "scrolling": + verdict += [f"{keep}w: {bad}" for bad in outside_or_overlapping()] + reason = healthy() + if reason: + verdict.append(f"{keep}w: not healthy ({reason})") + checks.check( + f"{layout}: the windows are in their outputs and do not overlap, and komorebi is healthy" + + "".join(f"\n {v}" for v in verdict), + verdict == [], + ) + for n in range(kde.managed() + 1, 6): + open_window(n) + kde.wait_for(lambda: kde.managed() == 5, timeout=20) +kde.komorebic("change-layout", "bsp") + +print("== 3. a sweep of commands (each must be understood, and leave komorebi healthy)") +SWEEP = """ +focus left +focus right +focus up +focus down +move left +move right +move up +move down +cycle-focus next +cycle-focus previous +cycle-move next +cycle-move previous +retile +flip-layout horizontal +flip-layout vertical +flip-layout horizontal-and-vertical +flip-layout horizontal-and-vertical +cycle-layout next +cycle-layout previous +change-layout columns +change-layout bsp +preselect-direction left +cancel-preselect +toggle-tiling +toggle-tiling +mouse-follows-focus enable +mouse-follows-focus disable +toggle-mouse-follows-focus +toggle-mouse-follows-focus +retile +""" +for line in SWEEP.strip().splitlines(): + status, out = kde.run(shlex.join(["komorebic", *line.split()])) + if status != 0: + checks.bad(f"komorebic {line}: exit {status}: {' '.join(out.splitlines()[:2])}") + continue + if not kde.wait_for(lambda: healthy() == 0, timeout=5): + checks.bad(f"komorebic {line}: komorebi is not healthy afterwards ({healthy()})") + continue + checks.ok(f"komorebic {line}") + +print("== 4. what komorebic only prints") +for args in ["state", "monitor-information", "data-directory"]: + checks.check(f"komorebic {args}", kde.run(f"komorebic {args}")[0] == 0) +for query in [ + "focused-monitor-index", + "focused-workspace-index", + "focused-container-index", + "focused-window-index", + "focused-workspace-layout", + "focused-container-kind", + "version", +]: + status, out = kde.run(f"komorebic query {query}") + checks.check(f"query {query} answers", status == 0 and out.strip() != "") + +print("== 5. still all there") +checks.check("komorebi has every window KWin has, and answers", healthy() == 0) +for wid in live_windows(): + print(f" {kde.title(wid)}: {kde.rect(wid)}") +mismatch = [m for m in (where_asked(w) for w in live_windows()) if m is not None] +for m in mismatch: + print(f" {m}") +checks.check("every window is where komorebi last asked for it", mismatch == []) +kde.komorebic("stop") +checks.check("a clean stop", kde.wait_for(lambda: not kde.komorebi_running())) + +kde.stop() +checks.finish() From 37b06993d26947eee7d366499fbc79d5a5313575 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 16:08:34 -0700 Subject: [PATCH 021/255] feat(wm): tune layouts, and the scrolling layout `komorebic layout-ratios --columns ... --rows ...` sets the share of the work area the first columns and rows of the focused workspace's layout take, and `scrolling-layout-columns N` how many columns of the scrolling layout are in view. Both are layout options of the workspace, which komorebi-layouts reads. The scrolling layout is a strip of columns that runs past the edges of the work area, so its tiles are not clamped to it: the windows of the columns out of view are off the screen. When a window of a scrolling workspace gets the focus, the workspace is tiled after the focused container changed, which scrolls the strip to it. KWin moves a window anywhere, but keeps 100 pixels of a window it resizes on an output once the client has drawn at the new size, which pulls the columns out of view back onto the screen. The bridge remembers the position it was asked for, for a second, and asks again for the position alone when KWin moved the window elsewhere, three times at most. komorebi-layouts compiles `Rect::percentage_within_horizontal_bounds` only with its darwin feature, which this repository does not enable, so the workspace has its own copy of it. A new VM suite, vm-scrolling, after the spike's m2-scrolling script, checks in a real KWin that the columns out of view stay where komorebi put them and that the strip follows `komorebic focus`; vm-commands sweeps the two new commands. --- README.md | 7 +- docs/cli/layout-ratios.md | 16 ++ docs/cli/scrolling-layout-columns.md | 14 ++ docs/dev/ARCHITECTURE.md | 25 ++- docs/dev/DESIGN.md | 13 ++ docs/dev/PLATFORM.md | 10 ++ docs/usage/layouts.md | 36 ++++ komorebi/src/core/mod.rs | 3 + komorebi/src/kwin/bridge.js | 38 ++++ komorebi/src/kwin/bridge.test.js | 73 +++++++- komorebi/src/kwin/kwin-api.d.ts | 4 + komorebi/src/process_command.rs | 53 ++++++ komorebi/src/process_event.rs | 19 +- komorebi/src/state.rs | 2 + komorebi/src/window.rs | 22 +++ komorebi/src/workspace.rs | 112 +++++++++--- komorebi/tests/layout_options.rs | 206 ++++++++++++++++++++++ komorebi/tests/scrolling.rs | 119 +++++++++++++ komorebic/src/main.rs | 39 +++- komorebic/tests/cli.rs | 40 +++++ nix/tests/vm/suites/commands/test.py | 2 + nix/tests/vm/suites/scrolling/default.nix | 5 + nix/tests/vm/suites/scrolling/test.py | 89 ++++++++++ 23 files changed, 908 insertions(+), 39 deletions(-) create mode 100644 docs/cli/layout-ratios.md create mode 100644 docs/cli/scrolling-layout-columns.md create mode 100644 komorebi/tests/layout_options.rs create mode 100644 komorebi/tests/scrolling.rs create mode 100644 nix/tests/vm/suites/scrolling/default.nix create mode 100644 nix/tests/vm/suites/scrolling/test.py diff --git a/README.md b/README.md index 90970b17..be1a4b58 100644 --- a/README.md +++ b/README.md @@ -136,8 +136,11 @@ and `cycle-focus` give the focus to the container on one side of the focused one in the layout, or to the next one in the workspace's order, and `move` and `cycle-move` swap the focused container with that one and tile the workspace again. `change-layout`, `cycle-layout` and `flip-layout` tile the workspace in -another layout, `toggle-tiling` stops it moving windows and starts it again, -and `preselect-direction` reserves a tile for the next window. +another layout, `layout-ratios` and `scrolling-layout-columns` tune it, +`toggle-tiling` stops it moving windows and starts it again, and +`preselect-direction` reserves a tile for the next window. The scrolling layout +is a strip of columns that runs past the edges of the monitor and scrolls to +the window that has the focus. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/layout-ratios.md b/docs/cli/layout-ratios.md new file mode 100644 index 00000000..713bf9d9 --- /dev/null +++ b/docs/cli/layout-ratios.md @@ -0,0 +1,16 @@ +```text +Set the layout column and row ratios for the focused workspace + +Usage: layout-ratios [OPTIONS] + +Options: + -c, --columns ... + Column width ratios (space-separated values between 0.1 and 0.9) + + -r, --rows ... + Row height ratios (space-separated values between 0.1 and 0.9) + + -h, --help + Print help + +``` diff --git a/docs/cli/scrolling-layout-columns.md b/docs/cli/scrolling-layout-columns.md new file mode 100644 index 00000000..a27649d5 --- /dev/null +++ b/docs/cli/scrolling-layout-columns.md @@ -0,0 +1,14 @@ +```text +Set the number of visible columns for the Scrolling layout on the focused workspace + +Usage: scrolling-layout-columns + +Arguments: + + Desired number of visible columns + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 5aa3d1d6..b3f0fefb 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -271,6 +271,20 @@ flipped layout goes to the tile on the left. `ToggleTiling` turns the workspace' and on ([`Workspace::tile`]): with it off, [`Workspace::update`] moves no window, the workspace still takes the windows that open into containers, and they are tiled when it is turned on. +`LayoutRatios` and `ScrollingLayoutColumns` set the focused workspace's [`LayoutOptions`] +([`Workspace::layout_options`]): the share of the work area its first columns and rows take, and +the number of columns of the scrolling layout in view. The layout calculates the tiles from +them, and from the tiles it calculated last ([`Workspace::latest_layout`]), which the scrolling +layout scrolls from. + +The scrolling layout is a strip of columns that runs past the edges of the work area. Its tiles +are the only ones [`Workspace::update`] does not clamp to the work area, so the windows of the +columns out of view are off the screen; a window whose tile is out of view while part of it is +in view is centered in the work area first. A `FocusChange` tiles a scrolling workspace after the +focused container has changed, which scrolls the strip to it. KWin keeps part of a window it +resizes on an output, so the bridge asks again for the position of a window KWin pulled back +within a second of the command, three times at most ([`bridge.js`]'s `settle`). + `PreselectDirection` reserves the index on one side of the focused container for the next window ([`WindowManager::preselect_container_in_direction`]). The workspace inserts an empty container there ([`Container::preselect`]), which [`Workspace::update`] keeps and the layout @@ -411,6 +425,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A socket left behind by a daemon that did not stop cleanly does not keep the next one from starting | framework path: [`WindowManager::new`] removes the file before it binds | `a_socket_file_left_behind_is_replaced` | none | | A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | | A container moved onto a locked index is locked in its place, and the lock leaves the container that moved away | framework path: [`Workspace::swap_containers`] swaps through `LockableSequence`, which keeps the lock with the index | `test_swap_respecting_locks_various_cases`, `a_lock_stays_with_its_index_when_a_window_is_moved_onto_it` | `containers_mut()` is the `VecDeque` itself | +| A window komorebi puts off the screen stays there | framework path: the bridge asks again for the position of a window KWin pulled back after a `geo` command, for a second, three times at most | `a window KWin pulls back from where it was asked to be is asked for the position again`, `a window that cannot go where it was asked is asked again three times at most`, `vm-scrolling` | a window that cannot go where it was asked is left where KWin put it | | A workspace whose tiling is off moves no window | framework path: [`Workspace::update`] returns before the layout when [`Workspace::tile`] is false | `with_tiling_off_no_window_is_moved_until_it_is_back_on` | none | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | none | @@ -523,7 +538,12 @@ A window is shown, and ends up on a tile: - [`komorebi/tests/focus.rs`](../../komorebi/tests/focus.rs), [`komorebi/tests/moving.rs`](../../komorebi/tests/moving.rs) and [`komorebi/tests/layouts.rs`](../../komorebi/tests/layouts.rs): the focus, move and layout - commands against the fake. + commands against the fake; + [`komorebi/tests/layout_options.rs`](../../komorebi/tests/layout_options.rs) and + [`komorebi/tests/scrolling.rs`](../../komorebi/tests/scrolling.rs), the layout options and the + scrolling layout. +- [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling + strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, and every `komorebic` command, against a real KWin with two outputs. - [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; @@ -558,6 +578,9 @@ A window is shown, and ends up on a tile: [`WindowManager::move_container_in_cycle_direction`]: ../../komorebi/src/window_manager.rs [`Workspace::swap_containers`]: ../../komorebi/src/workspace.rs [`Workspace::layout_flip`]: ../../komorebi/src/workspace.rs +[`Workspace::layout_options`]: ../../komorebi/src/workspace.rs +[`Workspace::latest_layout`]: ../../komorebi/src/workspace.rs +[`LayoutOptions`]: ../../komorebi/src/core/mod.rs [`Workspace::tile`]: ../../komorebi/src/workspace.rs [`Layout`]: ../../komorebi/src/core/mod.rs [`Container::preselect`]: ../../komorebi/src/container.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 7ee69a41..cc625c47 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -210,3 +210,16 @@ So that the tests exercise the module. Every VM suite boots a machine that impor the module's read-only `execStart`, and the session node runs the module's unit itself. A change to the module that breaks how komorebi is installed or started fails the VM suites, and not only `nixos-module-eval`. + +## Why does the bridge ask KWin twice for the position of a window? + +KWin moves a window anywhere it is asked to, but when it resizes a window it keeps 100 pixels of +it on an output, and it does so once the client has drawn at the new size, which is after the +bridge has set the frame. The scrolling layout moves the windows of the columns out of view off +the screen and resizes them in the same command, and a terminal that rounds its size to its +cells is resized again by its client, so KWin pulls both back onto the screen. By then, setting +the position alone is a plain move, which KWin honors. The bridge remembers where it was asked +to put a window for a second, and sets the position again when the window's frame changes to +another one in that time ([PLATFORM.md](PLATFORM.md#how-clients-answer-a-frame)). Three tries +at most keep it from chasing a window that cannot go where it was asked, such as a fullscreen +one. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 34773adb..2948f47a 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -239,6 +239,16 @@ asked for. komorebi does not ask again when a client keeps to a size of its own: manager reads the frame the window has from the table, and a window larger than its tile covers part of its neighbor's. +KWin moves a window anywhere it is asked to, off the screen too, but when it *resizes* a window +it keeps 100 pixels of it on an output, and it does that once the client has drawn at the new +size. A window that is moved off the screen and resized at once, as the scrolling layout does +with the columns out of view, is pulled back onto the screen a moment later; so is one whose +client rounds the size, as `foot` does. The bridge therefore remembers the position it was asked +for, for a second, and when the window's frame changes to another position in that time, asks +for the position again, which is a plain move. It tries three times at most, so a window that +cannot go where it was asked is left alone. The VM test `vm-scrolling` checks that the columns +out of view stay where komorebi put them. + ## How long a retile takes Measured by the VM test `vm-latency` at time of writing (2026-10-27), in a headless KWin 6.8.1 diff --git a/docs/usage/layouts.md b/docs/usage/layouts.md index 1d01b011..52dc5140 100644 --- a/docs/usage/layouts.md +++ b/docs/usage/layouts.md @@ -39,6 +39,42 @@ right main vertical stack. [`komorebic query focused-workspace-layout`](../cli/query.md) prints the layout of the focused workspace. +## Ratios + +[`komorebic layout-ratios`](../cli/layout-ratios.md) sets the share of the work area the first +columns (`--columns`) and the first rows (`--rows`) of the focused workspace's layout take, as +fractions: `--columns 0.6` gives the first column 60% of the width, and the columns after it +share the rest. + +```sh +komorebic layout-ratios --columns 0.6 +komorebic layout-ratios --columns 0.5 0.3 --rows 0.7 +``` + +Each takes five ratios at most, each kept between 0.1 and 0.9, and the ratios after the one that +would make them add up to 1 are dropped, so that there is always room for another column or row. +The ratios stay with the workspace when its layout changes. Without `--columns` or `--rows`, +`layout-ratios` changes nothing. + +## The scrolling layout + +The scrolling layout puts every container in a column of its own, the columns side by side in a +strip that runs past the edges of the monitor. The windows of the columns out of view are off +the screen, and KWin leaves them there. When a window of the workspace gets the focus, the strip +scrolls so that its column is in view, so `komorebic focus left` and `focus right` walk along +it. + +[`komorebic scrolling-layout-columns`](../cli/scrolling-layout-columns.md) sets how many columns +are in view at once on the focused workspace: + +```sh +komorebic change-layout scrolling +komorebic scrolling-layout-columns 2 +``` + +Off the screen to the right of one monitor is on the next monitor over, if there is one, so the +columns out of view can show on it. + ## Flipping the layout [`komorebic flip-layout`](../cli/flip-layout.md) mirrors the tiles of the focused workspace: diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 0c08554f..48b1c403 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -16,6 +16,7 @@ use clap::ValueEnum; use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; +use std::num::NonZeroUsize; use std::str::FromStr; use strum::Display; use strum::EnumString; @@ -346,6 +347,8 @@ pub enum SocketMessage { // Current Workspace Commands ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), + ScrollingLayoutColumns(NonZeroUsize), + LayoutRatios(Option>, Option>), // ChangeLayoutCustom(#[serde_as(as = "ResolvedPathBuf")] PathBuf), FlipLayout(Axis), // Monitor and Workspace Commands diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index 37a64286..2c4cab02 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -86,6 +86,18 @@ var seq = 0; /** @type {Record} */ var known = {}; +// Where the daemon last asked a window to be, for a moment after it asked. KWin honors a plain +// move to anywhere, but when a window is *resized* it keeps 100px of it on an output, so a window +// that komorebi puts off screen (the scrolling layout does) and resizes in the same breath, or +// whose client rounds the size (a terminal snapping to its cells), is pulled back onto the screen +// once the client has committed the new size. By then asking again for the position is a plain +// move. (The first geometry change, to the requested rect, comes before the client has answered, +// so a match does not end the watch; only the clock does.) +/** @type {Record} */ +var want = {}; +var WANT_RETRIES = 3; +var WANT_MS = 1000; + /** * @template {BridgeEvent["type"]} T * @param {T} type @@ -210,6 +222,29 @@ function findWindow(id) { return null; } +// A window has moved or been resized; if it is not where komorebi asked, ask again for the +// position alone (see `want`). A few tries at most, so a window that cannot go where it was asked +// (a fullscreen one, say) is left alone rather than chased. +/** + * @param {KWinWindow} w + * @param {string} id + */ +function settle(w, id) { + var t = want[id]; + if (!t || w.move || w.resize) { + return; + } + if (Date.now() > t.until || t.tries >= WANT_RETRIES) { + delete want[id]; + return; + } + var g = w.frameGeometry; + if (Math.round(g.x) !== t.x || Math.round(g.y) !== t.y) { + t.tries++; + w.frameGeometry = { x: t.x, y: t.y, width: g.width, height: g.height }; + } +} + // ---- hooks --------------------------------------------------------------------------------- /** @@ -227,6 +262,7 @@ function track(w, announce) { } w.frameGeometryChanged.connect(function (old) { emit("geometry", { id: id, geo: rect(w.frameGeometry) }); + settle(w, id); }); w.minimizedChanged.connect(function () { emit("minimized", { id: id, v: !!w.minimized }); @@ -239,6 +275,7 @@ workspace.windowAdded.connect(function (w) { workspace.windowRemoved.connect(function (w) { var id = wid(w); delete known[id]; + delete want[id]; emit("removed", { id: id }); }); /** @type {string | null} */ @@ -292,6 +329,7 @@ function applyOne(c) { switch (c.op) { case "geo": // a plain object converts to QRectF; there is no `Qt` global in kwin scripts + want[c.id] = { x: c.x, y: c.y, tries: 0, until: Date.now() + WANT_MS }; w.frameGeometry = { x: c.x, y: c.y, width: c.w, height: c.h }; break; case "min": diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index 8bbe61b8..2d51ddae 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -58,8 +58,15 @@ function geometry(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, and `closeWindow` closes it -// once it is in a KWin. -function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100), ...rest }) { +// once it is in a KWin. `place` is where KWin puts the window when it is asked for a frame: where +// it was asked, unless a test says otherwise. +function window({ + id, + minimized = false, + frameGeometry = geometry(0, 0, 100, 100), + place = (g) => g, + ...rest +}) { const w = { internalId: { toString: () => id }, pid: 0, @@ -74,6 +81,8 @@ function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100 fullScreen: false, maximizeMode: 0, minSize: { width: 0, height: 0 }, + move: false, + resize: false, desktops: [], frameGeometryChanged: new Signal(), minimizedChanged: new Signal(), @@ -93,7 +102,7 @@ function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100 get: () => state.frameGeometry, set: (g) => { const old = state.frameGeometry; - state.frameGeometry = geometry(g.x, g.y, g.width, g.height); + state.frameGeometry = place(geometry(g.x, g.y, g.width, g.height)); w.frameGeometryChanged.emit(old); }, }, @@ -458,3 +467,61 @@ test("a command KWin throws on is printed and given back as failed", () => { assert.match(k.printed[0], /^komorebi bridge: Error: the window is being destroyed in /); assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 5, cmds: [close], seq: 2 }); }); + +// KWin keeps 100 pixels of a window that it resizes on an output +function keepOnScreen(g) { + return geometry(Math.max(g.x, 100 - g.width), g.y, g.width, g.height); +} + +test("a window KWin pulls back from where it was asked to be is asked for the position again", () => { + let pulled = false; + const w = window({ + id: "{w}", + // the first time only, as when the client commits a new size + place: (g) => (pulled ? g : ((pulled = true), keepOnScreen(g))), + }); + const k = kwin({ windows: [w] }); + + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: -900, y: 0, w: 800, h: 600 }] }]); + + assert.deepStrictEqual(w.frameGeometry, geometry(-900, 0, 800, 600)); + assert.deepStrictEqual( + k.events().slice(1).map((e) => e.geo), + [ + { x: -700, y: 0, w: 800, h: 600 }, + { x: -900, y: 0, w: 800, h: 600 }, + ], + ); +}); + +test("a window that cannot go where it was asked is asked again three times at most", () => { + let frames = 0; + const w = window({ id: "{w}", place: (g) => (frames++, keepOnScreen(g)) }); + const k = kwin({ windows: [w] }); + + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: -900, y: 0, w: 800, h: 600 }] }]); + + assert.equal(frames, 4, "the command and three tries"); + assert.deepStrictEqual(w.frameGeometry, geometry(-700, 0, 800, 600)); +}); + +test("a window is asked for its position again for a second after the command, and no longer", () => { + const w = window({ id: "{w}" }); + const k = kwin({ windows: [w] }); + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: -900, y: 0, w: 800, h: 600 }] }]); + + k.clock.now += 1001; + w.frameGeometry = geometry(-700, 0, 800, 600); + + assert.deepStrictEqual(w.frameGeometry, geometry(-700, 0, 800, 600)); +}); + +test("a window the user is moving or resizing is not asked for its position again", () => { + const w = window({ id: "{w}", move: true }); + const k = kwin({ windows: [w] }); + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: -900, y: 0, w: 800, h: 600 }] }]); + + w.frameGeometry = geometry(-700, 0, 800, 600); + + assert.deepStrictEqual(w.frameGeometry, geometry(-700, 0, 800, 600)); +}); diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts index 85c01a50..4b1e077e 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -78,6 +78,10 @@ interface KWinWindow { /** Set to a plain `{x, y, width, height}`: a script has no `Qt` global to make a `QRectF`. */ frameGeometry: QRectF; readonly minSize: QSizeF; + /** True while the user moves the window with the pointer. */ + readonly move: boolean; + /** True while the user resizes the window with the pointer. */ + readonly resize: boolean; readonly desktops: VirtualDesktop[]; readonly frameGeometryChanged: Signal<[oldGeometry: QRectF]>; readonly minimizedChanged: Signal; diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 7c21c0d3..3713f743 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -24,6 +24,9 @@ //! layout, or mirror it, and **ToggleTiling** turns its tiling off and on //! ([`WindowManager::change_workspace_layout_default`], [`WindowManager::cycle_layout`], //! [`WindowManager::flip_layout`], [`WindowManager::toggle_tiling`]). +//! - **ScrollingLayoutColumns** sets how many columns the scrolling layout shows on the focused +//! workspace, and **LayoutRatios** the share of the work area its first columns and rows take, +//! and both tile the workspace again. //! - **PreselectDirection** reserves the place on one side of the focused container for the next //! window ([`WindowManager::preselect_container_in_direction`]), unless a place is reserved //! already, and **CancelPreselect** gives the reserved place up. @@ -43,6 +46,8 @@ use crate::NotificationEvent; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; use crate::core::Layout; +use crate::core::LayoutOptions; +use crate::core::ScrollingLayoutOptions; use crate::core::SocketMessage; use crate::core::StateQuery; use crate::monitor::MonitorInformation; @@ -248,6 +253,54 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::ScrollingLayoutColumns(count) => { + let focused_workspace = self.focused_workspace_mut()?; + + let options = match focused_workspace.layout_options { + Some(mut opts) => { + if let Some(scrolling) = &mut opts.scrolling { + scrolling.columns = count.into(); + } + + opts + } + None => LayoutOptions { + scrolling: Some(ScrollingLayoutOptions { + columns: count.into(), + center_focused_column: Default::default(), + }), + grid: None, + column_ratios: None, + row_ratios: None, + }, + }; + + focused_workspace.layout_options = Some(options); + self.update_focused_workspace(false, false)?; + } + SocketMessage::LayoutRatios(ref columns, ref rows) => { + use crate::core::validate_ratios; + + let focused_workspace = self.focused_workspace_mut()?; + + let mut options = focused_workspace.layout_options.unwrap_or(LayoutOptions { + scrolling: None, + grid: None, + column_ratios: None, + row_ratios: None, + }); + + if let Some(cols) = columns { + options.column_ratios = Some(validate_ratios(cols)); + } + + if let Some(rws) = rows { + options.row_ratios = Some(validate_ratios(rws)); + } + + focused_workspace.layout_options = Some(options); + self.update_focused_workspace(false, false)?; + } SocketMessage::MouseFollowsFocus(enable) => { self.mouse_follows_focus = enable; } diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index c497b131..d8719f69 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -8,7 +8,8 @@ //! - **Destroy**: the window is taken out of whichever workspace has it, and if that is the one in //! front it is tiled again. //! - **FocusChange**: the workspace is tiled again and the container of the window that has the -//! focus becomes the focused container. +//! focus becomes the focused container. In the scrolling layout the workspace is tiled after +//! that instead, so that the strip scrolls to the window that has the focus. //! - **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. //! @@ -23,6 +24,8 @@ use crate::Notification; use crate::NotificationEvent; use crate::backend::backend; +use crate::core::DefaultLayout; +use crate::core::Layout; use crate::notify_subscribers; use crate::state::State; use crate::window_manager::WindowManager; @@ -118,7 +121,11 @@ impl WindowManager { // don't want to trigger the full workspace updates when there are no managed // containers - if !self.focused_workspace()?.containers().is_empty() { + if !matches!( + self.focused_workspace()?.layout, + Layout::Default(DefaultLayout::Scrolling) + ) && !self.focused_workspace()?.containers().is_empty() + { self.update_focused_workspace(self.mouse_follows_focus, false)?; } @@ -130,6 +137,14 @@ impl WindowManager { if is_on_current_workspace { workspace.focus_container_by_window(window_id)?; } + + if matches!( + self.focused_workspace()?.layout, + Layout::Default(DefaultLayout::Scrolling) + ) && !self.focused_workspace()?.containers().is_empty() + { + self.update_focused_workspace(self.mouse_follows_focus, false)?; + } } WindowManagerEvent::Show(_, _) => { let mut create = true; diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 68e2d91d..65ebf6ad 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -80,9 +80,11 @@ impl From<&WindowManager> for State { .map(|workspace| Workspace { containers: workspace.containers.clone(), layout: workspace.layout.clone(), + layout_options: workspace.layout_options, layout_flip: workspace.layout_flip, workspace_padding: workspace.workspace_padding, container_padding: workspace.container_padding, + latest_layout: workspace.latest_layout.clone(), tile: workspace.tile, globals: workspace.globals, preselected_container_idx: None, diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 838e3230..76e42f74 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -191,6 +191,28 @@ impl Window { backend().unminimize(self.id) } + /// Moves the window to the middle of `work_area`, keeping its size + /// + /// # Errors + /// + /// The backend does not know the window, or refuses to move it. + pub fn center(&mut self, work_area: &Rect) -> eyre::Result<()> { + let (target_width, target_height) = { + let current_rect = self.rect()?; + (current_rect.right, current_rect.bottom) + }; + + let x = work_area.left + ((work_area.right - target_width) / 2); + let y = work_area.top + ((work_area.bottom - target_height) / 2); + + self.set_position(&Rect { + left: x, + top: y, + right: target_width, + bottom: target_height, + }) + } + /// Whether the window is one komorebi should tile: a window that is still alive and that the /// compositor considers a normal application window, as opposed to a dialog, a splash screen, /// a utility window or a dock ([`WindowInfo::normal`](crate::backend::WindowInfo::normal)). diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 92e403a0..689e8765 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -10,6 +10,7 @@ use crate::core::Axis; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::LayoutOptions; use crate::core::OperationDirection; use crate::core::Rect; use crate::lockable_sequence::LockableSequence; @@ -27,9 +28,11 @@ use std::num::NonZeroUsize; pub struct Workspace { pub containers: Ring, pub layout: Layout, + pub layout_options: Option, pub layout_flip: Option, pub workspace_padding: Option, pub container_padding: Option, + pub latest_layout: Vec, pub tile: bool, #[serde(skip)] pub globals: WorkspaceGlobals, @@ -46,7 +49,9 @@ impl Default for Workspace { workspace_padding: None, container_padding: None, layout: Layout::Default(DefaultLayout::BSP), + latest_layout: vec![], layout_flip: None, + layout_options: None, globals: Default::default(), tile: true, preselected_container_idx: None, @@ -64,6 +69,29 @@ pub struct WorkspaceGlobals { pub work_area_offset: Option, } +/// `komorebi_layouts::Rect::percentage_within_horizontal_bounds`, which that crate compiles only +/// with its `darwin` feature +trait HorizontalBounds { + /// Returns how much of `other`'s width is within this rectangle's left and right edges, in + /// percent + fn percentage_within_horizontal_bounds(&self, other: &Rect) -> f64; +} + +impl HorizontalBounds for Rect { + fn percentage_within_horizontal_bounds(&self, other: &Rect) -> f64 { + let overlap_left = self.left.max(other.left); + let overlap_right = (self.left + self.right).min(other.left + other.right); + + let overlap_width = overlap_right - overlap_left; + + if overlap_width <= 0 { + 0.0 + } else { + (overlap_width as f64) / (other.right as f64) * 100.0 + } + } +} + impl Workspace { #[tracing::instrument(skip(self))] pub fn focus_container(&mut self, idx: usize) { @@ -103,7 +131,7 @@ impl Workspace { self.layout_flip, self.focused_container_idx(), len, - None, + self.layout_options, ) } @@ -323,8 +351,13 @@ impl Workspace { /// /// Containers that have no windows left are dropped first, except the one a preselection /// reserved, and so is a window that is in more than one container. A tile is clamped to the - /// work area, so it cannot bleed onto a neighboring monitor. A workspace whose tiling is off - /// ([`Workspace::tile`] is false) moves no window. + /// work area, so it cannot bleed onto a neighboring monitor, except in the scrolling layout, + /// whose strip runs past the edges of the work area. A window whose tile is out of view while + /// part of the window is in view is first centered in the work area. A workspace whose tiling + /// is off ([`Workspace::tile`] is false) moves no window. + /// + /// The tiles are kept in [`Workspace::latest_layout`], which the scrolling layout scrolls + /// from. pub fn update(&mut self) -> eyre::Result<()> { // make sure we are never holding on to empty containers self.prune_duplicate_windows()?; @@ -376,47 +409,68 @@ impl Workspace { self.layout_flip, &[], self.focused_container_idx(), - None, - &[], + self.layout_options, + &self.latest_layout, ); + let is_scrolling = + matches!(self.layout, Layout::Default(DefaultLayout::Scrolling)); + let containers = self.containers_mut(); for (i, container) in containers.iter_mut().enumerate() { if let Some(layout) = layouts.get_mut(i) { - // Every tile is clamped to the work area so it cannot bleed onto an - // adjacent monitor. + // The scrolling layout is a strip that is meant to run past the edges of + // the work area, with the windows outside the viewport sitting off screen + // (KWin does not constrain where a window is put). Everything else is + // clamped to the work area so it cannot bleed onto an adjacent monitor. + if !is_scrolling { + // horizontal + if layout.left < adjusted_work_area.left { + layout.right -= adjusted_work_area.left - layout.left; + layout.left = adjusted_work_area.left; + } + let max_right_edge = + adjusted_work_area.left + adjusted_work_area.right; + let current_right_edge = layout.left + layout.right; + if current_right_edge > max_right_edge { + layout.right = max_right_edge - layout.left; + } - // horizontal - if layout.left < adjusted_work_area.left { - layout.right -= adjusted_work_area.left - layout.left; - layout.left = adjusted_work_area.left; - } - let max_right_edge = adjusted_work_area.left + adjusted_work_area.right; - let current_right_edge = layout.left + layout.right; - if current_right_edge > max_right_edge { - layout.right = max_right_edge - layout.left; - } - - // vertical - if layout.top < adjusted_work_area.top { - layout.bottom -= adjusted_work_area.top - layout.top; - layout.top = adjusted_work_area.top; - } - let max_bottom_edge = - adjusted_work_area.top + adjusted_work_area.bottom; - let current_bottom_edge = layout.top + layout.bottom; - if current_bottom_edge > max_bottom_edge { - layout.bottom = max_bottom_edge - layout.top; + // vertical + if layout.top < adjusted_work_area.top { + layout.bottom -= adjusted_work_area.top - layout.top; + layout.top = adjusted_work_area.top; + } + let max_bottom_edge = + adjusted_work_area.top + adjusted_work_area.bottom; + let current_bottom_edge = layout.top + layout.bottom; + if current_bottom_edge > max_bottom_edge { + layout.bottom = max_bottom_edge - layout.top; + } } for window in container.windows_mut() { - if let Err(error) = window.set_position(layout) { + let current_rect = window.rect().unwrap_or_default(); + let current_percentage = + work_area.percentage_within_horizontal_bounds(¤t_rect); + let proposed_percentage = + work_area.percentage_within_horizontal_bounds(layout); + + let percentage_override = proposed_percentage == 0.0 + && current_percentage > 0.1 + && current_percentage < 100.0; + + if percentage_override { + window.center(&work_area)?; + } else if let Err(error) = window.set_position(layout) { tracing::warn!("failed to set window position: {error}") } } } } + + self.latest_layout = layouts; } Ok(()) })(); diff --git a/komorebi/tests/layout_options.rs b/komorebi/tests/layout_options.rs new file mode 100644 index 00000000..1e5626fd --- /dev/null +++ b/komorebi/tests/layout_options.rs @@ -0,0 +1,206 @@ +//! The options of the layouts, `layout-ratios` and `scrolling-layout-columns`, and the scrolling +//! layout's strip, against an in-memory desktop: the messages go in through +//! [`WindowManager::process_command`], and what comes out is where the backend is asked to put +//! each window. +//! +//! Window ids are in the 22_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::DefaultLayout; +use komorebi::core::OperationDirection; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::num::NonZeroUsize; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel) +fn desktop() -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmo-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +fn open(fake: &Arc, wm: &mut WindowManager, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn columns(count: usize) -> SocketMessage { + SocketMessage::ScrollingLayoutColumns(NonZeroUsize::new(count).unwrap()) +} + +fn in_view(rect: Rect) -> bool { + rect.left >= 0 && rect.left + rect.right <= 1920 +} + +fn out_of_view(rect: Rect) -> bool { + rect.left >= 1920 || rect.left + rect.right <= 0 +} + +#[test] +fn layout_ratios_give_the_first_column_its_share_of_the_work_area() { + let (fake, mut wm) = desktop(); + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Columns), + ); + open(&fake, &mut wm, 22_001); + open(&fake, &mut wm, 22_002); + let even = fake.rect_of(22_001).unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::LayoutRatios(Some(vec![0.75]), None), + ); + + let (first, second) = (fake.rect_of(22_001).unwrap(), fake.rect_of(22_002).unwrap()); + assert!(first.right > even.right, "{first:?} is wider than {even:?}"); + assert!( + first.right > 2 * second.right, + "three quarters against one: {first:?} {second:?}" + ); + assert_eq!( + wm.focused_workspace() + .unwrap() + .layout_options + .and_then(|options| options.column_ratios) + .and_then(|ratios| ratios[0]), + Some(0.75) + ); +} + +#[test] +fn the_scrolling_strip_runs_past_the_edge_of_the_work_area_with_the_focused_window_in_view() { + let (fake, mut wm) = desktop(); + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Scrolling), + ); + send(&fake, &mut wm, columns(2)); + for id in 22_011..=22_015 { + open(&fake, &mut wm, id); + } + + let rects: Vec = (22_011..=22_015) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert!( + in_view(rects[4]), + "the focused window is in view: {rects:?}" + ); + assert!( + in_view(rects[3]), + "two columns: so is the one before it: {rects:?}" + ); + for rect in &rects[..3] { + assert!( + out_of_view(*rect), + "the first three are scrolled out of view: {rects:?}" + ); + } + // not clamped: every column is as wide as the others, at the same distance from the next + let pitch = rects[4].left - rects[3].left; + assert_eq!(rects[0].left, rects[3].left - 3 * pitch, "{rects:?}"); + assert!( + rects.iter().all(|rect| rect.right == rects[0].right), + "{rects:?}" + ); +} + +#[test] +fn the_scrolling_strip_scrolls_to_the_window_that_has_the_focus() { + let (fake, mut wm) = desktop(); + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Scrolling), + ); + send(&fake, &mut wm, columns(2)); + for id in 22_021..=22_025 { + open(&fake, &mut wm, id); + } + + for id in (22_021..=22_024).rev() { + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Left), + ); + // the compositor reports the focus it was asked to give, which is what scrolls the strip + with_backend(fake.clone(), || wm.process_event(activated(id))).unwrap(); + } + + assert_eq!(wm.focused_window().unwrap().id, 22_021); + assert!(in_view(fake.rect_of(22_021).unwrap())); + assert!(out_of_view(fake.rect_of(22_025).unwrap())); +} + +#[test] +fn scrolling_layout_columns_sets_how_many_columns_are_in_view() { + let (fake, mut wm) = desktop(); + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Scrolling), + ); + for id in 22_031..=22_034 { + open(&fake, &mut wm, id); + } + + send(&fake, &mut wm, columns(4)); + let four: Vec = (22_031..=22_034) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert!(four.iter().all(|rect| in_view(*rect)), "{four:?}"); + + send(&fake, &mut wm, columns(1)); + let one: Vec = (22_031..=22_034) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert_eq!( + one.iter().filter(|rect| in_view(**rect)).count(), + 1, + "{one:?}" + ); +} diff --git a/komorebi/tests/scrolling.rs b/komorebi/tests/scrolling.rs new file mode 100644 index 00000000..685d111b --- /dev/null +++ b/komorebi/tests/scrolling.rs @@ -0,0 +1,119 @@ +//! The scrolling layout, against an in-memory desktop. +//! +//! KWin lets a window sit anywhere, so the columns of a strip that are past the edge of a monitor +//! can be on the next monitor over. Those windows still belong to the monitor whose strip they are +//! in. +//! +//! Window ids are in the 10_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::DefaultLayout; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn desktop_on(fake: FakeBackend) -> (Arc, WindowManager) { + let fake = Arc::new(fake); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmb-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +fn open(fake: &FakeBackend, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); +} + +#[test] +fn a_scrolling_strip_on_the_next_monitor_over_does_not_take_focus_with_it() { + // KWin lets a window sit anywhere, so the part of the strip past the right edge of the first + // monitor is on the second one. Those windows still belong to the first. + let fake = FakeBackend::with_one_monitor(); + fake.add_monitor( + 2, + "Virtual-1", + Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1080, + }, + Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1050, + }, + ); + let (fake, mut wm) = desktop_on(fake); + for id in 10_201..=10_205 { + open(&fake, id); + } + + with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::ChangeLayout(DefaultLayout::Scrolling), + Vec::new(), + )?; + wm.process_command( + SocketMessage::ScrollingLayoutColumns(std::num::NonZeroUsize::new(2).unwrap()), + Vec::new(), + )?; + for id in 10_201..=10_205 { + wm.process_event(added(id))?; + } + // back to the start of the strip, which leaves the later columns past the monitor's edge + for _ in 0..4 { + wm.process_command( + SocketMessage::FocusWindow(komorebi::core::OperationDirection::Left), + Vec::new(), + )?; + } + + // (the compositor's focus event is what scrolls the strip, and the fake sends none) + wm.update_focused_workspace(false, false)?; + + let past_the_edge = fake.rect_of(10_204).unwrap(); + assert!( + past_the_edge.left >= 1920, + "the test needs a window on the second monitor, got {past_the_edge:?}" + ); + + wm.process_event(WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(10_204), + )) + }) + .unwrap(); + + assert_eq!( + wm.focused_monitor_idx(), + 0, + "focus moved to the monitor the strip spills onto" + ); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index c1c970b9..5f6eb776 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -9,8 +9,9 @@ //! `mouse-follows-focus` and `toggle-mouse-follows-focus` set whether the pointer goes with it. //! `move` and `cycle-move` move the focused window to another tile. `change-layout`, //! `cycle-layout` and `flip-layout` change the layout of the focused workspace, `toggle-tiling` -//! turns its tiling off and on, and `preselect-direction` and `cancel-preselect` reserve the -//! place of the next window and give it up. +//! turns its tiling off and on, `scrolling-layout-columns` and `layout-ratios` tune the layouts, +//! and `preselect-direction` and `cancel-preselect` reserve the place of the next window and give +//! it up. //! //! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens //! on a socket in the daemon's data directory, to which the daemon sends a notification after each @@ -38,6 +39,7 @@ use komorebi_client::send_query; use std::fs::File; use std::io::BufRead; use std::io::Write; +use std::num::NonZeroUsize; use std::path::PathBuf; use std::process::Command; use std::process::Stdio; @@ -111,6 +113,22 @@ struct Start { #[derive(Parser)] struct Stop {} +#[derive(Parser)] +struct ScrollingLayoutColumns { + /// Desired number of visible columns + count: NonZeroUsize, +} + +#[derive(Parser)] +struct LayoutRatios { + /// Column width ratios (space-separated values between 0.1 and 0.9) + #[clap(short, long, num_args = 1..)] + columns: Option>, + /// Row height ratios (space-separated values between 0.1 and 0.9) + #[clap(short, long, num_args = 1..)] + rows: Option>, +} + #[derive(Parser)] struct Docgen { /// Output directory for generated documentation files @@ -192,6 +210,11 @@ enum SubCommand { /// Cycle between available layouts #[clap(arg_required_else_help = true)] CycleLayout(CycleLayout), + /// Set the number of visible columns for the Scrolling layout on the focused workspace + #[clap(arg_required_else_help = true)] + ScrollingLayoutColumns(ScrollingLayoutColumns), + /// Set the layout column and row ratios for the focused workspace + LayoutRatios(LayoutRatios), // /// Load a custom layout from file for the focused workspace // #[clap(hide = true)] // #[clap(arg_required_else_help = true)] @@ -367,6 +390,18 @@ fn main() -> eyre::Result<()> { SubCommand::MonitorInformation => { print_query(&SocketMessage::MonitorInformation); } + SubCommand::ScrollingLayoutColumns(args) => { + send_message(&SocketMessage::ScrollingLayoutColumns(args.count))?; + } + SubCommand::LayoutRatios(args) => { + if args.columns.is_none() && args.rows.is_none() { + println!( + "No ratios provided, nothing to change. Use --columns or --rows to specify ratios." + ); + } else { + send_message(&SocketMessage::LayoutRatios(args.columns, args.rows))?; + } + } SubCommand::ToggleMouseFollowsFocus => { send_message(&SocketMessage::ToggleMouseFollowsFocus)?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index b052d92a..63882b84 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -216,6 +216,44 @@ fn the_layout_subcommands_send_the_layout_axis_or_direction_they_are_given() { sends(&["cancel-preselect"], r#"{"type":"CancelPreselect"}"#); } +#[test] +fn scrolling_layout_columns_and_layout_ratios_send_what_they_are_given() { + sends( + &["scrolling-layout-columns", "3"], + r#"{"type":"ScrollingLayoutColumns","content":3}"#, + ); + sends( + &["layout-ratios", "--columns", "0.6", "0.25", "--rows", "0.5"], + r#"{"type":"LayoutRatios","content":[[0.6,0.25],[0.5]]}"#, + ); + sends( + &["layout-ratios", "--rows", "0.3"], + r#"{"type":"LayoutRatios","content":[null,[0.3]]}"#, + ); +} + +#[test] +fn layout_ratios_without_ratios_sends_nothing_and_says_so() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["layout-ratios"]); + + assert!(output.status.success(), "{output:?}"); + assert!( + stdout(&output).starts_with("No ratios provided"), + "{output:?}" + ); +} + +#[test] +fn scrolling_layout_columns_refuses_zero() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["scrolling-layout-columns", "0"]); + + assert!(!output.status.success(), "{output:?}"); +} + #[test] fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { sends( @@ -280,6 +318,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "data-directory.md", "flip-layout.md", "focus.md", + "layout-ratios.md", "log.md", "monitor-information.md", "mouse-follows-focus.md", @@ -287,6 +326,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "preselect-direction.md", "query.md", "retile.md", + "scrolling-layout-columns.md", "start.md", "state.md", "stop.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 2f6eac41..3e33bc8a 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -164,7 +164,9 @@ flip-layout horizontal-and-vertical flip-layout horizontal-and-vertical cycle-layout next cycle-layout previous +layout-ratios --columns 0.6 0.4 change-layout columns +scrolling-layout-columns 2 change-layout bsp preselect-direction left cancel-preselect diff --git a/nix/tests/vm/suites/scrolling/default.nix b/nix/tests/vm/suites/scrolling/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/scrolling/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/scrolling/test.py b/nix/tests/vm/suites/scrolling/test.py new file mode 100644 index 00000000..420463b3 --- /dev/null +++ b/nix/tests/vm/suites/scrolling/test.py @@ -0,0 +1,89 @@ +# The scrolling layout in a real KWin. The strip runs past the edge of the work area, and KWin is +# expected to leave the windows exactly where komorebi puts them, off the screen too: KWin keeps +# part of a window it resizes on an output, and the bridge asks again for the position of a window +# that was pulled back (`settle` in `bridge.js`). `komorebi/tests/layout_options.rs` checks where +# komorebi puts the columns against the fake; this checks that KWin keeps them there, and that the +# strip scrolls with the focus that `komorebic focus` moves. +from komorebi_vm import Checks, Kde, Rect + +W, H = 1920, 1080 + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) + + +def n(i: int) -> Rect: + return kde.rect(kde.wid(f"win{i}")) + + +def in_view(r: Rect) -> bool: + return r.x >= 0 and r.x + r.w <= W + + +def out_of_view(r: Rect) -> bool: + return r.x >= W or r.x + r.w <= 0 + + +def focused_monitor() -> int: + return kde.state()["monitors"]["focused"] + + +def agree(title: str) -> bool: + return kde.title(kde.active()) == title and kde.focused_title() == title + + +print("== five windows in two columns") +kde.start_komorebi() +kde.wait_for(lambda: kde.run("komorebic monitor-information")[0] == 0, timeout=30) +kde.komorebic("change-layout", "scrolling") +kde.komorebic("scrolling-layout-columns", "2") +for i in range(1, 6): + kde.spawn(f"foot -T win{i} sleep 3000") + kde.wait_for(lambda i=i: kde.wid(f"win{i}") != "", timeout=30) +checks.check("komorebi manages all five", kde.wait_for(lambda: kde.managed() == 5, timeout=20)) +checks.check( + "the focused (last) window is in view, and so is the one before it", + kde.wait_for(lambda: in_view(n(5)) and in_view(n(4)), timeout=20), +) +checks.check( + "the first three are scrolled out of view", + kde.wait_for(lambda: all(out_of_view(n(i)) for i in (1, 2, 3)), timeout=20), +) +for i in range(1, 6): + print(f" win{i}: {n(i)}") +# not an absolute x: the paddings move every column +pitch = n(5).x - n(4).x +checks.check( + f"KWin left them where komorebi put them: win1 is three columns left of win4" + f" ({n(1).x} = {n(4).x} - 3 x {pitch}), not pulled back", + kde.wait_for(lambda: n(1).x == n(4).x - 3 * pitch, timeout=10), +) +checks.check("KWin and komorebi agree on the focus", kde.wait_for(lambda: agree("win5"))) + +print("== focus to the far left and back") +for _ in range(4): + kde.komorebic("focus", "left") + kde.wait_for(lambda: kde.title(kde.active()) == kde.focused_title()) +checks.check( + "focusing to the far left scrolls the strip back: win1 in view", + kde.wait_for(lambda: in_view(n(1)), timeout=10), +) +checks.check("... and win5 is past the right edge", kde.wait_for(lambda: out_of_view(n(5)))) +checks.check("... and the focus is win1 on both sides", kde.wait_for(lambda: agree("win1"))) +checks.check("... on the first monitor", focused_monitor() == 0) + +for _ in range(4): + kde.komorebic("focus", "right") + kde.wait_for(lambda: kde.title(kde.active()) == kde.focused_title()) +checks.check("walking right again reaches win5", kde.wait_for(lambda: agree("win5"))) +checks.check("... without the focus having left the first monitor", focused_monitor() == 0) +checks.check("... and win5 is in view", kde.wait_for(lambda: in_view(n(5)), timeout=10)) + +kde.komorebic("stop") +kde.wait_for(lambda: not kde.komorebi_running()) +kde.stop() +checks.finish() From 95eb4d5039986733f1c25a7e6ea35f42fa67d7f6 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 16:22:53 -0700 Subject: [PATCH 022/255] feat(wm): resize from the CLI `komorebic resize-edge left|right|up|down increase|decrease` moves one edge of the focused tile, and `resize-axis` both edges along an axis, by the delta that `resize-delta` sets (50 pixels to start with; komorebi-layouts moves an edge by half of it). The neighbors give up the room. A resize is an adjustment of the container's tile that the workspace keeps, one per container, and that the layout applies whenever it tiles. Before each tiling, the workspace clears the parts its layout cannot apply, such as the height of a column. No tile may end up narrower or shorter than a tenth of the work area, or than it already is: a resize that would make one so is granted as far as it can go, not dropped. `retile` drops the adjustments, and the `RetileWithResizeDimensions` message tiles with them. `save-resize` and `load-resize` write them to a file and read them back, and `quick-save-resize` and `quick-load-resize` do the same with one file in the daemon's temporary directory. The vm-commands sweep gains every resize command, and the saving and loading. --- README.md | 9 +- docs/cli/load-resize.md | 14 + docs/cli/quick-load-resize.md | 10 + docs/cli/quick-save-resize.md | 10 + docs/cli/resize-axis.md | 22 ++ docs/cli/resize-delta.md | 14 + docs/cli/resize-edge.md | 19 ++ docs/cli/save-resize.md | 14 + docs/dev/ARCHITECTURE.md | 21 +- docs/index.md | 5 +- docs/usage/resizing-windows.md | 63 ++++ komorebi-client/src/lib.rs | 4 +- komorebi-client/tests/daemon.rs | 2 +- komorebi/src/core/mod.rs | 10 + komorebi/src/lib.rs | 4 +- komorebi/src/main.rs | 2 +- komorebi/src/process_command.rs | 140 ++++++++- komorebi/src/state.rs | 3 + komorebi/src/window_manager.rs | 197 +++++++++++- komorebi/src/workspace.rs | 427 ++++++++++++++++++++++++++- komorebi/tests/resize.rs | 237 +++++++++++++++ komorebic/src/main.rs | 102 ++++++- komorebic/tests/cli.rs | 37 +++ nix/tests/vm/suites/commands/test.py | 19 ++ 24 files changed, 1351 insertions(+), 34 deletions(-) create mode 100644 docs/cli/load-resize.md create mode 100644 docs/cli/quick-load-resize.md create mode 100644 docs/cli/quick-save-resize.md create mode 100644 docs/cli/resize-axis.md create mode 100644 docs/cli/resize-delta.md create mode 100644 docs/cli/resize-edge.md create mode 100644 docs/cli/save-resize.md create mode 100644 docs/usage/resizing-windows.md create mode 100644 komorebi/tests/resize.rs diff --git a/README.md b/README.md index be1a4b58..6fd7a151 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,8 @@ While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in `$XDG_RUNTIME_DIR/komorebi` (the local data directory when there is no runtime directory): a message can ask for the state of the window manager, ask which monitor, workspace or container has the focus, give the focus to another -window, move the focused window to another tile, change the layout, retile -every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +window, move the focused window to another tile, change the layout, resize a +tile, retile every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, the command line, is how a person sends them. `komorebic start` runs the `komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma session: @@ -137,8 +137,9 @@ one in the layout, or to the next one in the workspace's order, and `move` and `cycle-move` swap the focused container with that one and tile the workspace again. `change-layout`, `cycle-layout` and `flip-layout` tile the workspace in another layout, `layout-ratios` and `scrolling-layout-columns` tune it, -`toggle-tiling` stops it moving windows and starts it again, and -`preselect-direction` reserves a tile for the next window. The scrolling layout +`toggle-tiling` stops it moving windows and starts it again, +`preselect-direction` reserves a tile for the next window, and `resize-edge` +and `resize-axis` move the edges of the focused tile. The scrolling layout is a strip of columns that runs past the edges of the monitor and scrolls to the window that has the focus. diff --git a/docs/cli/load-resize.md b/docs/cli/load-resize.md new file mode 100644 index 00000000..2cd2b591 --- /dev/null +++ b/docs/cli/load-resize.md @@ -0,0 +1,14 @@ +```text +Load the resize layout dimensions from a file + +Usage: load-resize + +Arguments: + + File from which the resize layout dimensions should be loaded + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/quick-load-resize.md b/docs/cli/quick-load-resize.md new file mode 100644 index 00000000..fcec7fe3 --- /dev/null +++ b/docs/cli/quick-load-resize.md @@ -0,0 +1,10 @@ +```text +Load the last quicksaved resize layout dimensions + +Usage: quick-load-resize + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/quick-save-resize.md b/docs/cli/quick-save-resize.md new file mode 100644 index 00000000..f8a8208b --- /dev/null +++ b/docs/cli/quick-save-resize.md @@ -0,0 +1,10 @@ +```text +Quicksave the current resize layout dimensions + +Usage: quick-save-resize + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/resize-axis.md b/docs/cli/resize-axis.md new file mode 100644 index 00000000..cbebabab --- /dev/null +++ b/docs/cli/resize-axis.md @@ -0,0 +1,22 @@ +```text +Resize the focused window or primary column along the specified axis + +Usage: resize-axis + +Arguments: + + Possible values: + - horizontal: Horizontal axis + - vertical: Vertical axis + - horizontal-and-vertical: Both horizontal and vertical axes + + + Possible values: + - increase: Increase + - decrease: Decrease + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/resize-delta.md b/docs/cli/resize-delta.md new file mode 100644 index 00000000..d7337700 --- /dev/null +++ b/docs/cli/resize-delta.md @@ -0,0 +1,14 @@ +```text +Set the resize delta (used by resize-edge and resize-axis) + +Usage: resize-delta + +Arguments: + + The delta of pixels by which to increase or decrease window dimensions when resizing + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/resize-edge.md b/docs/cli/resize-edge.md new file mode 100644 index 00000000..90fb5663 --- /dev/null +++ b/docs/cli/resize-edge.md @@ -0,0 +1,19 @@ +```text +Resize the focused window in the specified direction + +Usage: resize-edge + +Arguments: + + [possible values: left, right, up, down] + + + Possible values: + - increase: Increase + - decrease: Decrease + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/save-resize.md b/docs/cli/save-resize.md new file mode 100644 index 00000000..c63e784e --- /dev/null +++ b/docs/cli/save-resize.md @@ -0,0 +1,14 @@ +```text +Save the current resize layout dimensions to a file + +Usage: save-resize + +Arguments: + + File to which the resize layout dimensions should be saved + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index b3f0fefb..c2c60932 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -27,7 +27,7 @@ its place here. - **Event**: what the compositor reports about a window: it was shown, destroyed, given the focus, minimized or restored ([`WindowManagerEvent`]). - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order - (focus a window, move it, change the layout, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). + (focus a window, move it, change the layout, resize it, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). - **Direction**: where an order goes from the focused container: a side of its tile ([`OperationDirection`]), or the next or the previous container of the workspace ([`CycleDirection`]). @@ -285,6 +285,16 @@ focused container has changed, which scrolls the strip to it. KWin keeps part of resizes on an output, so the bridge asks again for the position of a window KWin pulled back within a second of the command, three times at most ([`bridge.js`]'s `settle`). +`ResizeWindowEdge` and `ResizeWindowAxis` resize the focused container +([`WindowManager::resize_window`]). A resize is an adjustment of the container's tile, kept in +[`Workspace::resize_dimensions`], one per container, which the layout applies when it calculates +the tiles; before every tiling, the workspace clears the parts of each adjustment that its layout +cannot apply, such as the top and the bottom of a column. The adjustment is the one +`komorebi-layouts` gives for the edge and [`WindowManager::resize_delta`], cut down until no tile +would be smaller than a tenth of the work area, or than it is already. The adjustments are kept +until a `Retile`, which drops them; `RetileWithResizeDimensions` tiles with them, and `Save`, +`Load`, `QuickSave` and `QuickLoad` write them to a file as JSON and read them back. + `PreselectDirection` reserves the index on one side of the focused container for the next window ([`WindowManager::preselect_container_in_direction`]). The workspace inserts an empty container there ([`Container::preselect`]), which [`Workspace::update`] keeps and the layout @@ -342,7 +352,8 @@ module's unit. changes its containers. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized - window out, move the focus, move the focused container, change the layout). + window out, move the focus, move the focused container, change the layout, resize the + focused container). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -426,6 +437,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | | A container moved onto a locked index is locked in its place, and the lock leaves the container that moved away | framework path: [`Workspace::swap_containers`] swaps through `LockableSequence`, which keeps the lock with the index | `test_swap_respecting_locks_various_cases`, `a_lock_stays_with_its_index_when_a_window_is_moved_onto_it` | `containers_mut()` is the `VecDeque` itself | | A window komorebi puts off the screen stays there | framework path: the bridge asks again for the position of a window KWin pulled back after a `geo` command, for a second, three times at most | `a window KWin pulls back from where it was asked to be is asked for the position again`, `a window that cannot go where it was asked is asked again three times at most`, `vm-scrolling` | a window that cannot go where it was asked is left where KWin put it | +| A resize leaves no tile smaller than a tenth of the work area, or than it was | framework path: [`WindowManager::resize_window`] calculates the tiles for the adjustment, and cuts the adjustment down until they all fit | `a_resize_leaves_every_tile_about_a_tenth_of_the_work_area_wide_at_least` | the paddings are taken off afterwards, so a tile can end up a little smaller | | A workspace whose tiling is off moves no window | framework path: [`Workspace::update`] returns before the layout when [`Workspace::tile`] is false | `with_tiling_off_no_window_is_moved_until_it_is_back_on` | none | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | none | @@ -541,7 +553,7 @@ A window is shown, and ends up on a tile: commands against the fake; [`komorebi/tests/layout_options.rs`](../../komorebi/tests/layout_options.rs) and [`komorebi/tests/scrolling.rs`](../../komorebi/tests/scrolling.rs), the layout options and the - scrolling layout. + scrolling layout; [`komorebi/tests/resize.rs`](../../komorebi/tests/resize.rs), resizing. - [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, @@ -579,6 +591,9 @@ A window is shown, and ends up on a tile: [`Workspace::swap_containers`]: ../../komorebi/src/workspace.rs [`Workspace::layout_flip`]: ../../komorebi/src/workspace.rs [`Workspace::layout_options`]: ../../komorebi/src/workspace.rs +[`Workspace::resize_dimensions`]: ../../komorebi/src/workspace.rs +[`WindowManager::resize_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::resize_delta`]: ../../komorebi/src/window_manager.rs [`Workspace::latest_layout`]: ../../komorebi/src/workspace.rs [`LayoutOptions`]: ../../komorebi/src/core/mod.rs [`Workspace::tile`]: ../../komorebi/src/workspace.rs diff --git a/docs/index.md b/docs/index.md index 8da35f5d..6a2a93a4 100644 --- a/docs/index.md +++ b/docs/index.md @@ -33,8 +33,9 @@ the flake's module, which also starts komorebi with every Plasma session, and fr anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to start and stop the daemon, ask it what it is doing and read its log. [Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window, -[Moving windows](usage/moving-windows.md) how to move the focused window to another tile, and -[Layouts](usage/layouts.md) how to change the arrangement of the tiles. +[Moving windows](usage/moving-windows.md) how to move the focused window to another tile, +[Layouts](usage/layouts.md) how to change the arrangement of the tiles, and +[Resizing windows](usage/resizing-windows.md) how to change the size of one. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/resizing-windows.md b/docs/usage/resizing-windows.md new file mode 100644 index 00000000..4425d7f3 --- /dev/null +++ b/docs/usage/resizing-windows.md @@ -0,0 +1,63 @@ +# Resizing windows + +komorebi resizes the focused window by moving the edges of its tile, and its neighbors give up +the room. The size a tile has been given is kept until the workspace is retiled with +`komorebic retile`, so it lasts while windows open and close around it. + +## An edge + +[`komorebic resize-edge`](../cli/resize-edge.md) (or `resize`) moves one edge of the focused +window: `left`, `right`, `up` or `down`, and `increase` moves it outwards, `decrease` inwards. + +```sh +komorebic resize-edge left increase +komorebic resize-edge right decrease +``` + +An edge with no tile on the other side of it, such as the left edge of the first window in the +BSP layout, does not move. Neither does an edge the layout keeps where it is: the grid layout +has no resizing at all, and in the columns layout a window can only be made wider or narrower. + +## An axis + +[`komorebic resize-axis`](../cli/resize-axis.md) moves both edges of the focused window along an +axis: `horizontal` the left and the right edge, `vertical` the top and the bottom edge, and +`horizontal-and-vertical` all four. + +```sh +komorebic resize-axis horizontal increase +``` + +## How far + +[`komorebic resize-delta`](../cli/resize-delta.md) sets how far a resize goes, in pixels: an +edge moves by half of it. The delta starts at 50, so an edge moves by 25 pixels. + +```sh +komorebic resize-delta 100 +``` + +A resize never makes a tile narrower or shorter than a tenth of the monitor's work area, unless +the tile is smaller than that already: a resize that would is carried out as far as it can go. + +## Back to the layout + +[`komorebic retile`](../cli/retile.md) tiles every monitor again in its layout, without the +sizes the tiles were given. To tile again and keep them, send the `RetileWithResizeDimensions` +message, which has no subcommand of its own. + +## Saving and loading the sizes + +The sizes the tiles of the focused workspace were given can be saved to a file and loaded back, +on the same workspace or another one with as many windows: + +```sh +komorebic save-resize ~/sizes.json +komorebic load-resize ~/sizes.json +``` + +[`komorebic quick-save-resize`](../cli/quick-save-resize.md) and +[`komorebic quick-load-resize`](../cli/quick-load-resize.md) do the same with one file the daemon +keeps in its temporary directory, `komorebi.quicksave.json` in `$TMPDIR` (or `/tmp`). A path +given to `save-resize` and `load-resize` can name environment variables, which `komorebic` +expands. diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index f06c7f7c..af51ea46 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -198,7 +198,7 @@ where /// # let daemon = std::thread::spawn(move || -> std::io::Result<()> { /// # let (mut stream, _) = listener.accept()?; /// # BufReader::new(stream.try_clone()?).read_line(&mut String::new())?; -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; /// # stream.write_all(state.as_bytes()) /// # }); /// use komorebi_client::SocketMessage; @@ -260,7 +260,7 @@ pub fn send_query(message: &SocketMessage) -> std::io::Result { /// # let mut message = String::new(); /// # BufReader::new(stream).read_line(&mut message)?; /// # let subscriber = komorebi_client::DATA_DIR.join("bar.sock"); -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; /// # let notification = format!(r#"{{"event":{message},"state":{state}}}"#); /// # std::os::unix::net::UnixStream::connect(subscriber)?.write_all(notification.as_bytes())?; /// # Ok(message) diff --git a/komorebi-client/tests/daemon.rs b/komorebi-client/tests/daemon.rs index 434bf5d5..d41f977b 100644 --- a/komorebi-client/tests/daemon.rs +++ b/komorebi-client/tests/daemon.rs @@ -40,7 +40,7 @@ fn daemon() -> Arc { let mut wm = WindowManager::new(window_manager_event_listener::event_rx(), None).unwrap(); wm.init().unwrap(); - wm.retile_all().unwrap(); + wm.retile_all(false).unwrap(); listen_for_commands(Arc::new(Mutex::new(wm))); fake diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 48b1c403..8198e213 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -12,11 +12,13 @@ //! [`OperationDirection`] is a side of the focused tile, and a [`CycleDirection`] the next or the //! previous container in the order of the workspace. +use crate::core::pathext::ResolvedPathBuf; use clap::ValueEnum; use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; use std::num::NonZeroUsize; +use std::path::PathBuf; use std::str::FromStr; use strum::Display; use strum::EnumString; @@ -344,6 +346,8 @@ pub enum SocketMessage { CancelPreselect, CycleFocusWindow(CycleDirection), CycleMoveWindow(CycleDirection), + ResizeWindowEdge(OperationDirection, Sizing), + ResizeWindowAxis(Axis, Sizing), // Current Workspace Commands ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), @@ -356,6 +360,12 @@ pub enum SocketMessage { ToggleTiling, Stop, Retile, + RetileWithResizeDimensions, + QuickSave, + QuickLoad, + Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + ResizeDelta(i32), State, MonitorInformation, Query(StateQuery), diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index b3ca5641..79d8ade2 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -124,7 +124,7 @@ pub enum NotificationEvent { /// use komorebi::core::SocketMessage; /// use komorebi::window_manager_event::WindowManagerEvent; /// -/// let state = r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#; +/// let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; /// /// let shown = format!( /// r#"{{"event":{{"type":"Show","content":[{{"type":"KWin","content":"WindowAdded"}},{{"id":7}}]}},"state":{state}}}"# @@ -199,7 +199,7 @@ pub struct Notification { /// ]); /// /// let state: State = serde_json::from_str( -/// r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#, +/// r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#, /// )?; /// let event = NotificationEvent::Socket(SocketMessage::Retile); /// notify_subscribers(Notification { event, state }, false)?; diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 71948819..378150ed 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -179,7 +179,7 @@ fn main() -> eyre::Result<()> { )?)); wm.lock().init()?; - wm.lock().retile_all()?; + wm.lock().retile_all(false)?; listen_for_commands(wm.clone()); listen_for_events(wm.clone()); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 3713f743..319e058c 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -32,7 +32,12 @@ //! already, and **CancelPreselect** gives the reserved place up. //! - **MouseFollowsFocus** and **ToggleMouseFollowsFocus** set whether the pointer is moved to //! the window that is given the focus. -//! - **Retile** tiles the focused workspace of every monitor again. +//! - **ResizeWindowEdge** and **ResizeWindowAxis** resize the focused container by the +//! [`WindowManager::resize_delta`] that **ResizeDelta** sets ([`WindowManager::resize_window`]), +//! and **QuickSave**, **QuickLoad**, **Save** and **Load** write the resize adjustments of the +//! focused workspace's containers to a file and read them back. +//! - **Retile** tiles the focused workspace of every monitor again, without the resize +//! adjustments, and **RetileWithResizeDimensions** with them. //! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name //! of its socket in the data directory, and **RemoveSubscriberSocket** removes one. //! - **Stop** stops the daemon ([`WindowManager::stop`]). @@ -45,8 +50,11 @@ use crate::Notification; use crate::NotificationEvent; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; +use crate::core::Axis; use crate::core::Layout; use crate::core::LayoutOptions; +use crate::core::OperationDirection; +use crate::core::Rect; use crate::core::ScrollingLayoutOptions; use crate::core::SocketMessage; use crate::core::StateQuery; @@ -55,8 +63,11 @@ use crate::notify_subscribers; use crate::state::State; use crate::window_manager::WindowManager; use color_eyre::eyre; +use color_eyre::eyre::Context; use color_eyre::eyre::OptionExt; use parking_lot::Mutex; +use std::fs::File; +use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; use std::os::unix::net::UnixStream; @@ -126,8 +137,10 @@ impl WindowManager { /// - The focused container cannot be moved, for one of the reasons /// [`WindowManager::move_container_in_direction`] and /// [`WindowManager::move_container_in_cycle_direction`] give. - /// - There is no focused workspace to change the layout or the tiling of, or to preselect a - /// place in, or it cannot be tiled again. + /// - There is no focused workspace to change the layout or the tiling of, to preselect a + /// place in, or to resize a container of, or it cannot be tiled again. + /// - The file of `QuickSave` or `Save` cannot be written, or the file of `QuickLoad` or + /// `Load` cannot be read or is not a list of resize adjustments. /// - The window manager fails to retile, for one of the reasons /// [`WindowManager::retile_all`] gives. /// - The answer cannot be written to `reply`. @@ -180,10 +193,74 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::ResizeWindowEdge(direction, sizing) => { + self.resize_window(direction, sizing, self.resize_delta, true)?; + } + SocketMessage::ResizeWindowAxis(axis, sizing) => { + match axis { + Axis::Horizontal => { + self.resize_window( + OperationDirection::Left, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Right, + sizing, + self.resize_delta, + false, + )?; + } + Axis::Vertical => { + self.resize_window( + OperationDirection::Up, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Down, + sizing, + self.resize_delta, + false, + )?; + } + Axis::HorizontalAndVertical => { + self.resize_window( + OperationDirection::Left, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Right, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Up, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Down, + sizing, + self.resize_delta, + false, + )?; + } + } + + self.update_focused_workspace(false, false)?; + } SocketMessage::FlipLayout(layout_flip) => self.flip_layout(layout_flip)?, SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, SocketMessage::CycleLayout(direction) => self.cycle_layout(direction)?, - SocketMessage::Retile => self.retile_all()?, + SocketMessage::Retile => self.retile_all(false)?, + SocketMessage::RetileWithResizeDimensions => self.retile_all(true)?, SocketMessage::ToggleTiling => { self.toggle_tiling()?; } @@ -253,6 +330,9 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::ResizeDelta(delta) => { + self.resize_delta = delta; + } SocketMessage::ScrollingLayoutColumns(count) => { let focused_workspace = self.focused_workspace_mut()?; @@ -327,6 +407,58 @@ impl WindowManager { SocketMessage::Stop => { self.stop()?; } + SocketMessage::QuickSave => { + let workspace = self.focused_workspace()?; + let resize = &workspace.resize_dimensions; + + let quicksave_json = std::env::temp_dir().join("komorebi.quicksave.json"); + + let file = OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(quicksave_json)?; + + serde_json::to_writer_pretty(&file, &resize)?; + } + SocketMessage::QuickLoad => { + let workspace = self.focused_workspace_mut()?; + + let quicksave_json = std::env::temp_dir().join("komorebi.quicksave.json"); + + let file = File::open(&quicksave_json).wrap_err(format!( + "no quicksave found at {}", + quicksave_json.display() + ))?; + + let resize: Vec> = serde_json::from_reader(file)?; + + workspace.resize_dimensions = resize; + self.update_focused_workspace(false, false)?; + } + SocketMessage::Save(ref path) => { + let workspace = self.focused_workspace_mut()?; + let resize = &workspace.resize_dimensions; + + let file = OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(path)?; + + serde_json::to_writer_pretty(&file, &resize)?; + } + SocketMessage::Load(ref path) => { + let workspace = self.focused_workspace_mut()?; + + let file = + File::open(path).wrap_err(format!("no file found at {}", path.display()))?; + + let resize: Vec> = serde_json::from_reader(file)?; + + workspace.resize_dimensions = resize; + self.update_focused_workspace(false, false)?; + } } self.update_known_window_ids(); diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 65ebf6ad..0ee1f767 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -53,6 +53,7 @@ use std::collections::VecDeque; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct State { pub monitors: Ring, + pub resize_delta: i32, pub work_area_offset: Option, pub mouse_follows_focus: bool, } @@ -85,6 +86,7 @@ impl From<&WindowManager> for State { workspace_padding: workspace.workspace_padding, container_padding: workspace.container_padding, latest_layout: workspace.latest_layout.clone(), + resize_dimensions: workspace.resize_dimensions.clone(), tile: workspace.tile, globals: workspace.globals, preselected_container_idx: None, @@ -102,6 +104,7 @@ impl From<&WindowManager> for State { Self { monitors: stripped_monitors, work_area_offset: wm.work_area_offset, + resize_delta: wm.resize_delta, mouse_follows_focus: wm.mouse_follows_focus, } } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 171f18ed..630d9058 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -21,12 +21,14 @@ use crate::LibraryError; use crate::SUBSCRIPTION_SOCKETS; use crate::backend::backend; use crate::container::Container; +use crate::core::Arrangement; use crate::core::Axis; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; use crate::core::OperationDirection; use crate::core::Rect; +use crate::core::Sizing; use crate::desktop; use crate::monitor::Monitor; use crate::ring::Ring; @@ -40,16 +42,22 @@ use crossbeam_channel::Receiver; use std::collections::HashMap; use std::io::ErrorKind; use std::net::Shutdown; +use std::num::NonZeroUsize; use std::os::unix::net::UnixListener; use std::os::unix::net::UnixStream; use std::path::PathBuf; +/// A tile cannot be resized to less than this fraction of the work area (or less than it already is) +const MINIMUM_TILE_FRACTION: i32 = 10; + #[derive(Debug)] pub struct WindowManager { pub monitors: Ring, /// The socket the daemon takes messages on, `komorebi.sock` in [`struct@DATA_DIR`] unless /// [`WindowManager::new`] was given another path pub command_listener: UnixListener, + /// How many pixels `ResizeWindowEdge` and `ResizeWindowAxis` resize by + pub resize_delta: i32, /// Whether the pointer is moved to the window that is given the focus, which is the default pub mouse_follows_focus: bool, pub work_area_offset: Option, @@ -102,6 +110,7 @@ impl WindowManager { Ok(Self { monitors: Ring::default(), command_listener: listener, + resize_delta: 50, mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -343,6 +352,13 @@ impl WindowManager { .ok_or_eyre("there is no window") } + pub fn focused_monitor_work_area(&self) -> eyre::Result { + Ok(self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .work_area_size) + } + /// Takes a window the user minimized out of the focused workspace, and keeps it until it is /// restored pub fn extract_minimized_window(&mut self, window_id: u32) -> eyre::Result<()> { @@ -390,9 +406,179 @@ impl WindowManager { std::process::exit(0) } - /// Tiles the focused workspace of every monitor + /// Resizes the focused container by `delta` pixels on its `direction` side, by giving it a + /// resize adjustment that the layout applies, and tiles the workspace again if `update` is set + /// + /// The neighbors on that side give up the room, and none of the tiles may end up smaller than + /// a tenth of the monitor's work area, measured before the paddings are taken off, or than it + /// already is: a resize that would make one smaller is granted as far as it can be. Where + /// there is no container on that side, nothing changes. + /// + /// # Errors + /// + /// - There is no focused monitor, workspace or container. + /// - The workspace cannot be tiled again. #[tracing::instrument(skip(self))] - pub fn retile_all(&mut self) -> eyre::Result<()> { + pub fn resize_window( + &mut self, + direction: OperationDirection, + sizing: Sizing, + delta: i32, + update: bool, + ) -> eyre::Result<()> { + let focused_monitor_work_area = self.focused_monitor_work_area()?; + let workspace = self.focused_workspace_mut()?; + + match workspace.layout { + Layout::Default(layout) => { + tracing::debug!("resizing window"); + let len = NonZeroUsize::new(workspace.containers().len()) + .ok_or_eyre("there must be at least one container")?; + let focused_idx = workspace.focused_container_idx(); + let focused_idx_resize = workspace + .resize_dimensions + .get(focused_idx) + .ok_or_eyre("there is no resize adjustment for this container")?; + + if direction + .destination( + workspace.layout.as_boxed_direction().as_ref(), + workspace.layout_flip, + focused_idx, + len, + workspace.layout_options, + ) + .is_some() + { + let unaltered = layout.calculate( + &focused_monitor_work_area, + len, + workspace.container_padding, + workspace.layout_flip, + &[], + workspace.focused_container_idx(), + workspace.layout_options, + &workspace.latest_layout, + ); + + let mut direction = direction; + + // We only ever want to operate on the unflipped Rect positions when resizing, then we + // can flip them however they need to be flipped once the resizing has been done + if let Some(flip) = workspace.layout_flip { + match flip { + Axis::Horizontal => { + if matches!(direction, OperationDirection::Left) + || matches!(direction, OperationDirection::Right) + { + direction = direction.opposite(); + } + } + Axis::Vertical => { + if matches!(direction, OperationDirection::Up) + || matches!(direction, OperationDirection::Down) + { + direction = direction.opposite(); + } + } + Axis::HorizontalAndVertical => direction = direction.opposite(), + } + } + + let unaltered_tile = *unaltered + .get(focused_idx) + .ok_or_eyre("there is no last layout")?; + + // How much of what was asked for the layout can take. The layout crate no + // longer turns a resize down by the size of the container being resized + // (the wrong measure: the room is in the neighbours, and a narrow tile + // could not be dragged by more than half its own width, however much its + // neighbours had to give); the right one is what every tile looks like + // afterwards. None may end up smaller than a tenth of the work area, or + // than it already is, and a request that would is granted as far as it + // can be rather than dropped. + let min_width = focused_monitor_work_area.right / MINIMUM_TILE_FRACTION; + let min_height = focused_monitor_work_area.bottom / MINIMUM_TILE_FRACTION; + + let calculate = |dimensions: &[Option]| { + layout.calculate( + &focused_monitor_work_area, + len, + workspace.container_padding, + workspace.layout_flip, + dimensions, + focused_idx, + workspace.layout_options, + &workspace.latest_layout, + ) + }; + let now = calculate(&workspace.resize_dimensions); + let candidate = |amount: i32| { + layout.resize( + &unaltered_tile, + focused_idx_resize, + direction, + sizing, + amount, + ) + }; + let fits = |amount: i32| { + let mut dimensions = workspace.resize_dimensions.clone(); + dimensions[focused_idx] = candidate(amount); + calculate(&dimensions) + .iter() + .zip(now.iter()) + .all(|(tile, before)| { + tile.right >= min_width.min(before.right) + && tile.bottom >= min_height.min(before.bottom) + }) + }; + + let granted = if fits(delta) { + delta + } else { + // the tiles only ever get smaller as the amount grows + let (mut fits_at, mut fails_at) = (0, delta); + while fails_at - fits_at > 1 { + let middle = fits_at + (fails_at - fits_at) / 2; + if fits(middle) { + fits_at = middle; + } else { + fails_at = middle; + } + } + fits_at + }; + + if granted != delta { + tracing::debug!( + "granting {granted} of the {delta} asked for: a tile would get smaller than {min_width}x{min_height}" + ); + } + + if granted > 0 { + let resize = candidate(granted); + workspace.resize_dimensions[focused_idx] = resize; + } + + return if update { + self.update_focused_workspace(false, false) + } else { + Ok(()) + }; + } + + tracing::debug!("cannot resize container in this direction"); + } + } + + Ok(()) + } + + /// Tiles the focused workspace of every monitor, without the resize adjustments of its + /// containers unless `preserve_resize_dimensions` is set + #[tracing::instrument(skip(self))] + pub fn retile_all(&mut self, preserve_resize_dimensions: bool) -> eyre::Result<()> { let offset = self.work_area_offset; for monitor in self.monitors_mut() { @@ -409,6 +595,11 @@ impl WindowManager { .focused_workspace_mut() .ok_or_eyre("there is no workspace")?; + // Reset any resize adjustments if we want to force a retile + if !preserve_resize_dimensions { + workspace.resize_dimensions.fill(None); + } + workspace.update()?; } @@ -800,7 +991,7 @@ mod tests { with_backend(fake.clone(), || { wm.init()?; - wm.retile_all() + wm.retile_all(false) })?; // the default workspace and container padding are 5 each, and the second monitor has no diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 689e8765..468a070f 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -33,6 +33,7 @@ pub struct Workspace { pub workspace_padding: Option, pub container_padding: Option, pub latest_layout: Vec, + pub resize_dimensions: Vec>, pub tile: bool, #[serde(skip)] pub globals: WorkspaceGlobals, @@ -48,6 +49,7 @@ impl Default for Workspace { containers: Default::default(), workspace_padding: None, container_padding: None, + resize_dimensions: vec![], layout: Layout::Default(DefaultLayout::BSP), latest_layout: vec![], layout_flip: None, @@ -206,6 +208,12 @@ impl Workspace { .containers_mut() .insert_respecting_locks(idx, container); + if insertion_idx > self.resize_dimensions.len() { + self.resize_dimensions.push(None); + } else { + self.resize_dimensions.insert(insertion_idx, None); + } + self.focus_container(insertion_idx); insertion_idx @@ -289,7 +297,13 @@ impl Workspace { // this fn respects locked container indexes - we should use it for pretty much everything // except monocle and maximize toggles pub fn remove_container_by_idx(&mut self, idx: usize) -> Option { - self.containers_mut().remove_respecting_locks(idx) + let container = self.containers_mut().remove_respecting_locks(idx); + + if idx < self.resize_dimensions.len() { + self.resize_dimensions.remove(idx); + } + + container } pub fn focus_previous_container(&mut self) { @@ -356,8 +370,9 @@ impl Workspace { /// part of the window is in view is first centered in the work area. A workspace whose tiling /// is off ([`Workspace::tile`] is false) moves no window. /// - /// The tiles are kept in [`Workspace::latest_layout`], which the scrolling layout scrolls - /// from. + /// The layout applies the resize adjustment of each container ([`Workspace::resize_dimensions`]) + /// after the parts its layout cannot apply have been cleared. The tiles are kept in + /// [`Workspace::latest_layout`], which the scrolling layout scrolls from. pub fn update(&mut self) -> eyre::Result<()> { // make sure we are never holding on to empty containers self.prune_duplicate_windows()?; @@ -396,6 +411,8 @@ impl Workspace { adjusted_work_area.add_padding(workspace_padding); + self.enforce_resize_constraints(); + if self.tile { // the backend batches the commands this produces and sends them together let result = (|| -> eyre::Result<()> { @@ -407,12 +424,13 @@ impl Workspace { )?, Some(container_padding), self.layout_flip, - &[], + &self.resize_dimensions, self.focused_container_idx(), self.layout_options, &self.latest_layout, ); + let resize_dimensions_is_empty = self.resize_dimensions.is_empty(); let is_scrolling = matches!(self.layout, Layout::Default(DefaultLayout::Scrolling)); @@ -459,7 +477,8 @@ impl Workspace { let percentage_override = proposed_percentage == 0.0 && current_percentage > 0.1 - && current_percentage < 100.0; + && current_percentage < 100.0 + && resize_dimensions_is_empty; if percentage_override { window.center(&work_area)?; @@ -478,10 +497,296 @@ impl Workspace { result?; } + // Always make sure that the length of the resize dimensions vec is the same as the + // number of layouts / containers. This should never actually truncate as the remove_window + // function takes care of cleaning up resize dimensions when destroying empty containers + let container_count = self.containers().len(); + self.resize_dimensions.resize(container_count, None); + Ok(()) } } +impl Workspace { + fn enforce_resize_constraints(&mut self) { + match self.layout { + Layout::Default(DefaultLayout::BSP) => self.enforce_resize_constraints_for_bsp(), + Layout::Default(DefaultLayout::Columns) => self.enforce_resize_for_columns(), + Layout::Default(DefaultLayout::Rows) => self.enforce_resize_for_rows(), + Layout::Default(DefaultLayout::VerticalStack) => { + self.enforce_resize_for_vertical_stack(); + } + Layout::Default(DefaultLayout::RightMainVerticalStack) => { + self.enforce_resize_for_right_vertical_stack(); + } + Layout::Default(DefaultLayout::HorizontalStack) => { + self.enforce_resize_for_horizontal_stack(); + } + Layout::Default(DefaultLayout::UltrawideVerticalStack) => { + self.enforce_resize_for_ultrawide(); + } + Layout::Default(DefaultLayout::Scrolling) => { + self.enforce_resize_for_scrolling(); + } + _ => self.enforce_no_resize(), + } + } + + fn enforce_resize_constraints_for_bsp(&mut self) { + for (i, rect) in self.resize_dimensions.iter_mut().enumerate() { + if let Some(rect) = rect { + // Even containers can't be resized to the bottom + if i % 2 == 0 { + rect.bottom = 0; + // Odd containers can't be resized to the right + } else { + rect.right = 0; + } + } + } + + // The first container can never be resized to the left or the top + if let Some(Some(first)) = self.resize_dimensions.first_mut() { + first.top = 0; + first.left = 0; + } + + // The last container can never be resized to the bottom or the right + if let Some(Some(last)) = self.resize_dimensions.last_mut() { + last.bottom = 0; + last.right = 0; + } + } + + fn enforce_resize_for_columns(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + 0 | 1 => self.enforce_no_resize(), + _ => { + let len = resize_dimensions.len(); + for (i, rect) in resize_dimensions.iter_mut().enumerate() { + if let Some(rect) = rect { + rect.top = 0; + rect.bottom = 0; + + if i == 0 { + rect.left = 0; + } + if i == len - 1 { + rect.right = 0; + } + } + } + } + } + } + + fn enforce_resize_for_rows(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + 0 | 1 => self.enforce_no_resize(), + _ => { + let len = resize_dimensions.len(); + for (i, rect) in resize_dimensions.iter_mut().enumerate() { + if let Some(rect) = rect { + rect.left = 0; + rect.right = 0; + + if i == 0 { + rect.top = 0; + } + if i == len - 1 { + rect.bottom = 0; + } + } + } + } + } + } + + fn enforce_resize_for_vertical_stack(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + // Single window can not be resized at all + 0 | 1 => self.enforce_no_resize(), + _ => { + // Zero is actually on the left + if let Some(left) = resize_dimensions[0].as_mut() { + left.top = 0; + left.bottom = 0; + left.left = 0; + } + + // Handle stack on the right + let stack_size = resize_dimensions[1..].len(); + for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { + if let Some(rect) = rect { + // No containers can resize to the right + rect.right = 0; + + // First container in stack cant resize up + if i == 0 { + rect.top = 0; + } else if i == stack_size - 1 { + // Last cant be resized to the bottom + rect.bottom = 0; + } + } + } + } + } + } + + fn enforce_resize_for_right_vertical_stack(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + // Single window can not be resized at all + 0 | 1 => self.enforce_no_resize(), + _ => { + // Zero is actually on the right + if let Some(left) = resize_dimensions[1].as_mut() { + left.top = 0; + left.bottom = 0; + left.right = 0; + } + + // Handle stack on the right + let stack_size = resize_dimensions[1..].len(); + for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { + if let Some(rect) = rect { + // No containers can resize to the left + rect.left = 0; + + // First container in stack cant resize up + if i == 0 { + rect.top = 0; + } else if i == stack_size - 1 { + // Last cant be resized to the bottom + rect.bottom = 0; + } + } + } + } + } + } + + fn enforce_resize_for_horizontal_stack(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + 0 | 1 => self.enforce_no_resize(), + _ => { + if let Some(left) = resize_dimensions[0].as_mut() { + left.top = 0; + left.left = 0; + left.right = 0; + } + + let stack_size = resize_dimensions[1..].len(); + for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { + if let Some(rect) = rect { + rect.bottom = 0; + + if i == 0 { + rect.left = 0; + } + if i == stack_size - 1 { + rect.right = 0; + } + } + } + } + } + } + + fn enforce_resize_for_ultrawide(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + // Single window can not be resized at all + 0 | 1 => self.enforce_no_resize(), + // Two windows can only be resized in the middle + 2 => { + // Zero is actually on the right + if let Some(right) = resize_dimensions[0].as_mut() { + right.top = 0; + right.bottom = 0; + right.right = 0; + } + + // One is on the left + if let Some(left) = resize_dimensions[1].as_mut() { + left.top = 0; + left.bottom = 0; + left.left = 0; + } + } + // Three or more windows means 0 is in center, 1 is at the left, 2.. are a vertical + // stack on the right + _ => { + // Central can be resized left or right + if let Some(right) = resize_dimensions[0].as_mut() { + right.top = 0; + right.bottom = 0; + } + + // Left one can only be resized to the right + if let Some(left) = resize_dimensions[1].as_mut() { + left.top = 0; + left.bottom = 0; + left.left = 0; + } + + // Handle stack on the right + let stack_size = resize_dimensions[2..].len(); + for (i, rect) in resize_dimensions[2..].iter_mut().enumerate() { + if let Some(rect) = rect { + // No containers can resize to the right + rect.right = 0; + + // First container in stack cant resize up + if i == 0 { + rect.top = 0; + } else if i == stack_size - 1 { + // Last cant be resized to the bottom + rect.bottom = 0; + } + } + } + } + } + } + + fn enforce_resize_for_scrolling(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + 0 | 1 => self.enforce_no_resize(), + _ => { + let len = resize_dimensions.len(); + + for (i, rect) in resize_dimensions.iter_mut().enumerate() { + if let Some(rect) = rect { + rect.top = 0; + rect.bottom = 0; + + if i == 0 { + rect.left = 0; + } else if i == len - 1 { + rect.right = 0; + } + } + } + } + } + } + fn enforce_no_resize(&mut self) { + for rect in self.resize_dimensions.iter_mut().flatten() { + rect.left = 0; + rect.right = 0; + rect.top = 0; + rect.bottom = 0; + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -1017,6 +1322,118 @@ mod tests { assert_eq!(focused_container.focused_window_idx(), 1); } + #[test] + fn test_layout_boundary_clamping() { + use crate::core::Rect; + use komorebi_layouts::default_layout::DefaultLayout; + use std::num::NonZeroUsize; + + // Simulate an ultrawide monitor at 5120px width + let work_area = Rect { + left: 0, + top: 0, + right: 5120, + bottom: 1440, + }; + + // Create a workspace with 2 containers in Columns layout + let layout = Layout::Default(DefaultLayout::Columns); + + // Simulate a resize adjustment that would cause overflow + // Container 0 gets expanded by 2100px to the right + let resize_dimensions = vec![ + Some(Rect { + left: 0, + top: 0, + right: 2100, + bottom: 0, + }), + None, + ]; + + // Calculate the layout + let mut layouts = layout.as_boxed_arrangement().calculate( + &work_area, + NonZeroUsize::new(2).unwrap(), + None, + None, + &resize_dimensions, + 0, + None, + &[], + ); + + // Apply boundary clamping (mimicking the logic in workspace.rs update()) + for layout in &mut layouts { + // Check horizontal boundaries + if layout.left < work_area.left { + layout.right -= work_area.left - layout.left; + layout.left = work_area.left; + } + let max_right_edge = work_area.left + work_area.right; + let current_right_edge = layout.left + layout.right; + if current_right_edge > max_right_edge { + layout.right = max_right_edge - layout.left; + } + + // Check vertical boundaries + if layout.top < work_area.top { + layout.bottom -= work_area.top - layout.top; + layout.top = work_area.top; + } + let max_bottom_edge = work_area.top + work_area.bottom; + let current_bottom_edge = layout.top + layout.bottom; + if current_bottom_edge > max_bottom_edge { + layout.bottom = max_bottom_edge - layout.top; + } + } + + // Verify that all layouts stay within work area boundaries + for layout in &layouts { + // Horizontal bounds + assert!( + layout.left >= work_area.left, + "Layout left ({}) should be >= work_area left ({})", + layout.left, + work_area.left + ); + let right_edge = layout.left + layout.right; + let max_right_edge = work_area.left + work_area.right; + assert!( + right_edge <= max_right_edge, + "Layout right edge ({}) should be <= work_area right edge ({})", + right_edge, + max_right_edge + ); + + // Vertical bounds + assert!( + layout.top >= work_area.top, + "Layout top ({}) should be >= work_area top ({})", + layout.top, + work_area.top + ); + let bottom_edge = layout.top + layout.bottom; + let max_bottom_edge = work_area.top + work_area.bottom; + assert!( + bottom_edge <= max_bottom_edge, + "Layout bottom edge ({}) should be <= work_area bottom edge ({})", + bottom_edge, + max_bottom_edge + ); + } + + // Additionally verify that with the resize adjustment, + // the second container doesn't bleed beyond 5120 + assert_eq!(layouts.len(), 2); + let container1_right_edge = layouts[1].left + layouts[1].right; + assert!( + container1_right_edge <= 5120, + "Container 1 right edge ({}) should not exceed monitor width (5120)", + container1_right_edge + ); + } + fn tile(left: i32, top: i32, right: i32, bottom: i32) -> Rect { Rect { left, diff --git a/komorebi/tests/resize.rs b/komorebi/tests/resize.rs new file mode 100644 index 00000000..8be939c5 --- /dev/null +++ b/komorebi/tests/resize.rs @@ -0,0 +1,237 @@ +//! Resizing the focused window from the command line, `resize-edge`, `resize-axis` and +//! `resize-delta`, and saving and loading the sizes, against an in-memory desktop: the messages go +//! in through [`WindowManager::process_command`], and what comes out is where the backend is asked +//! to put each window. +//! +//! Window ids are in the 23_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::Axis; +use komorebi::core::DefaultLayout; +use komorebi::core::OperationDirection; +use komorebi::core::Rect; +use komorebi::core::Sizing; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel) +/// in `layout`, and a window for each of `ids`, opened in that order. The last one has the focus. +fn desktop_with(layout: DefaultLayout, ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmr-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + send(&fake, &mut wm, SocketMessage::ChangeLayout(layout)); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); + } + + (fake, wm) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn edge(direction: OperationDirection, sizing: Sizing) -> SocketMessage { + SocketMessage::ResizeWindowEdge(direction, sizing) +} + +fn rects(fake: &FakeBackend, ids: &[u32]) -> Vec { + ids.iter().map(|&id| fake.rect_of(id).unwrap()).collect() +} + +#[test] +fn resize_edge_moves_the_edge_between_the_focused_window_and_its_neighbor() { + let ids = [23_001, 23_002]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let before = rects(&fake, &ids); + + // the second window has the focus, on the right: its left edge goes left by half the delta + // of 50, which is how komorebi-layouts moves an edge + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + + let after = rects(&fake, &ids); + assert_eq!(after[1].left, before[1].left - 25, "{before:?} {after:?}"); + assert_eq!(after[1].right, before[1].right + 25); + assert_eq!(after[0].right, before[0].right - 25); + + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Decrease), + ); + + assert_eq!(rects(&fake, &ids), before); +} + +#[test] +fn resize_edge_on_a_side_with_no_neighbor_changes_nothing() { + let ids = [23_011, 23_012]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let before = rects(&fake, &ids); + + send( + &fake, + &mut wm, + edge(OperationDirection::Right, Sizing::Increase), + ); + + assert_eq!(rects(&fake, &ids), before); + assert_eq!( + wm.focused_workspace().unwrap().resize_dimensions, + [None, None] + ); +} + +#[test] +fn resize_axis_moves_both_edges_along_the_axis() { + let ids = [23_021, 23_022, 23_023]; + let (fake, mut wm) = desktop_with(DefaultLayout::Columns, &ids); + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(komorebi::core::CycleDirection::Previous), + ); + assert_eq!(wm.focused_window().unwrap().id, 23_022); + let before = rects(&fake, &ids); + + send( + &fake, + &mut wm, + SocketMessage::ResizeWindowAxis(Axis::Horizontal, Sizing::Increase), + ); + + let after = rects(&fake, &ids); + assert_eq!(after[1].left, before[1].left - 25, "{before:?} {after:?}"); + assert_eq!(after[1].right, before[1].right + 50); + assert_eq!(after[0].right, before[0].right - 25); + assert_eq!(after[2].right, before[2].right - 25); +} + +#[test] +fn resize_delta_sets_how_far_a_resize_goes() { + let ids = [23_031, 23_032]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let before = rects(&fake, &ids); + + send(&fake, &mut wm, SocketMessage::ResizeDelta(120)); + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + + assert_eq!(wm.resize_delta, 120); + assert_eq!(fake.rect_of(23_032).unwrap().left, before[1].left - 60); +} + +#[test] +fn a_resize_leaves_every_tile_about_a_tenth_of_the_work_area_wide_at_least() { + let ids = [23_041, 23_042]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + + send(&fake, &mut wm, SocketMessage::ResizeDelta(5000)); + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + + // a tenth of the work area, measured before the paddings are taken off the tiles + let after = rects(&fake, &ids); + assert!(after[0].right >= 1920 / 10 - 20, "{after:?}"); + assert!( + after[0].right < 400, + "it was granted as far as it goes: {after:?}" + ); +} + +#[test] +fn retile_forgets_the_resizes_and_retile_with_resize_dimensions_keeps_them() { + let ids = [23_051, 23_052]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let before = rects(&fake, &ids); + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + let resized = rects(&fake, &ids); + + send(&fake, &mut wm, SocketMessage::RetileWithResizeDimensions); + assert_eq!(rects(&fake, &ids), resized); + + send(&fake, &mut wm, SocketMessage::Retile); + assert_eq!(rects(&fake, &ids), before); +} + +#[test] +fn sizes_saved_to_a_file_are_loaded_back_from_it() { + let ids = [23_061, 23_062]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let path = + std::env::temp_dir().join(format!("komorebi-resize-test-{}.json", std::process::id())); + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + let resized = rects(&fake, &ids); + + send(&fake, &mut wm, SocketMessage::Save(path.clone())); + send(&fake, &mut wm, SocketMessage::Retile); + assert_ne!(rects(&fake, &ids), resized); + send(&fake, &mut wm, SocketMessage::Load(path.clone())); + + assert_eq!(rects(&fake, &ids), resized); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn loading_sizes_from_a_file_that_is_not_there_is_an_error() { + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &[23_071]); + + let result = with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::Load("/nonexistent/komorebi-resize.json".into()), + Vec::new(), + ) + }); + + assert_eq!( + result.map_err(|error| error.to_string()), + Err(String::from( + "no file found at /nonexistent/komorebi-resize.json" + )) + ); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 5f6eb776..8fd4942a 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -5,13 +5,18 @@ //! is written and the answer is printed. The messages are [`komorebi_client::SocketMessage`]s, //! sent with [`komorebi_client::send_message`] and [`komorebi_client::send_query`]. //! -//! `focus` and `cycle-focus` give the focus to another window of the focused workspace, and -//! `mouse-follows-focus` and `toggle-mouse-follows-focus` set whether the pointer goes with it. -//! `move` and `cycle-move` move the focused window to another tile. `change-layout`, -//! `cycle-layout` and `flip-layout` change the layout of the focused workspace, `toggle-tiling` -//! turns its tiling off and on, `scrolling-layout-columns` and `layout-ratios` tune the layouts, -//! and `preselect-direction` and `cancel-preselect` reserve the place of the next window and give -//! it up. +//! The orders that change what the daemon tiles: +//! +//! - `focus` and `cycle-focus` give the focus to another window of the focused workspace, and +//! `mouse-follows-focus` and `toggle-mouse-follows-focus` set whether the pointer goes with it. +//! - `move` and `cycle-move` move the focused window to another tile. +//! - `change-layout`, `cycle-layout` and `flip-layout` change the layout of the focused +//! workspace, `scrolling-layout-columns` and `layout-ratios` tune it, `toggle-tiling` turns its +//! tiling off and on, and `preselect-direction` and `cancel-preselect` reserve the place of the +//! next window and give it up. +//! - `resize-edge` and `resize-axis` resize the focused window by the `resize-delta`, and +//! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of +//! the tiles of the focused workspace and load them back. //! //! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens //! on a socket in the daemon's data directory, to which the daemon sends a notification after each @@ -32,8 +37,10 @@ use komorebi_client::Axis; use komorebi_client::CycleDirection; use komorebi_client::DefaultLayout; use komorebi_client::OperationDirection; +use komorebi_client::Sizing; use komorebi_client::SocketMessage; use komorebi_client::StateQuery; +use komorebi_client::replace_env_in_path; use komorebi_client::send_message; use komorebi_client::send_query; use std::fs::File; @@ -90,6 +97,28 @@ gen_enum_subcommand_args! { Query: StateQuery, } +#[derive(Parser)] +struct Resize { + #[clap(value_enum)] + edge: OperationDirection, + #[clap(value_enum)] + sizing: Sizing, +} + +#[derive(Parser)] +struct ResizeAxis { + #[clap(value_enum)] + axis: Axis, + #[clap(value_enum)] + sizing: Sizing, +} + +#[derive(Parser)] +struct ResizeDelta { + /// The delta of pixels by which to increase or decrease window dimensions when resizing + pixels: i32, +} + #[derive(Parser)] struct SubscribeSocket { /// Name of the socket to send event notifications to @@ -113,6 +142,20 @@ struct Start { #[derive(Parser)] struct Stop {} +#[derive(Parser)] +struct SaveResize { + /// File to which the resize layout dimensions should be saved + #[clap(value_parser = replace_env_in_path)] + path: PathBuf, +} + +#[derive(Parser)] +struct LoadResize { + /// File from which the resize layout dimensions should be loaded + #[clap(value_parser = replace_env_in_path)] + path: PathBuf, +} + #[derive(Parser)] struct ScrollingLayoutColumns { /// Desired number of visible columns @@ -187,6 +230,20 @@ enum SubCommand { // UnsubscribePipe(UnsubscribePipe), /// Tail komorebi's process logs (cancel with Ctrl-C) Log, + /// Quicksave the current resize layout dimensions + #[clap(alias = "quick-save")] + QuickSaveResize, + /// Load the last quicksaved resize layout dimensions + #[clap(alias = "quick-load")] + QuickLoadResize, + /// Save the current resize layout dimensions to a file + #[clap(arg_required_else_help = true)] + #[clap(alias = "save")] + SaveResize(SaveResize), + /// Load the resize layout dimensions from a file + #[clap(arg_required_else_help = true)] + #[clap(alias = "load")] + LoadResize(LoadResize), /// Change focus to the window in the specified direction #[clap(arg_required_else_help = true)] Focus(Focus), @@ -204,6 +261,16 @@ enum SubCommand { /// Move the focused window in the specified cycle direction #[clap(arg_required_else_help = true)] CycleMove(CycleMove), + /// Resize the focused window in the specified direction + #[clap(arg_required_else_help = true)] + #[clap(alias = "resize")] + ResizeEdge(Resize), + /// Resize the focused window or primary column along the specified axis + #[clap(arg_required_else_help = true)] + ResizeAxis(ResizeAxis), + /// Set the resize delta (used by resize-edge and resize-axis) + #[clap(arg_required_else_help = true)] + ResizeDelta(ResizeDelta), /// Set the layout on the focused workspace #[clap(arg_required_else_help = true)] ChangeLayout(ChangeLayout), @@ -375,6 +442,12 @@ fn main() -> eyre::Result<()> { SubCommand::FlipLayout(args) => { send_message(&SocketMessage::FlipLayout(args.axis))?; } + SubCommand::ResizeEdge(args) => { + send_message(&SocketMessage::ResizeWindowEdge(args.edge, args.sizing))?; + } + SubCommand::ResizeAxis(args) => { + send_message(&SocketMessage::ResizeWindowAxis(args.axis, args.sizing))?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } @@ -390,6 +463,9 @@ fn main() -> eyre::Result<()> { SubCommand::MonitorInformation => { print_query(&SocketMessage::MonitorInformation); } + SubCommand::ResizeDelta(args) => { + send_message(&SocketMessage::ResizeDelta(args.pixels))?; + } SubCommand::ScrollingLayoutColumns(args) => { send_message(&SocketMessage::ScrollingLayoutColumns(args.count))?; } @@ -414,6 +490,18 @@ fn main() -> eyre::Result<()> { SubCommand::UnsubscribeSocket(args) => { send_message(&SocketMessage::RemoveSubscriberSocket(args.socket))?; } + SubCommand::QuickSaveResize => { + send_message(&SocketMessage::QuickSave)?; + } + SubCommand::QuickLoadResize => { + send_message(&SocketMessage::QuickLoad)?; + } + SubCommand::SaveResize(args) => { + send_message(&SocketMessage::Save(args.path))?; + } + SubCommand::LoadResize(args) => { + send_message(&SocketMessage::Load(args.path))?; + } } Ok(()) diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 63882b84..2e3847a9 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -254,6 +254,36 @@ fn scrolling_layout_columns_refuses_zero() { assert!(!output.status.success(), "{output:?}"); } +#[test] +fn the_resize_subcommands_send_what_they_are_given() { + sends( + &["resize-edge", "left", "increase"], + r#"{"type":"ResizeWindowEdge","content":["Left","Increase"]}"#, + ); + sends( + &["resize", "down", "decrease"], + r#"{"type":"ResizeWindowEdge","content":["Down","Decrease"]}"#, + ); + sends( + &["resize-axis", "horizontal-and-vertical", "increase"], + r#"{"type":"ResizeWindowAxis","content":["HorizontalAndVertical","Increase"]}"#, + ); + sends( + &["resize-delta", "75"], + r#"{"type":"ResizeDelta","content":75}"#, + ); + sends(&["quick-save-resize"], r#"{"type":"QuickSave"}"#); + sends(&["quick-load"], r#"{"type":"QuickLoad"}"#); + sends( + &["save-resize", "/tmp/sizes.json"], + r#"{"type":"Save","content":"/tmp/sizes.json"}"#, + ); + sends( + &["load", "/tmp/sizes.json"], + r#"{"type":"Load","content":"/tmp/sizes.json"}"#, + ); +} + #[test] fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { sends( @@ -319,13 +349,20 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "flip-layout.md", "focus.md", "layout-ratios.md", + "load-resize.md", "log.md", "monitor-information.md", "mouse-follows-focus.md", "move.md", "preselect-direction.md", "query.md", + "quick-load-resize.md", + "quick-save-resize.md", + "resize-axis.md", + "resize-delta.md", + "resize-edge.md", "retile.md", + "save-resize.md", "scrolling-layout-columns.md", "start.md", "state.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 3e33bc8a..a29f4dcc 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -157,6 +157,14 @@ cycle-focus next cycle-focus previous cycle-move next cycle-move previous +resize-edge left increase +resize-edge right decrease +resize-edge up increase +resize-edge down decrease +resize-axis horizontal increase +resize-axis vertical decrease +resize-delta 50 +resize-delta 100 retile flip-layout horizontal flip-layout vertical @@ -202,6 +210,17 @@ for query in [ ]: status, out = kde.run(f"komorebic query {query}") checks.check(f"query {query} answers", status == 0 and out.strip() != "") +checks.check( + "quick-save-resize and quick-load-resize", + kde.run("komorebic quick-save-resize && komorebic quick-load-resize")[0] == 0, +) +checks.check( + "save-resize and load-resize", + kde.run( + "komorebic save-resize /tmp/e2e-resize.json && komorebic load-resize /tmp/e2e-resize.json" + )[0] + == 0, +) print("== 5. still all there") checks.check("komorebi has every window KWin has, and answers", healthy() == 0) From 554d77aed9795f2b2f013ac2925f3979791bb3ff Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 16:29:38 -0700 Subject: [PATCH 023/255] feat(wm): promote The first tile of a layout is its largest, and the place for the window being worked on. `komorebic promote` moves the focused window there, with the windows that were before it each moving one tile on; `promote-swap` swaps it with the window that has the first tile, and from the first tile swaps it back with the window it was last swapped with; `promote-window left|right|up|down` promotes the window on that side of the focused one; and `promote-focus` gives the focus to the first tile and moves nothing. The grid layout has no largest tile, so the four do nothing there. The vm-commands sweep gains the four. --- README.md | 5 +- docs/cli/promote-focus.md | 10 ++ docs/cli/promote-swap.md | 10 ++ docs/cli/promote-window.md | 14 +++ docs/cli/promote.md | 10 ++ docs/dev/ARCHITECTURE.md | 20 +++- docs/usage/focusing-windows.md | 5 + docs/usage/moving-windows.md | 23 ++++ komorebi/src/core/mod.rs | 4 + komorebi/src/process_command.rs | 14 ++- komorebi/src/state.rs | 1 + komorebi/src/window_manager.rs | 86 +++++++++++++++ komorebi/src/workspace.rs | 28 +++++ komorebi/tests/promote.rs | 153 +++++++++++++++++++++++++++ komorebic/src/main.rs | 23 ++++ komorebic/tests/cli.rs | 15 +++ nix/tests/vm/suites/commands/test.py | 4 + 17 files changed, 419 insertions(+), 6 deletions(-) create mode 100644 docs/cli/promote-focus.md create mode 100644 docs/cli/promote-swap.md create mode 100644 docs/cli/promote-window.md create mode 100644 docs/cli/promote.md create mode 100644 komorebi/tests/promote.rs diff --git a/README.md b/README.md index 6fd7a151..299f5e2c 100644 --- a/README.md +++ b/README.md @@ -138,8 +138,9 @@ one in the layout, or to the next one in the workspace's order, and `move` and again. `change-layout`, `cycle-layout` and `flip-layout` tile the workspace in another layout, `layout-ratios` and `scrolling-layout-columns` tune it, `toggle-tiling` stops it moving windows and starts it again, -`preselect-direction` reserves a tile for the next window, and `resize-edge` -and `resize-axis` move the edges of the focused tile. The scrolling layout +`preselect-direction` reserves a tile for the next window, `resize-edge` and +`resize-axis` move the edges of the focused tile, and `promote` brings the +focused window to the largest tile. The scrolling layout is a strip of columns that runs past the edges of the monitor and scrolls to the window that has the focus. diff --git a/docs/cli/promote-focus.md b/docs/cli/promote-focus.md new file mode 100644 index 00000000..5b021a73 --- /dev/null +++ b/docs/cli/promote-focus.md @@ -0,0 +1,10 @@ +```text +Promote the user focus to the largest window container + +Usage: promote-focus + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/promote-swap.md b/docs/cli/promote-swap.md new file mode 100644 index 00000000..79ba6e19 --- /dev/null +++ b/docs/cli/promote-swap.md @@ -0,0 +1,10 @@ +```text +Promote the focused window to the largest tile by swapping container indices with the largest tile + +Usage: promote-swap + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/promote-window.md b/docs/cli/promote-window.md new file mode 100644 index 00000000..7a4f51ea --- /dev/null +++ b/docs/cli/promote-window.md @@ -0,0 +1,14 @@ +```text +Promote the window in the specified direction + +Usage: promote-window + +Arguments: + + [possible values: left, right, up, down] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/promote.md b/docs/cli/promote.md new file mode 100644 index 00000000..465b293a --- /dev/null +++ b/docs/cli/promote.md @@ -0,0 +1,10 @@ +```text +Promote the focused window to the largest tile via container removal and re-insertion + +Usage: promote + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index c2c60932..f656e2fb 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -285,6 +285,15 @@ focused container has changed, which scrolls the strip to it. KWin keeps part of resizes on an output, so the bridge asks again for the position of a window KWin pulled back within a second of the command, three times at most ([`bridge.js`]'s `settle`). +`Promote` moves the focused container to index 0, the largest tile of every layout but the grid, +through `LockableSequence`, so the containers before it move one index on +([`WindowManager::promote_container_to_front`]). `PromoteSwap` swaps it with the container at +index 0 and records the index it came from in [`Workspace::promotion_swap_container_idx`], so +that from index 0 it swaps back ([`WindowManager::promote_container_swap`]). `PromoteFocus` +focuses the container at index 0 ([`WindowManager::promote_focus_to_front`]), and +`PromoteWindow` focuses the container in a direction and promotes it. On the grid layout they +change nothing. + `ResizeWindowEdge` and `ResizeWindowAxis` resize the focused container ([`WindowManager::resize_window`]). A resize is an adjustment of the container's tile, kept in [`Workspace::resize_dimensions`], one per container, which the layout applies when it calculates @@ -352,8 +361,8 @@ module's unit. changes its containers. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized - window out, move the focus, move the focused container, change the layout, resize the - focused container). + window out, move the focus, move the focused container, change the layout, resize or + promote the focused container). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -553,7 +562,8 @@ A window is shown, and ends up on a tile: commands against the fake; [`komorebi/tests/layout_options.rs`](../../komorebi/tests/layout_options.rs) and [`komorebi/tests/scrolling.rs`](../../komorebi/tests/scrolling.rs), the layout options and the - scrolling layout; [`komorebi/tests/resize.rs`](../../komorebi/tests/resize.rs), resizing. + scrolling layout; [`komorebi/tests/resize.rs`](../../komorebi/tests/resize.rs), resizing; + [`komorebi/tests/promote.rs`](../../komorebi/tests/promote.rs), promoting. - [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, @@ -593,6 +603,10 @@ A window is shown, and ends up on a tile: [`Workspace::layout_options`]: ../../komorebi/src/workspace.rs [`Workspace::resize_dimensions`]: ../../komorebi/src/workspace.rs [`WindowManager::resize_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::promote_container_to_front`]: ../../komorebi/src/window_manager.rs +[`WindowManager::promote_container_swap`]: ../../komorebi/src/window_manager.rs +[`WindowManager::promote_focus_to_front`]: ../../komorebi/src/window_manager.rs +[`Workspace::promotion_swap_container_idx`]: ../../komorebi/src/workspace.rs [`WindowManager::resize_delta`]: ../../komorebi/src/window_manager.rs [`Workspace::latest_layout`]: ../../komorebi/src/workspace.rs [`LayoutOptions`]: ../../komorebi/src/core/mod.rs diff --git a/docs/usage/focusing-windows.md b/docs/usage/focusing-windows.md index 599d306f..ee9ed845 100644 --- a/docs/usage/focusing-windows.md +++ b/docs/usage/focusing-windows.md @@ -33,6 +33,11 @@ komorebic cycle-focus next komorebic cycle-focus previous ``` +## The largest tile + +[`komorebic promote-focus`](../cli/promote-focus.md) focuses the window on the first tile of the +layout, which is its largest ([Moving windows](moving-windows.md#to-the-largest-tile)). + ## The pointer By default the pointer moves to the middle of the window that is given the focus. komorebi asks diff --git a/docs/usage/moving-windows.md b/docs/usage/moving-windows.md index 09237554..75010824 100644 --- a/docs/usage/moving-windows.md +++ b/docs/usage/moving-windows.md @@ -32,6 +32,29 @@ komorebic cycle-move next komorebic cycle-move previous ``` +## To the largest tile + +The first tile of a layout is the largest one: the left half in BSP and the vertical stack, the +top half in the horizontal stack, the middle of the ultrawide vertical stack and the right half +in the right main vertical stack. In the columns, rows and scrolling layouts it is the first +column or row. The grid layout is left alone: these commands do nothing there. + +[`komorebic promote`](../cli/promote.md) moves the focused window to the first tile, and the +windows that were before it each move one tile on. +[`komorebic promote-swap`](../cli/promote-swap.md) swaps the focused window with the window on +the first tile instead, and from the first tile swaps it back with the window it was last +swapped with. [`komorebic promote-window`](../cli/promote-window.md) promotes the window on one +side of the focused one. + +```sh +komorebic promote +komorebic promote-swap +komorebic promote-window left +``` + +[`komorebic promote-focus`](../cli/promote-focus.md) gives the focus to the window on the first +tile and moves nothing. + ## The pointer The pointer follows the window that moved, unless diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 8198e213..4ff6ec9d 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -348,6 +348,10 @@ pub enum SocketMessage { CycleMoveWindow(CycleDirection), ResizeWindowEdge(OperationDirection, Sizing), ResizeWindowAxis(Axis, Sizing), + Promote, + PromoteSwap, + PromoteFocus, + PromoteWindow(OperationDirection), // Current Workspace Commands ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 319e058c..9df4f6e8 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -20,6 +20,11 @@ //! of it, or with the next or the previous one, and tile the workspace again //! ([`WindowManager::move_container_in_direction`], //! [`WindowManager::move_container_in_cycle_direction`]). +//! - **Promote** moves the focused container to the largest tile, **PromoteSwap** swaps it with +//! the container there (and back), **PromoteFocus** gives that container the focus, and +//! **PromoteWindow** promotes the container on one side of the focused one +//! ([`WindowManager::promote_container_to_front`], [`WindowManager::promote_container_swap`], +//! [`WindowManager::promote_focus_to_front`]). //! - **ChangeLayout**, **CycleLayout** and **FlipLayout** give the focused workspace another //! layout, or mirror it, and **ToggleTiling** turns its tiling off and on //! ([`WindowManager::change_workspace_layout_default`], [`WindowManager::cycle_layout`], @@ -138,7 +143,7 @@ impl WindowManager { /// [`WindowManager::move_container_in_direction`] and /// [`WindowManager::move_container_in_cycle_direction`] give. /// - There is no focused workspace to change the layout or the tiling of, to preselect a - /// place in, or to resize a container of, or it cannot be tiled again. + /// place in, or to resize or promote a container of, or it cannot be tiled again. /// - The file of `QuickSave` or `Save` cannot be written, or the file of `QuickLoad` or /// `Load` cannot be read or is not a list of resize adjustments. /// - The window manager fails to retile, for one of the reasons @@ -159,6 +164,13 @@ impl WindowManager { let initial_state = State::from(self.as_ref()); match message { + SocketMessage::Promote => self.promote_container_to_front()?, + SocketMessage::PromoteSwap => self.promote_container_swap()?, + SocketMessage::PromoteFocus => self.promote_focus_to_front()?, + SocketMessage::PromoteWindow(direction) => { + self.focus_container_in_direction(direction)?; + self.promote_container_to_front()? + } SocketMessage::FocusWindow(direction) => { self.focus_container_in_direction(direction)?; } diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 0ee1f767..7795aad3 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -90,6 +90,7 @@ impl From<&WindowManager> for State { tile: workspace.tile, globals: workspace.globals, preselected_container_idx: None, + promotion_swap_container_idx: None, }) .collect::>(); ws.focus(monitor.workspaces.focused_idx()); diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 630d9058..7ef9be02 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -606,6 +606,92 @@ impl WindowManager { Ok(()) } + /// Moves the focused container to the first index of the focused workspace, which is the + /// largest tile, and tiles the workspace again: the containers before it each move one index + /// on + /// + /// The grid layout has no largest tile, and nothing changes there. + /// + /// # Errors + /// + /// There is no focused workspace, it has no containers, or it cannot be tiled again. + #[tracing::instrument(skip(self))] + pub fn promote_container_to_front(&mut self) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + + if matches!(workspace.layout, Layout::Default(DefaultLayout::Grid)) { + tracing::debug!("ignoring promote command for grid layout"); + return Ok(()); + } + + tracing::info!("promoting container"); + + workspace.promote_container()?; + self.update_focused_workspace(self.mouse_follows_focus, true) + } + + /// Swaps the focused container with the one at the first index, the largest tile, and tiles + /// the workspace again; when the focused container is the first already, swaps it back with + /// the container it was swapped with last + /// + /// The grid layout has no largest tile, and nothing changes there. + /// + /// # Errors + /// + /// There is no focused workspace, or it cannot be tiled again. + #[tracing::instrument(skip(self))] + pub fn promote_container_swap(&mut self) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + let focused_container_idx = workspace.focused_container_idx(); + + let primary_idx = match workspace.layout { + Layout::Default(_) => 0, + }; + + if matches!(workspace.layout, Layout::Default(DefaultLayout::Grid)) { + tracing::debug!("ignoring promote-swap command for grid layout"); + return Ok(()); + } + + let primary_tile_is_focused = focused_container_idx == primary_idx; + + if primary_tile_is_focused && let Some(swap_idx) = workspace.promotion_swap_container_idx { + workspace.swap_containers(focused_container_idx, swap_idx); + } else { + workspace.promotion_swap_container_idx = Some(focused_container_idx); + workspace.swap_containers(focused_container_idx, primary_idx); + } + + self.update_focused_workspace(self.mouse_follows_focus, true) + } + + /// Gives the focus to the container at the first index, the largest tile, without moving + /// anything + /// + /// The grid layout has no largest tile, and nothing changes there. + /// + /// # Errors + /// + /// There is no focused workspace, or the backend refuses to focus the window. + #[tracing::instrument(skip(self))] + pub fn promote_focus_to_front(&mut self) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + + if matches!(workspace.layout, Layout::Default(DefaultLayout::Grid)) { + tracing::info!("ignoring promote focus command for grid layout"); + return Ok(()); + } + + tracing::info!("promoting focus"); + + let target_idx = match workspace.layout { + Layout::Default(_) => 0, + }; + + workspace.focus_container(target_idx); + self.update_focused_workspace(self.mouse_follows_focus, true) + } + /// Mirrors the layout of the focused workspace along `layout_flip`, on top of the way it is /// mirrored already, and tiles the workspace again /// diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 468a070f..31eecb0b 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -39,6 +39,8 @@ pub struct Workspace { pub globals: WorkspaceGlobals, #[serde(skip_serializing_if = "Option::is_none")] pub preselected_container_idx: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub promotion_swap_container_idx: Option, } impl_ring_elements!(Workspace, Container); @@ -57,6 +59,7 @@ impl Default for Workspace { globals: Default::default(), tile: true, preselected_container_idx: None, + promotion_swap_container_idx: None, } } } @@ -340,6 +343,31 @@ impl Workspace { container } + /// Moves the focused container to the first index, the largest tile in every layout but the + /// grid, and keeps the focus on it + /// + /// # Errors + /// + /// The workspace has no containers. + pub fn promote_container(&mut self) -> eyre::Result<()> { + let focused_idx = self.focused_container_idx(); + let container = self + .containers_mut() + .remove_respecting_locks(focused_idx) + .ok_or_eyre("there is no container")?; + + let primary_idx = match &self.layout { + Layout::Default(_) => 0, + }; + + let insertion_idx = self + .containers_mut() + .insert_respecting_locks(primary_idx, container); + self.focus_container(insertion_idx); + + Ok(()) + } + pub fn add_container_to_back(&mut self, container: Container) { self.containers_mut().push_back(container); self.focus_last_container(); diff --git a/komorebi/tests/promote.rs b/komorebi/tests/promote.rs new file mode 100644 index 00000000..46def693 --- /dev/null +++ b/komorebi/tests/promote.rs @@ -0,0 +1,153 @@ +//! Bringing a window to the largest tile with `promote`, `promote-swap`, `promote-window`, and the +//! focus to it with `promote-focus`, against an in-memory desktop: the messages go in through +//! [`WindowManager::process_command`], and what comes out is the order of the containers, where +//! the backend is asked to put each window, and which window has the focus. +//! +//! Window ids are in the 24_000s. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::DefaultLayout; +use komorebi::core::OperationDirection; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor in `layout`, and a window for +/// each of `ids`, opened in that order. The last one has the focus, and the commands it took to +/// get there are cleared. +fn desktop_with(layout: DefaultLayout, ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmp-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + send(&fake, &mut wm, SocketMessage::ChangeLayout(layout)); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); + } + + fake.clear_commands(); + (fake, wm) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +/// The window of each container of the focused workspace, in order +fn order(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().unwrap().id) + .collect() +} + +fn focused(wm: &WindowManager) -> u32 { + wm.focused_window().unwrap().id +} + +#[test] +fn promote_moves_the_focused_window_to_the_largest_tile_and_the_others_along() { + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &[24_001, 24_002, 24_003]); + let largest = fake.rect_of(24_001); + + send(&fake, &mut wm, SocketMessage::Promote); + + assert_eq!(order(&wm), [24_003, 24_001, 24_002]); + assert_eq!(focused(&wm), 24_003); + assert_eq!(fake.rect_of(24_003), largest); +} + +#[test] +fn promote_swap_swaps_with_the_largest_tile_and_swaps_back() { + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &[24_011, 24_012, 24_013]); + + send(&fake, &mut wm, SocketMessage::PromoteSwap); + + assert_eq!(order(&wm), [24_013, 24_012, 24_011]); + assert_eq!(focused(&wm), 24_013); + + send(&fake, &mut wm, SocketMessage::PromoteSwap); + + assert_eq!( + order(&wm), + [24_011, 24_012, 24_013], + "the largest tile is swapped back" + ); + assert_eq!(focused(&wm), 24_013); +} + +#[test] +fn promote_focus_gives_the_focus_to_the_largest_tile_and_moves_nothing() { + let ids = [24_021, 24_022, 24_023]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let tiles: Vec<_> = ids.iter().map(|&id| fake.rect_of(id)).collect(); + + send(&fake, &mut wm, SocketMessage::PromoteFocus); + + assert_eq!(focused(&wm), 24_021); + assert_eq!(order(&wm), ids); + assert_eq!( + ids.iter().map(|&id| fake.rect_of(id)).collect::>(), + tiles + ); + assert!( + fake.commands().contains(&Command::Focus(24_021, true)), + "{:?}", + fake.commands() + ); +} + +#[test] +fn promote_window_promotes_the_window_on_that_side() { + let (fake, mut wm) = desktop_with(DefaultLayout::Columns, &[24_031, 24_032, 24_033]); + + send( + &fake, + &mut wm, + SocketMessage::PromoteWindow(OperationDirection::Left), + ); + + assert_eq!(order(&wm), [24_032, 24_031, 24_033]); + assert_eq!(focused(&wm), 24_032); +} + +#[test] +fn nothing_is_promoted_in_the_grid_layout() { + let ids = [24_041, 24_042, 24_043]; + let (fake, mut wm) = desktop_with(DefaultLayout::Grid, &ids); + + send(&fake, &mut wm, SocketMessage::Promote); + send(&fake, &mut wm, SocketMessage::PromoteSwap); + send(&fake, &mut wm, SocketMessage::PromoteFocus); + + assert_eq!(order(&wm), ids); + assert_eq!(focused(&wm), 24_043); + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 8fd4942a..d6c65017 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -14,6 +14,8 @@ //! workspace, `scrolling-layout-columns` and `layout-ratios` tune it, `toggle-tiling` turns its //! tiling off and on, and `preselect-direction` and `cancel-preselect` reserve the place of the //! next window and give it up. +//! - `promote`, `promote-swap`, `promote-focus` and `promote-window` bring a window to the largest +//! tile, or the focus to it. //! - `resize-edge` and `resize-axis` resize the focused window by the `resize-delta`, and //! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of //! the tiles of the focused workspace and load them back. @@ -95,6 +97,7 @@ gen_enum_subcommand_args! { // WatchConfiguration: BooleanState, MouseFollowsFocus: BooleanState, Query: StateQuery, + PromoteWindow: OperationDirection, } #[derive(Parser)] @@ -289,6 +292,14 @@ enum SubCommand { /// Flip the layout on the focused workspace #[clap(arg_required_else_help = true)] FlipLayout(FlipLayout), + /// Promote the focused window to the largest tile via container removal and re-insertion + Promote, + /// Promote the focused window to the largest tile by swapping container indices with the largest tile + PromoteSwap, + /// Promote the user focus to the largest window container + PromoteFocus, + /// Promote the window in the specified direction + PromoteWindow(PromoteWindow), /// Force the retiling of all managed windows Retile, /// Toggle window tiling on the focused workspace @@ -451,6 +462,18 @@ fn main() -> eyre::Result<()> { SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } + SubCommand::Promote => { + send_message(&SocketMessage::Promote)?; + } + SubCommand::PromoteSwap => { + send_message(&SocketMessage::PromoteSwap)?; + } + SubCommand::PromoteFocus => { + send_message(&SocketMessage::PromoteFocus)?; + } + SubCommand::PromoteWindow(args) => { + send_message(&SocketMessage::PromoteWindow(args.operation_direction))?; + } SubCommand::ToggleTiling => { send_message(&SocketMessage::ToggleTiling)?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 2e3847a9..1440500b 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -284,6 +284,17 @@ fn the_resize_subcommands_send_what_they_are_given() { ); } +#[test] +fn the_promote_subcommands_send_their_message() { + sends(&["promote"], r#"{"type":"Promote"}"#); + sends(&["promote-swap"], r#"{"type":"PromoteSwap"}"#); + sends(&["promote-focus"], r#"{"type":"PromoteFocus"}"#); + sends( + &["promote-window", "right"], + r#"{"type":"PromoteWindow","content":"Right"}"#, + ); +} + #[test] fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { sends( @@ -355,6 +366,10 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "mouse-follows-focus.md", "move.md", "preselect-direction.md", + "promote-focus.md", + "promote-swap.md", + "promote-window.md", + "promote.md", "query.md", "quick-load-resize.md", "quick-save-resize.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index a29f4dcc..97e240fc 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -165,6 +165,10 @@ resize-axis horizontal increase resize-axis vertical decrease resize-delta 50 resize-delta 100 +promote +promote-swap +promote-focus +promote-window left retile flip-layout horizontal flip-layout vertical From 062fe57fac9095edbf5ba7bea7f07dde3a039f48 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 16:38:57 -0700 Subject: [PATCH 024/255] feat(wm): float Some windows are better left out of the layout. `komorebic toggle-float` takes the window that has the focus out of its container into the floating windows of the workspace, which komorebi gives no tile and does not move, and the other windows share the work area; on a floating window it puts it back in a container at the focused place. A floating window is in the index of managed windows like any other, so its events find it, and it is in the state as the workspace's `floating_windows`. Where a floated window goes is the `toggle_float_placement` of the window management behaviour: by default it stays where it is, since the spike's centering of floated windows waited for a configuration file. Centering and resizing to the floating aspect ratio come with it. Opening windows floating (the float override and the float rules), the floating layer and its own focus and move commands come later. The vm-commands sweep floats a window and puts it back, and its health check counts the floating windows. --- README.md | 7 +- docs/cli/toggle-float.md | 10 ++ docs/dev/ARCHITECTURE.md | 17 ++- docs/dev/vm-tests.md | 4 +- docs/index.md | 5 +- docs/usage/floating-windows.md | 15 ++ komorebi/src/core/mod.rs | 1 + komorebi/src/lib.rs | 7 + komorebi/src/process_command.rs | 6 + komorebi/src/ring.rs | 31 ++++ komorebi/src/state.rs | 1 + komorebi/src/window.rs | 62 +++++++- komorebi/src/window_manager.rs | 198 +++++++++++++++++++++++++ komorebi/src/workspace.rs | 212 ++++++++++++++++++++++++++- komorebi/tests/float.rs | 125 ++++++++++++++++ komorebic/src/main.rs | 6 + komorebic/tests/cli.rs | 2 + nix/tests/vm/lib/komorebi_vm/kde.py | 18 ++- nix/tests/vm/lib/tests/test_kde.py | 18 ++- nix/tests/vm/suites/commands/test.py | 2 + 20 files changed, 718 insertions(+), 29 deletions(-) create mode 100644 docs/cli/toggle-float.md create mode 100644 docs/usage/floating-windows.md create mode 100644 komorebi/tests/float.rs diff --git a/README.md b/README.md index 299f5e2c..35121fdd 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in directory): a message can ask for the state of the window manager, ask which monitor, workspace or container has the focus, give the focus to another window, move the focused window to another tile, change the layout, resize a -tile, retile every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +tile, float a window, retile every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, the command line, is how a person sends them. `komorebic start` runs the `komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma session: @@ -139,8 +139,9 @@ again. `change-layout`, `cycle-layout` and `flip-layout` tile the workspace in another layout, `layout-ratios` and `scrolling-layout-columns` tune it, `toggle-tiling` stops it moving windows and starts it again, `preselect-direction` reserves a tile for the next window, `resize-edge` and -`resize-axis` move the edges of the focused tile, and `promote` brings the -focused window to the largest tile. The scrolling layout +`resize-axis` move the edges of the focused tile, `promote` brings the +focused window to the largest tile, and `toggle-float` takes it out of the +layout. The scrolling layout is a strip of columns that runs past the edges of the monitor and scrolls to the window that has the focus. diff --git a/docs/cli/toggle-float.md b/docs/cli/toggle-float.md new file mode 100644 index 00000000..846dfd87 --- /dev/null +++ b/docs/cli/toggle-float.md @@ -0,0 +1,10 @@ +```text +Toggle floating mode for the focused window + +Usage: toggle-float + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index f656e2fb..a79c3dc1 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -85,7 +85,8 @@ the same thing at every level. - A **monitor** ([`Monitor`]) is one of the backend's monitors: its bounds, its work area, its padding, an optional work area offset, and its workspaces. It shows the focused one. -- A **workspace** ([`Workspace`]) has a layout, its padding, and its containers, in order. +- A **workspace** ([`Workspace`]) has a layout, its padding, its containers, in order, and its + floating windows, which are in no container and which the layout does not tile. - A **container** ([`Container`]) has its windows. A new window gets a container of its own. A container can be locked, which keeps it at its index while others are inserted, removed or swapped around it. @@ -294,6 +295,13 @@ focuses the container at index 0 ([`WindowManager::promote_focus_to_front`]), an `PromoteWindow` focuses the container in a direction and promotes it. On the grid layout they change nothing. +`ToggleFloat` takes the window the compositor has focused out of its container into the +workspace's floating windows, and back into a container of its own at the focused index +([`WindowManager::toggle_float`]). A floating window is in the index of managed windows like +any other, so its events find it, and [`Workspace::update`] leaves it where it is. Where a +floated window goes is [`WindowManagementBehaviour::toggle_float_placement`]: by default it +stays where it is. + `ResizeWindowEdge` and `ResizeWindowAxis` resize the focused container ([`WindowManager::resize_window`]). A resize is an adjustment of the container's tile, kept in [`Workspace::resize_dimensions`], one per container, which the layout applies when it calculates @@ -362,7 +370,7 @@ module's unit. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized window out, move the focus, move the focused container, change the layout, resize or - promote the focused container). + promote the focused container, float a window). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -563,7 +571,8 @@ A window is shown, and ends up on a tile: [`komorebi/tests/layout_options.rs`](../../komorebi/tests/layout_options.rs) and [`komorebi/tests/scrolling.rs`](../../komorebi/tests/scrolling.rs), the layout options and the scrolling layout; [`komorebi/tests/resize.rs`](../../komorebi/tests/resize.rs), resizing; - [`komorebi/tests/promote.rs`](../../komorebi/tests/promote.rs), promoting. + [`komorebi/tests/promote.rs`](../../komorebi/tests/promote.rs), promoting; + [`komorebi/tests/float.rs`](../../komorebi/tests/float.rs), floating. - [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, @@ -603,6 +612,8 @@ A window is shown, and ends up on a tile: [`Workspace::layout_options`]: ../../komorebi/src/workspace.rs [`Workspace::resize_dimensions`]: ../../komorebi/src/workspace.rs [`WindowManager::resize_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::toggle_float`]: ../../komorebi/src/window_manager.rs +[`WindowManagementBehaviour::toggle_float_placement`]: ../../komorebi/src/core/mod.rs [`WindowManager::promote_container_to_front`]: ../../komorebi/src/window_manager.rs [`WindowManager::promote_container_swap`]: ../../komorebi/src/window_manager.rs [`WindowManager::promote_focus_to_front`]: ../../komorebi/src/window_manager.rs diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index dbd17385..b45e243b 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -127,8 +127,8 @@ the run. printed, failing the test if it fails. `state()` is the daemon's state as `komorebic state` prints it, `managed(workspace)` the number of windows the daemon has on a workspace of the first monitor, `managed_all()` the number it - has on every workspace of every monitor, and `focused_title(workspace)` the - title of the window it has focused there. + has on every workspace of every monitor (floating windows too), and + `focused_title(workspace)` the title of the window it has focused there. - `daemon` reads the daemon's view of the desktop from that log, at the debug level the nodes set: `daemon.events(log)` lists the window events it handled, in order, `daemon.window_ids(log)` maps a window's title to the daemon's id diff --git a/docs/index.md b/docs/index.md index 6a2a93a4..77226bf8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -34,8 +34,9 @@ anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to sta daemon, ask it what it is doing and read its log. [Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window, [Moving windows](usage/moving-windows.md) how to move the focused window to another tile, -[Layouts](usage/layouts.md) how to change the arrangement of the tiles, and -[Resizing windows](usage/resizing-windows.md) how to change the size of one. +[Layouts](usage/layouts.md) how to change the arrangement of the tiles, +[Resizing windows](usage/resizing-windows.md) how to change the size of one, and +[Floating windows](usage/floating-windows.md) how to take a window out of the layout. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/floating-windows.md b/docs/usage/floating-windows.md new file mode 100644 index 00000000..83b44797 --- /dev/null +++ b/docs/usage/floating-windows.md @@ -0,0 +1,15 @@ +# Floating windows + +A floating window is one of a workspace's windows that is not in its layout: komorebi gives it no +tile and does not move it, and it stays where it is put by hand. + +[`komorebic toggle-float`](../cli/toggle-float.md) takes the window that has the focus out of the +layout, and the other windows of the workspace share the work area. The same command on a +floating window puts it back in the layout, at the place of the focused window. + +```sh +komorebic toggle-float +``` + +A floated window keeps its size and position by default. The floating windows of a workspace are +in the daemon's state as `floating_windows`, next to its containers. diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 4ff6ec9d..6917ca94 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -352,6 +352,7 @@ pub enum SocketMessage { PromoteSwap, PromoteFocus, PromoteWindow(OperationDirection), + ToggleFloat, // Current Workspace Commands ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 79d8ade2..a7397297 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -24,6 +24,8 @@ use crate::core::SocketMessage; use crate::core::SubscribeOptions; use crate::state::State; +use crate::window::AspectRatio; +use crate::window::PredefinedAspectRatio; use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; use lazy_static::lazy_static; @@ -88,6 +90,11 @@ lazy_static! { /// same name, without options, keeps the options it had. pub static ref SUBSCRIPTION_SOCKET_OPTIONS: Arc>> = Arc::new(Mutex::new(HashMap::new())); + /// The aspect ratio a window that is floated by `ToggleFloat` is given when the placement of + /// floated windows centers and resizes them + static ref FLOATING_WINDOW_TOGGLE_ASPECT_RATIO: Arc> = Arc::new(Mutex::new( + AspectRatio::Predefined(PredefinedAspectRatio::Widescreen) + )); } /// The padding, in pixels, between the edge of a monitor's work area and the tiles of its diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 9df4f6e8..ea47fb34 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -37,6 +37,9 @@ //! already, and **CancelPreselect** gives the reserved place up. //! - **MouseFollowsFocus** and **ToggleMouseFollowsFocus** set whether the pointer is moved to //! the window that is given the focus. +//! - **ToggleFloat** takes the focused window out of the layout into the floating windows of the +//! workspace, which komorebi does not move, or puts a floating window back +//! ([`WindowManager::toggle_float`]). //! - **ResizeWindowEdge** and **ResizeWindowAxis** resize the focused container by the //! [`WindowManager::resize_delta`] that **ResizeDelta** sets ([`WindowManager::resize_window`]), //! and **QuickSave**, **QuickLoad**, **Save** and **Load** write the resize adjustments of the @@ -144,6 +147,8 @@ impl WindowManager { /// [`WindowManager::move_container_in_cycle_direction`] give. /// - There is no focused workspace to change the layout or the tiling of, to preselect a /// place in, or to resize or promote a container of, or it cannot be tiled again. + /// - The focused window cannot be floated or put back, for one of the reasons + /// [`WindowManager::toggle_float`] gives. /// - The file of `QuickSave` or `Save` cannot be written, or the file of `QuickLoad` or /// `Load` cannot be read or is not a list of resize adjustments. /// - The window manager fails to retile, for one of the reasons @@ -205,6 +210,7 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::ToggleFloat => self.toggle_float(false)?, SocketMessage::ResizeWindowEdge(direction, sizing) => { self.resize_window(direction, sizing, self.resize_delta, true)?; } diff --git a/komorebi/src/ring.rs b/komorebi/src/ring.rs index cab51c2a..ae8b2f25 100644 --- a/komorebi/src/ring.rs +++ b/komorebi/src/ring.rs @@ -109,6 +109,37 @@ macro_rules! impl_ring_elements { } } } + }; // This allows passing a different name to be used for the functions. For instance, the + // `floating_windows` ring calls this as: + // ```rust + // impl_ring_elements!(Workspace, Window, "floating_window"); + // ``` + // Which allows using the `Window` element but name the functions as `floating_window` + ($name:ty, $element:ident, $el_name:literal) => { + pastey::paste! { + impl $name { + pub const fn [<$el_name:lower s>](&self) -> &std::collections::VecDeque<$element> { + self.[<$el_name:lower s>].elements() + } + + pub fn [<$el_name:lower s_mut>](&mut self) -> &mut std::collections::VecDeque<$element> { + self.[<$el_name:lower s>].elements_mut() + } + + #[allow(dead_code)] + pub fn [](&self) -> Option<&$element> { + self.[<$el_name:lower s>].focused() + } + + pub const fn [](&self) -> usize { + self.[<$el_name:lower s>].focused_idx() + } + + pub fn [](&mut self) -> Option<&mut $element> { + self.[<$el_name:lower s>].focused_mut() + } + } + } }; } diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 7795aad3..9d497d84 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -80,6 +80,7 @@ impl From<&WindowManager> for State { .iter() .map(|workspace| Workspace { containers: workspace.containers.clone(), + floating_windows: workspace.floating_windows.clone(), layout: workspace.layout.clone(), layout_options: workspace.layout_options, layout_flip: workspace.layout_flip, diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 76e42f74..e51cb942 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -6,6 +6,7 @@ //! focus, a close) is a command to the backend. Nothing is cached, so a window that changed its //! title, or closed, is seen as it is now. +use crate::FLOATING_WINDOW_TOGGLE_ASPECT_RATIO; use crate::backend::backend; use crate::core::Rect; use color_eyre::eyre; @@ -18,6 +19,8 @@ use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write; use std::path::PathBuf; +use strum::Display; +use strum::EnumString; /// A handle to a window on the desktop: just its id. /// @@ -191,13 +194,21 @@ impl Window { backend().unminimize(self.id) } - /// Moves the window to the middle of `work_area`, keeping its size + /// Moves the window to the middle of `work_area`, keeping its size, or with `resize` making it + /// half as high as the work area and as wide as the aspect ratio of floating windows says /// /// # Errors /// /// The backend does not know the window, or refuses to move it. - pub fn center(&mut self, work_area: &Rect) -> eyre::Result<()> { - let (target_width, target_height) = { + pub fn center(&mut self, work_area: &Rect, resize: bool) -> eyre::Result<()> { + let (target_width, target_height) = if resize { + let (aspect_ratio_width, aspect_ratio_height) = FLOATING_WINDOW_TOGGLE_ASPECT_RATIO + .lock() + .width_and_height(); + let target_height = work_area.bottom / 2; + let target_width = (target_height * aspect_ratio_width) / aspect_ratio_height; + (target_width, target_height) + } else { let current_rect = self.rect()?; (current_rect.right, current_rect.bottom) }; @@ -234,6 +245,51 @@ impl Window { } } +#[derive(Copy, Clone, Debug, Display, EnumString, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +/// Aspect ratio for temporarily floating windows +pub enum AspectRatio { + /// A predefined aspect ratio + #[cfg_attr(feature = "schemars", schemars(title = "Predefined"))] + Predefined(PredefinedAspectRatio), + /// A custom W:H aspect ratio + #[cfg_attr(feature = "schemars", schemars(title = "Custom"))] + Custom(i32, i32), +} + +impl Default for AspectRatio { + fn default() -> Self { + AspectRatio::Predefined(PredefinedAspectRatio::default()) + } +} + +#[derive(Copy, Clone, Debug, Default, Display, EnumString, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Predefined aspect ratio +pub enum PredefinedAspectRatio { + /// 21:9 + Ultrawide, + /// 16:9 + Widescreen, + /// 4:3 + #[default] + Standard, +} + +impl AspectRatio { + pub fn width_and_height(self) -> (i32, i32) { + match self { + AspectRatio::Predefined(predefined) => match predefined { + PredefinedAspectRatio::Ultrawide => (21, 9), + PredefinedAspectRatio::Widescreen => (16, 9), + PredefinedAspectRatio::Standard => (4, 3), + }, + AspectRatio::Custom(w, h) => (w, h), + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 7ef9be02..d511cc33 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -29,6 +29,7 @@ use crate::core::Layout; use crate::core::OperationDirection; use crate::core::Rect; use crate::core::Sizing; +use crate::core::WindowManagementBehaviour; use crate::desktop; use crate::monitor::Monitor; use crate::ring::Ring; @@ -58,6 +59,8 @@ pub struct WindowManager { pub command_listener: UnixListener, /// How many pixels `ResizeWindowEdge` and `ResizeWindowAxis` resize by pub resize_delta: i32, + /// How new and floated windows are placed: `ToggleFloat` reads its `toggle_float_placement` + pub window_management_behaviour: WindowManagementBehaviour, /// Whether the pointer is moved to the window that is given the focus, which is the default pub mouse_follows_focus: bool, pub work_area_offset: Option, @@ -111,6 +114,7 @@ impl WindowManager { monitors: Ring::default(), command_listener: listener, resize_delta: 50, + window_management_behaviour: WindowManagementBehaviour::default(), mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -406,6 +410,88 @@ impl WindowManager { std::process::exit(0) } + /// Takes the window that has the focus in the compositor out of the layout of the focused + /// workspace, or puts it back when it is one of its floating windows and `force_float` is not + /// set, and tiles the workspace again + /// + /// # Errors + /// + /// - The compositor reports no focused window. + /// - There is no focused workspace, or the window cannot be floated or put back, for one of + /// the reasons [`WindowManager::float_window`] and [`WindowManager::unfloat_window`] give. + /// - The workspace cannot be tiled again. + #[tracing::instrument(skip(self))] + pub fn toggle_float(&mut self, force_float: bool) -> eyre::Result<()> { + let window_id = backend() + .foreground_window() + .ok_or_eyre("no foreground window")?; + + let workspace = self.focused_workspace_mut()?; + + let mut is_floating_window = false; + + for window in workspace.floating_windows() { + if window.id == window_id { + is_floating_window = true; + } + } + + if is_floating_window && !force_float { + self.unfloat_window()?; + } else { + self.float_window()?; + } + + self.update_focused_workspace(is_floating_window, true) + } + + /// Takes the focused window out of its container into the floating windows of the focused + /// workspace ([`Workspace::new_floating_window`]), places it as + /// [`WindowManagementBehaviour::toggle_float_placement`] says, and gives it the focus + /// + /// # Errors + /// + /// There is no focused monitor, workspace, container or window, or the backend refuses to + /// move or focus the window. + #[tracing::instrument(skip(self))] + pub fn float_window(&mut self) -> eyre::Result<()> { + tracing::info!("floating window"); + + let mouse_follows_focus = self.mouse_follows_focus; + let work_area = self.focused_monitor_work_area()?; + + let toggle_float_placement = self.window_management_behaviour.toggle_float_placement; + + let workspace = self.focused_workspace_mut()?; + workspace.new_floating_window()?; + + let window = workspace + .floating_windows_mut() + .back_mut() + .ok_or_eyre("there is no floating window")?; + + if toggle_float_placement.should_center() { + window.center(&work_area, toggle_float_placement.should_resize())?; + } + window.focus(mouse_follows_focus)?; + + Ok(()) + } + + /// Puts the floating window that has the focus in the compositor back in the layout of the + /// focused workspace ([`Workspace::new_container_for_floating_window`]) + /// + /// # Errors + /// + /// There is no focused workspace, or the focused window is not one of its floating windows. + #[tracing::instrument(skip(self))] + pub fn unfloat_window(&mut self) -> eyre::Result<()> { + tracing::info!("unfloating window"); + + let workspace = self.focused_workspace_mut()?; + workspace.new_container_for_floating_window() + } + /// Resizes the focused container by `delta` pixels on its `direction` side, by giving it a /// resize adjustment that the layout applies, and tiles the workspace again if `update` is set /// @@ -854,6 +940,10 @@ impl WindowManager { known_window_ids.insert(window.id, (m_idx, w_idx)); } } + + for window in workspace.floating_windows() { + known_window_ids.insert(window.id, (m_idx, w_idx)); + } } } @@ -1120,4 +1210,112 @@ mod tests { assert_eq!(wm.minimized_windows.get(&631), Some(&Window::from(631))); Ok(()) } + + #[test] + fn test_float_window() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let mut container = Container::default(); + + // Add three windows to the container + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + + // Should have 3 windows in the container + assert_eq!(container.windows().len(), 3); + + // Add the container to the workspace + let workspace = m.focused_workspace_mut().unwrap(); + workspace.add_container_to_back(container); + + // Add monitor to the window manager + wm.monitors_mut().push_back(m); + } + + // Add focused window to floating window list + wm.float_window().ok(); + + { + let workspace = wm.focused_workspace().unwrap(); + let floating_windows = workspace.floating_windows(); + let container = workspace.focused_container().unwrap(); + + // Hwnd 0 should be added to floating_windows + assert_eq!(floating_windows[0].id, 0); + + // Should have a length of 1 + assert_eq!(floating_windows.len(), 1); + + // Should have 2 windows in the container + assert_eq!(container.windows().len(), 2); + + // Should be focused on window 1 + assert_eq!(container.focused_window().unwrap().id, 1); + } + + // Add focused window to floating window list + wm.float_window().ok(); + + { + let workspace = wm.focused_workspace().unwrap(); + let floating_windows = workspace.floating_windows(); + let container = workspace.focused_container().unwrap(); + + // Hwnd 1 should be added to floating_windows + assert_eq!(floating_windows[1].id, 1); + + // Should have a length of 2 + assert_eq!(floating_windows.len(), 2); + + // Should have 1 window in the container + assert_eq!(container.windows().len(), 1); + + // Should be focused on window 2 + assert_eq!(container.focused_window().unwrap().id, 2); + } + } + + #[test] + fn test_float_nonexistent_window() { + let (mut wm, _context) = setup_window_manager(); + + { + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add another workspace + let new_workspace_index = m.new_workspace_idx(); + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Add monitor to window manager + wm.monitors_mut().push_back(m); + } + + // Should return an error when trying to float a non-existent window + let result = wm.float_window(); + assert!( + result.is_err(), + "Expected an error when trying to float a non-existent window" + ); + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 31eecb0b..61f48c14 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -5,6 +5,7 @@ //! container on its tile with [`Window::set_position`]. The work area and the padding a workspace //! falls back to come from the monitor it is on ([`WorkspaceGlobals`]). +use crate::backend::backend; use crate::container::Container; use crate::core::Axis; use crate::core::CycleDirection; @@ -27,6 +28,7 @@ use std::num::NonZeroUsize; #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Workspace { pub containers: Ring, + pub floating_windows: Ring, pub layout: Layout, pub layout_options: Option, pub layout_flip: Option, @@ -44,6 +46,7 @@ pub struct Workspace { } impl_ring_elements!(Workspace, Container); +impl_ring_elements!(Workspace, Window, "floating_window"); impl Default for Workspace { fn default() -> Self { @@ -58,6 +61,7 @@ impl Default for Workspace { layout_options: None, globals: Default::default(), tile: true, + floating_windows: Default::default(), preselected_container_idx: None, promotion_swap_container_idx: None, } @@ -225,6 +229,7 @@ impl Workspace { pub fn prune_duplicate_windows(&mut self) -> eyre::Result<()> { let mut tracker = HashMap::new(); let mut to_prune_from_containers = vec![]; + let mut to_prune_from_floating = vec![]; for container in self.containers() { for window in container.windows() { @@ -244,6 +249,22 @@ impl Workspace { tracker.remove(&id); } + for window in self.floating_windows() { + let entry = tracker.entry(window.id).or_insert(0); + *entry += 1; + } + + for (window_id, count) in &tracker { + if *count > 1 { + to_prune_from_floating.push(*window_id); + } + } + + for id in to_prune_from_floating { + self.remove_window(id)?; + tracker.remove(&id); + } + Ok(()) } @@ -251,6 +272,7 @@ impl Workspace { #[tracing::instrument(skip(self))] pub fn reap_invalid_windows(&mut self) -> eyre::Result { let mut invalid_window_ids = vec![]; + let mut invalid_floating_window_ids = vec![]; for container in self.containers() { for window in container.windows() { @@ -260,13 +282,25 @@ impl Workspace { } } + for window in self.floating_windows() { + if !window.is_valid() { + invalid_floating_window_ids.push(window.id); + } + } + for window_id in &invalid_window_ids { let _ = self.remove_window(*window_id); } - tracing::debug!("reaping invalid windows {invalid_window_ids:?}"); + for window_id in &invalid_floating_window_ids { + self.remove_floating_window(*window_id); + } - Ok(invalid_window_ids.len()) + tracing::debug!( + "reaping invalid windows {invalid_window_ids:?} {invalid_floating_window_ids:?}" + ); + + Ok(invalid_window_ids.len() + invalid_floating_window_ids.len()) } pub fn remove_window(&mut self, window_id: u32) -> eyre::Result { @@ -315,7 +349,7 @@ impl Workspace { } pub fn is_empty(&self) -> bool { - self.containers().is_empty() + self.containers().is_empty() && self.floating_windows().is_empty() } pub fn contains_window(&self, window_id: u32) -> bool { @@ -325,6 +359,12 @@ impl Workspace { } } + for window in self.floating_windows() { + if window_id == window.id { + return true; + } + } + false } @@ -385,6 +425,97 @@ impl Workspace { fn focus_first_container(&mut self) { self.focus_container(0); } + + /// Takes the focused window out of its container, and out of the layout, into the floating + /// windows of the workspace; a container that is left with no window is removed + /// + /// # Errors + /// + /// The workspace has no containers, or the focused one has no window. + pub fn new_floating_window(&mut self) -> eyre::Result<()> { + let window = { + let focused_idx = self.focused_container_idx(); + + let container = self + .focused_container_mut() + .ok_or_eyre("there is no container")?; + + let window = container + .remove_focused_window() + .ok_or_eyre("there is no window")?; + + if container.windows().is_empty() { + self.remove_container_by_idx(focused_idx); + + if focused_idx == self.containers().len() { + self.focus_container(focused_idx.saturating_sub(1)); + } + } + + window + }; + + self.floating_windows_mut().push_back(window); + + Ok(()) + } + + /// Puts the floating window that has the focus in the compositor back in the layout, in a + /// container of its own at the index of the focused container + /// + /// # Errors + /// + /// The window the compositor has focused is not a floating window of the workspace. + pub fn new_container_for_floating_window(&mut self) -> eyre::Result<()> { + let focused_idx = self.focused_container_idx(); + let window = self + .remove_focused_floating_window() + .ok_or_eyre("there is no floating window")?; + + let mut container = Container::default(); + container.add_window(&window)?; + + self.insert_container_at_idx(focused_idx, container); + + Ok(()) + } + + pub fn remove_focused_floating_window(&mut self) -> Option { + let window_id = backend().foreground_window()?; + self.remove_floating_window(window_id) + } + + pub fn remove_floating_window(&mut self, window_id: u32) -> Option { + let mut idx = None; + for (i, window) in self.floating_windows().iter().enumerate() { + if window_id == window.id { + idx = Option::from(i); + } + } + + match idx { + None => None, + Some(idx) => { + if self.floating_windows().get(idx).is_some() { + self.focus_previous_floating_window(); + self.floating_windows_mut().remove(idx) + } else { + None + } + } + } + } + + pub fn focus_previous_floating_window(&mut self) { + let focused_idx = self.focused_floating_window_idx(); + self.focus_floating_window(focused_idx.saturating_sub(1)); + } + + pub fn focus_floating_window(&mut self, idx: usize) { + tracing::info!("focusing floating window"); + + self.floating_windows.focus(idx); + } } impl Workspace { @@ -509,7 +640,7 @@ impl Workspace { && resize_dimensions_is_empty; if percentage_override { - window.center(&work_area)?; + window.center(&work_area, false)?; } else if let Err(error) = window.set_position(layout) { tracing::warn!("failed to set window position: {error}") } @@ -887,6 +1018,45 @@ mod tests { assert_eq!(ws.containers()[2].focused_window().unwrap().id, 3); } + #[test] + fn test_locked_containers_toggle_float() { + let mut ws = Workspace::default(); + + // add 4 containers + for i in 0..4 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + if i == 1 { + container.locked = true; + } + ws.add_container_to_back(container); + } + assert_eq!(ws.containers().len(), 4); + + // set index 0 focused + ws.focus_container(0); + + // float index 0 + ws.new_floating_window().unwrap(); + + assert_eq!(ws.containers()[0].focused_window().unwrap().id, 2); + // index 1 should still be the same + assert_eq!(ws.containers()[1].focused_window().unwrap().id, 1); + assert_eq!(ws.containers()[2].focused_window().unwrap().id, 3); + + // unfloat - have to do this semi-manually becuase of calls to WindowsApi in + // new_container_for_floating_window which usually handles unfloating + let window = ws.floating_windows_mut().pop_back().unwrap(); + let mut container = Container::default(); + container.add_window(&window).unwrap(); + ws.insert_container_at_idx(ws.focused_container_idx(), container); + + // all indexes should be at their original position + for i in 0..4 { + assert_eq!(ws.containers()[i].focused_window().unwrap().id, i as u32); + } + } + #[test] fn test_contains_window() { // Create default workspace @@ -1350,6 +1520,40 @@ mod tests { assert_eq!(focused_container.focused_window_idx(), 1); } + #[test] + fn test_new_floating_window() { + let mut workspace = Workspace::default(); + + { + // Container with 3 windows + let mut container = Container::default(); + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + workspace.add_container_to_back(container); + } + + // Add window to floating_windows + workspace.new_floating_window().ok(); + + // Should have 1 floating window + assert_eq!(workspace.floating_windows().len(), 1); + + // Should have only 2 windows now + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 2); + + // Should contain hwnd 0 since this is the first window in the container + let floating_windows = workspace.floating_windows_mut(); + let mut contains = false; + for w in floating_windows { + if w.id == 0 { + contains = true; + } + } + assert!(contains); + } + #[test] fn test_layout_boundary_clamping() { use crate::core::Rect; diff --git a/komorebi/tests/float.rs b/komorebi/tests/float.rs new file mode 100644 index 00000000..1e13d738 --- /dev/null +++ b/komorebi/tests/float.rs @@ -0,0 +1,125 @@ +//! Floating a window with `toggle-float`, against an in-memory desktop: the messages go in +//! through [`WindowManager::process_command`], and what comes out is which windows the layout +//! tiles and where the backend is asked to put them. +//! +//! Window ids are in the 25_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel), +/// and a window for each of `ids`, opened in that order. The last one has the focus. +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmt-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + wm + }); + + (fake, wm) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn tiled(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().unwrap().id) + .collect() +} + +fn floating(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .floating_windows() + .iter() + .map(|window| window.id) + .collect() +} + +#[test] +fn toggle_float_takes_the_focused_window_out_of_the_layout_and_puts_it_back() { + let (fake, mut wm) = desktop_with(&[25_001, 25_002]); + let half = fake.rect_of(25_001).unwrap(); + + send(&fake, &mut wm, SocketMessage::ToggleFloat); + + assert_eq!(tiled(&wm), [25_001]); + assert_eq!(floating(&wm), [25_002]); + assert!( + fake.rect_of(25_001).unwrap().right > half.right, + "the window left in the layout has the work area" + ); + assert!(wm.focused_workspace().unwrap().contains_window(25_002)); + + send(&fake, &mut wm, SocketMessage::ToggleFloat); + + assert_eq!(tiled(&wm), [25_002, 25_001]); + assert!(floating(&wm).is_empty()); +} + +#[test] +fn a_floating_window_is_left_where_it_is_by_a_retile() { + let (fake, mut wm) = desktop_with(&[25_011, 25_012]); + send(&fake, &mut wm, SocketMessage::ToggleFloat); + let by_hand = Rect { + left: 300, + top: 200, + right: 640, + bottom: 480, + }; + fake.move_window_by_user(25_012, by_hand); + + send(&fake, &mut wm, SocketMessage::Retile); + + assert_eq!(fake.rect_of(25_012), Some(by_hand)); +} + +#[test] +fn toggle_float_without_a_focused_window_is_an_error() { + let (fake, mut wm) = desktop_with(&[25_021]); + fake.set_foreground(None); + + let result = with_backend(fake.clone(), || { + wm.process_command(SocketMessage::ToggleFloat, Vec::new()) + }); + + assert_eq!( + result.map_err(|error| error.to_string()), + Err(String::from("no foreground window")) + ); + assert_eq!(tiled(&wm), [25_021]); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index d6c65017..45d75e63 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -16,6 +16,7 @@ //! next window and give it up. //! - `promote`, `promote-swap`, `promote-focus` and `promote-window` bring a window to the largest //! tile, or the focus to it. +//! - `toggle-float` takes the focused window out of the layout, or puts it back. //! - `resize-edge` and `resize-axis` resize the focused window by the `resize-delta`, and //! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of //! the tiles of the focused workspace and load them back. @@ -304,6 +305,8 @@ enum SubCommand { Retile, /// Toggle window tiling on the focused workspace ToggleTiling, + /// Toggle floating mode for the focused window + ToggleFloat, /// Enable or disable mouse follows focus on all workspaces #[clap(arg_required_else_help = true)] MouseFollowsFocus(MouseFollowsFocus), @@ -453,6 +456,9 @@ fn main() -> eyre::Result<()> { SubCommand::FlipLayout(args) => { send_message(&SocketMessage::FlipLayout(args.axis))?; } + SubCommand::ToggleFloat => { + send_message(&SocketMessage::ToggleFloat)?; + } SubCommand::ResizeEdge(args) => { send_message(&SocketMessage::ResizeWindowEdge(args.edge, args.sizing))?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 1440500b..1b856f63 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -209,6 +209,7 @@ fn the_layout_subcommands_send_the_layout_axis_or_direction_they_are_given() { r#"{"type":"FlipLayout","content":"HorizontalAndVertical"}"#, ); sends(&["toggle-tiling"], r#"{"type":"ToggleTiling"}"#); + sends(&["toggle-float"], r#"{"type":"ToggleFloat"}"#); sends( &["preselect-direction", "up"], r#"{"type":"PreselectDirection","content":"Up"}"#, @@ -383,6 +384,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "state.md", "stop.md", "subscribe-socket.md", + "toggle-float.md", "toggle-mouse-follows-focus.md", "toggle-tiling.md", "unsubscribe-socket.md", diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index 17960b28..be3a9f55 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -289,13 +289,17 @@ class Kde: return sum(len(container["windows"]["elements"]) for container in containers) def managed_all(self) -> int: - """The number of windows the daemon has, in the containers of every workspace it has.""" - return sum( - len(container["windows"]["elements"]) - for monitor in self.state()["monitors"]["elements"] - for workspace in monitor["workspaces"]["elements"] - for container in workspace["containers"]["elements"] - ) + """The number of windows the daemon has, on every workspace of every monitor. + + That is the windows of the containers, and the floating windows. + """ + total = 0 + for monitor in self.state()["monitors"]["elements"]: + for workspace in monitor["workspaces"]["elements"]: + for container in workspace["containers"]["elements"]: + total += len(container["windows"]["elements"]) + total += len(workspace["floating_windows"]["elements"]) + return total def monitor_bridge(self, path: str) -> None: """Starts recording the bridge's traffic on the session bus to `path`, in the background. diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index cc684f7e..22195438 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -349,8 +349,13 @@ def container(*titles: str, focused: int = 0) -> dict[str, object]: } -def workspace(*containers: dict[str, object], focused: int = 0) -> dict[str, object]: - return {"containers": {"elements": list(containers), "focused": focused}} +def workspace( + *containers: dict[str, object], focused: int = 0, floating: tuple[str, ...] = () +) -> dict[str, object]: + return { + "containers": {"elements": list(containers), "focused": focused}, + "floating_windows": {"elements": [window(t) for t in floating], "focused": 0}, + } def a_state(*workspaces: dict[str, object]) -> str: @@ -381,10 +386,13 @@ def test_managed_counts_the_windows_of_every_container_of_the_workspace( assert kde.managed(1) == 1 -def test_managed_all_counts_the_windows_of_every_workspace_of_every_monitor( +def test_managed_all_counts_the_windows_and_the_floating_windows_of_every_workspace( machine: FakeMachine, ) -> None: - first = {"id": 1, "workspaces": {"elements": [workspace(container("a", "b"))], "focused": 0}} + first = { + "id": 1, + "workspaces": {"elements": [workspace(container("a", "b"), floating=("f",))], "focused": 0}, + } second = { "id": 2, "workspaces": {"elements": [workspace(container("c")), workspace()], "focused": 0}, @@ -394,7 +402,7 @@ def test_managed_all_counts_the_windows_of_every_workspace_of_every_monitor( output=json.dumps({"monitors": {"elements": [first, second], "focused": 0}}), ) - assert Kde(machine, "main").managed_all() == 3 + assert Kde(machine, "main").managed_all() == 4 def test_managed_is_zero_for_a_workspace_without_containers(machine: FakeMachine) -> None: diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 97e240fc..41332fbf 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -182,6 +182,8 @@ scrolling-layout-columns 2 change-layout bsp preselect-direction left cancel-preselect +toggle-float +toggle-float toggle-tiling toggle-tiling mouse-follows-focus enable From 3cc5dceb7d7d36cbd67014763df6b8e2e02ea49d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 16:44:42 -0700 Subject: [PATCH 025/255] feat(wm): lock Containers can be locked since the model came in, and a locked container keeps its index while others are inserted, removed or swapped around it; nothing could lock one. `komorebic toggle-lock` locks the focused container, or unlocks it, and the `LockMonitorWorkspaceContainer` and `UnlockMonitorWorkspaceContainer` messages lock and unlock a container by the index of its monitor, its workspace and itself, for a program such as a status bar. The vm-commands sweep locks and unlocks a container. --- README.md | 4 +- docs/cli/toggle-lock.md | 10 ++ docs/dev/ARCHITECTURE.md | 13 ++- docs/usage/moving-windows.md | 16 +++ komorebi/src/core/mod.rs | 3 + komorebi/src/process_command.rs | 45 ++++++++ komorebi/src/window_manager.rs | 70 ++++++++++++ komorebi/tests/lock.rs | 158 +++++++++++++++++++++++++++ komorebic/src/main.rs | 8 +- komorebic/tests/cli.rs | 2 + nix/tests/vm/suites/commands/test.py | 2 + 11 files changed, 325 insertions(+), 6 deletions(-) create mode 100644 docs/cli/toggle-lock.md create mode 100644 komorebi/tests/lock.rs diff --git a/README.md b/README.md index 35121fdd..7b0828c3 100644 --- a/README.md +++ b/README.md @@ -140,8 +140,8 @@ another layout, `layout-ratios` and `scrolling-layout-columns` tune it, `toggle-tiling` stops it moving windows and starts it again, `preselect-direction` reserves a tile for the next window, `resize-edge` and `resize-axis` move the edges of the focused tile, `promote` brings the -focused window to the largest tile, and `toggle-float` takes it out of the -layout. The scrolling layout +focused window to the largest tile, `toggle-float` takes it out of the +layout, and `toggle-lock` keeps its container at its place. The scrolling layout is a strip of columns that runs past the edges of the monitor and scrolls to the window that has the focus. diff --git a/docs/cli/toggle-lock.md b/docs/cli/toggle-lock.md new file mode 100644 index 00000000..bb079116 --- /dev/null +++ b/docs/cli/toggle-lock.md @@ -0,0 +1,10 @@ +```text +Toggle a lock for the focused container, ensuring it will not be displaced by any new windows + +Usage: toggle-lock + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index a79c3dc1..00d68065 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -302,6 +302,11 @@ any other, so its events find it, and [`Workspace::update`] leaves it where it i floated window goes is [`WindowManagementBehaviour::toggle_float_placement`]: by default it stays where it is. +`ToggleLock` locks the focused container, or unlocks it ([`WindowManager::toggle_lock`]), and +`LockMonitorWorkspaceContainer` and `UnlockMonitorWorkspaceContainer` do the same for a +container given by its indices. A lock changes nothing until containers are inserted, removed or +swapped around it, which the workspace does through `LockableSequence`. + `ResizeWindowEdge` and `ResizeWindowAxis` resize the focused container ([`WindowManager::resize_window`]). A resize is an adjustment of the container's tile, kept in [`Workspace::resize_dimensions`], one per container, which the layout applies when it calculates @@ -370,7 +375,7 @@ module's unit. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized window out, move the focus, move the focused container, change the layout, resize or - promote the focused container, float a window). + promote the focused container, float a window, lock a container). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -434,7 +439,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | The window manager asks for a backend that was never installed | runtime error: [`backend`] panics, naming [`set_backend`] and [`with_backend`] | `# Panics` on [`backend`] | none | | A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none | | A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none | -| 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 locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window`, `test_locked_containers_remove_window`, `a_window_that_opens_does_not_push_a_locked_container_from_its_index` | `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 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` | @@ -572,7 +577,8 @@ A window is shown, and ends up on a tile: [`komorebi/tests/scrolling.rs`](../../komorebi/tests/scrolling.rs), the layout options and the scrolling layout; [`komorebi/tests/resize.rs`](../../komorebi/tests/resize.rs), resizing; [`komorebi/tests/promote.rs`](../../komorebi/tests/promote.rs), promoting; - [`komorebi/tests/float.rs`](../../komorebi/tests/float.rs), floating. + [`komorebi/tests/float.rs`](../../komorebi/tests/float.rs), floating; + [`komorebi/tests/lock.rs`](../../komorebi/tests/lock.rs), locking. - [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, @@ -613,6 +619,7 @@ A window is shown, and ends up on a tile: [`Workspace::resize_dimensions`]: ../../komorebi/src/workspace.rs [`WindowManager::resize_window`]: ../../komorebi/src/window_manager.rs [`WindowManager::toggle_float`]: ../../komorebi/src/window_manager.rs +[`WindowManager::toggle_lock`]: ../../komorebi/src/window_manager.rs [`WindowManagementBehaviour::toggle_float_placement`]: ../../komorebi/src/core/mod.rs [`WindowManager::promote_container_to_front`]: ../../komorebi/src/window_manager.rs [`WindowManager::promote_container_swap`]: ../../komorebi/src/window_manager.rs diff --git a/docs/usage/moving-windows.md b/docs/usage/moving-windows.md index 75010824..4a8ff2c1 100644 --- a/docs/usage/moving-windows.md +++ b/docs/usage/moving-windows.md @@ -55,6 +55,22 @@ komorebic promote-window left [`komorebic promote-focus`](../cli/promote-focus.md) gives the focus to the window on the first tile and moves nothing. +## Locking a window in its place + +[`komorebic toggle-lock`](../cli/toggle-lock.md) locks the focused window's container at its +place in the order of the workspace, and unlocks it again. Windows that open, close or move +around a locked container leave it where it is: a new window that would go in its place goes +after it. A window moved onto the place of a locked one with `move`, `cycle-move` or +`promote-swap` is locked there instead, since the lock belongs to the place. + +```sh +komorebic toggle-lock +``` + +The `LockMonitorWorkspaceContainer` and `UnlockMonitorWorkspaceContainer` messages lock and +unlock a container by the index of its monitor, its workspace and itself, for a program such as +a status bar. They have no subcommand. + ## The pointer The pointer follows the window that moved, unless diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 6917ca94..cff153ae 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -352,6 +352,9 @@ pub enum SocketMessage { PromoteSwap, PromoteFocus, PromoteWindow(OperationDirection), + LockMonitorWorkspaceContainer(usize, usize, usize), + UnlockMonitorWorkspaceContainer(usize, usize, usize), + ToggleLock, ToggleFloat, // Current Workspace Commands ChangeLayout(DefaultLayout), diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index ea47fb34..9a610dbb 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -37,6 +37,10 @@ //! already, and **CancelPreselect** gives the reserved place up. //! - **MouseFollowsFocus** and **ToggleMouseFollowsFocus** set whether the pointer is moved to //! the window that is given the focus. +//! - **ToggleLock** locks the focused container at its index, or unlocks it +//! ([`WindowManager::toggle_lock`]), and **LockMonitorWorkspaceContainer** and +//! **UnlockMonitorWorkspaceContainer** do the same for a container given by the index of its +//! monitor, its workspace and itself. //! - **ToggleFloat** takes the focused window out of the layout into the floating windows of the //! workspace, which komorebi does not move, or puts a floating window back //! ([`WindowManager::toggle_float`]). @@ -147,6 +151,8 @@ impl WindowManager { /// [`WindowManager::move_container_in_cycle_direction`] give. /// - There is no focused workspace to change the layout or the tiling of, to preselect a /// place in, or to resize or promote a container of, or it cannot be tiled again. + /// - The monitor or the workspace of `LockMonitorWorkspaceContainer` or + /// `UnlockMonitorWorkspaceContainer` is not there (a container that is not there is ignored). /// - The focused window cannot be floated or put back, for one of the reasons /// [`WindowManager::toggle_float`] gives. /// - The file of `QuickSave` or `Save` cannot be written, or the file of `QuickLoad` or @@ -274,11 +280,50 @@ impl WindowManager { self.update_focused_workspace(false, false)?; } + SocketMessage::LockMonitorWorkspaceContainer( + monitor_idx, + workspace_idx, + container_idx, + ) => { + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("no monitor at the given index")?; + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("no workspace at the given index")?; + + if let Some(container) = workspace.containers_mut().get_mut(container_idx) { + container.locked = true; + } + } + SocketMessage::UnlockMonitorWorkspaceContainer( + monitor_idx, + workspace_idx, + container_idx, + ) => { + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("no monitor at the given index")?; + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("no workspace at the given index")?; + + if let Some(container) = workspace.containers_mut().get_mut(container_idx) { + container.locked = false; + } + } SocketMessage::FlipLayout(layout_flip) => self.flip_layout(layout_flip)?, SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, SocketMessage::CycleLayout(direction) => self.cycle_layout(direction)?, SocketMessage::Retile => self.retile_all(false)?, SocketMessage::RetileWithResizeDimensions => self.retile_all(true)?, + SocketMessage::ToggleLock => self.toggle_lock()?, SocketMessage::ToggleTiling => { self.toggle_tiling()?; } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index d511cc33..815fbd04 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -31,6 +31,7 @@ use crate::core::Rect; use crate::core::Sizing; use crate::core::WindowManagementBehaviour; use crate::desktop; +use crate::lockable_sequence::Lockable; use crate::monitor::Monitor; use crate::ring::Ring; use crate::window::Window; @@ -857,6 +858,24 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, false) } + /// Locks the focused container of the focused workspace at its index, or unlocks it + /// + /// A locked container stays at its index while containers are inserted, removed and swapped + /// around it. Nothing is retiled. + /// + /// # Errors + /// + /// There is no focused workspace. + #[tracing::instrument(skip(self))] + pub fn toggle_lock(&mut self) -> eyre::Result<()> { + let workspace = self.focused_workspace_mut()?; + if let Some(container) = workspace.focused_container_mut() { + // Toggle the locked flag + container.set_locked(!container.locked()); + } + Ok(()) + } + /// Turns the tiling of the focused workspace off, or back on and tiles it again /// /// While its tiling is off, the workspace keeps its containers and moves no window. @@ -1211,6 +1230,57 @@ mod tests { Ok(()) } + #[test] + fn test_toggle_lock() { + let (mut wm, _context) = setup_window_manager(); + + { + // Add monitor with default workspace to + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + let workspace = m.focused_workspace_mut().unwrap(); + + // Create containers to add to the workspace + for _ in 0..3 { + let container = Container::default(); + workspace.add_container_to_back(container); + } + + wm.monitors_mut().push_back(m); + } + + { + // Ensure container 2 is not locked + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.focused_container_idx(), 2); + assert!(!workspace.focused_container().unwrap().locked); + } + + // Toggle lock on focused container + wm.toggle_lock().unwrap(); + + { + // Ensure container 2 is locked + let workspace = wm.focused_workspace_mut().unwrap(); + assert!(workspace.focused_container().unwrap().locked); + } + + // Toggle lock on focused container + wm.toggle_lock().unwrap(); + + { + // Ensure container 2 is not locked + let workspace = wm.focused_workspace_mut().unwrap(); + assert!(!workspace.focused_container().unwrap().locked); + } + } + #[test] fn test_float_window() { let (mut wm, _context) = setup_window_manager(); diff --git a/komorebi/tests/lock.rs b/komorebi/tests/lock.rs new file mode 100644 index 00000000..5abb45a7 --- /dev/null +++ b/komorebi/tests/lock.rs @@ -0,0 +1,158 @@ +//! Locking containers with `toggle-lock` and the messages that lock and unlock a container by its +//! indices, against an in-memory desktop: the messages go in through +//! [`WindowManager::process_command`], and what comes out is the order of the containers. +//! +//! Window ids are in the 26_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor, and a window for each of +/// `ids`, opened in that order. The last one has the focus. +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmk-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + for &id in ids { + open(&fake, &mut wm, id); + } + + (fake, wm) +} + +fn open(fake: &Arc, wm: &mut WindowManager, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); +} + +fn send( + fake: &Arc, + wm: &mut WindowManager, + message: SocketMessage, +) -> color_eyre::Result<()> { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())) +} + +/// The window of each container of the focused workspace, in order +fn order(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().unwrap().id) + .collect() +} + +fn locked(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.locked) + .collect() +} + +#[test] +fn toggle_lock_locks_the_focused_container_and_unlocks_it() { + let (fake, mut wm) = desktop_with(&[26_001, 26_002]); + + send(&fake, &mut wm, SocketMessage::ToggleLock).unwrap(); + assert_eq!(locked(&wm), [false, true]); + + send(&fake, &mut wm, SocketMessage::ToggleLock).unwrap(); + assert_eq!(locked(&wm), [false, false]); +} + +#[test] +fn a_window_that_opens_does_not_push_a_locked_container_from_its_index() { + let (fake, mut wm) = desktop_with(&[26_011, 26_012]); + // the first window gets the focus, and its container is locked: a new window goes after it, + // where the second one is + with_backend(fake.clone(), || wm.process_event(activated(26_011))).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::LockMonitorWorkspaceContainer(0, 0, 1), + ) + .unwrap(); + + open(&fake, &mut wm, 26_013); + + assert_eq!( + order(&wm), + [26_011, 26_012, 26_013], + "the second stays second" + ); + assert_eq!(locked(&wm), [false, true, false]); +} + +#[test] +fn a_container_is_locked_and_unlocked_by_its_indices() { + let (fake, mut wm) = desktop_with(&[26_021, 26_022]); + + send( + &fake, + &mut wm, + SocketMessage::LockMonitorWorkspaceContainer(0, 0, 0), + ) + .unwrap(); + assert_eq!(locked(&wm), [true, false]); + + send( + &fake, + &mut wm, + SocketMessage::UnlockMonitorWorkspaceContainer(0, 0, 0), + ) + .unwrap(); + assert_eq!(locked(&wm), [false, false]); + + // a container that is not there is ignored, a monitor that is not there is an error + send( + &fake, + &mut wm, + SocketMessage::LockMonitorWorkspaceContainer(0, 0, 9), + ) + .unwrap(); + assert_eq!( + send( + &fake, + &mut wm, + SocketMessage::LockMonitorWorkspaceContainer(3, 0, 0), + ) + .map_err(|error| error.to_string()), + Err(String::from("no monitor at the given index")) + ); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 45d75e63..c55c6a7d 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -16,7 +16,8 @@ //! next window and give it up. //! - `promote`, `promote-swap`, `promote-focus` and `promote-window` bring a window to the largest //! tile, or the focus to it. -//! - `toggle-float` takes the focused window out of the layout, or puts it back. +//! - `toggle-float` takes the focused window out of the layout, or puts it back, and +//! `toggle-lock` locks the focused container at its index, or unlocks it. //! - `resize-edge` and `resize-axis` resize the focused window by the `resize-delta`, and //! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of //! the tiles of the focused workspace and load them back. @@ -307,6 +308,8 @@ enum SubCommand { ToggleTiling, /// Toggle floating mode for the focused window ToggleFloat, + /// Toggle a lock for the focused container, ensuring it will not be displaced by any new windows + ToggleLock, /// Enable or disable mouse follows focus on all workspaces #[clap(arg_required_else_help = true)] MouseFollowsFocus(MouseFollowsFocus), @@ -483,6 +486,9 @@ fn main() -> eyre::Result<()> { SubCommand::ToggleTiling => { send_message(&SocketMessage::ToggleTiling)?; } + SubCommand::ToggleLock => { + send_message(&SocketMessage::ToggleLock)?; + } SubCommand::State => { print_query(&SocketMessage::State); } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 1b856f63..27338ffd 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -210,6 +210,7 @@ fn the_layout_subcommands_send_the_layout_axis_or_direction_they_are_given() { ); sends(&["toggle-tiling"], r#"{"type":"ToggleTiling"}"#); sends(&["toggle-float"], r#"{"type":"ToggleFloat"}"#); + sends(&["toggle-lock"], r#"{"type":"ToggleLock"}"#); sends( &["preselect-direction", "up"], r#"{"type":"PreselectDirection","content":"Up"}"#, @@ -385,6 +386,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "stop.md", "subscribe-socket.md", "toggle-float.md", + "toggle-lock.md", "toggle-mouse-follows-focus.md", "toggle-tiling.md", "unsubscribe-socket.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 41332fbf..984b5f63 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -184,6 +184,8 @@ preselect-direction left cancel-preselect toggle-float toggle-float +toggle-lock +toggle-lock toggle-tiling toggle-tiling mouse-follows-focus enable From 56294e1cd377e189345ce92676ba74fb940a2571 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 17:03:29 -0700 Subject: [PATCH 026/255] feat(wm): manage, minimize and close Every normal window KWin reports is tiled, and the only way to take one out of the layout was to float it, which keeps it a window komorebi manages. `komorebic unmanage` takes the focused window out of the layout, and komorebi leaves it alone until `komorebic manage` takes it back or the window closes. Both are events komorebi raises itself on the channel KWin's events go through, so they are handled in order with what KWin reports. `komorebic minimize` and `close` ask KWin to minimize or close the focused window, which leaves the layout when KWin reports that it did. `komorebic toggle-pause` pauses the daemon: it acts on no event, and takes only `toggle-pause`, `state` and `stop` on its socket until it is resumed. With `unmanaged-window-operation-behaviour no-op`, the daemon refuses every message while the focused window is not one it tiles. The vm-commands sweep pauses and resumes, sets the operation behavior, manages and closes the focused window, and a section of its own minimizes, unmanages and manages a window. --- README.md | 5 +- docs/cli/close.md | 10 + docs/cli/manage.md | 10 + docs/cli/minimize.md | 10 + docs/cli/toggle-pause.md | 10 + docs/cli/unmanage.md | 10 + .../unmanaged-window-operation-behaviour.md | 16 ++ docs/dev/ARCHITECTURE.md | 37 ++- docs/index.md | 6 +- docs/usage/managing-windows.md | 69 +++++ komorebi-client/src/lib.rs | 4 +- komorebi/src/core/mod.rs | 7 + komorebi/src/lib.rs | 7 +- komorebi/src/process_command.rs | 91 ++++++- komorebi/src/process_event.rs | 69 ++++- komorebi/src/state.rs | 17 +- komorebi/src/window_manager.rs | 83 ++++++ komorebi/src/window_manager_event.rs | 27 +- komorebi/src/workspace.rs | 44 ++++ komorebi/tests/manage.rs | 245 ++++++++++++++++++ komorebic/src/main.rs | 41 +++ komorebic/tests/cli.rs | 23 ++ nix/tests/vm/suites/commands/test.py | 47 +++- 23 files changed, 857 insertions(+), 31 deletions(-) create mode 100644 docs/cli/close.md create mode 100644 docs/cli/manage.md create mode 100644 docs/cli/minimize.md create mode 100644 docs/cli/toggle-pause.md create mode 100644 docs/cli/unmanage.md create mode 100644 docs/cli/unmanaged-window-operation-behaviour.md create mode 100644 docs/usage/managing-windows.md create mode 100644 komorebi/tests/manage.rs diff --git a/README.md b/README.md index 7b0828c3..c7a87e3f 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,10 @@ another layout, `layout-ratios` and `scrolling-layout-columns` tune it, focused window to the largest tile, `toggle-float` takes it out of the layout, and `toggle-lock` keeps its container at its place. The scrolling layout is a strip of columns that runs past the edges of the monitor and scrolls to -the window that has the focus. +the window that has the focus. `minimize` and `close` ask KWin to minimize or +close the focused window, `unmanage` takes it out of the layout until `manage` +takes it back, and `toggle-pause` stops the daemon acting on events and orders +until it is resumed. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/close.md b/docs/cli/close.md new file mode 100644 index 00000000..7f311fec --- /dev/null +++ b/docs/cli/close.md @@ -0,0 +1,10 @@ +```text +Close the focused window + +Usage: close + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/manage.md b/docs/cli/manage.md new file mode 100644 index 00000000..b898d165 --- /dev/null +++ b/docs/cli/manage.md @@ -0,0 +1,10 @@ +```text +Force komorebi to manage the focused window + +Usage: manage + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/minimize.md b/docs/cli/minimize.md new file mode 100644 index 00000000..0e15a9b7 --- /dev/null +++ b/docs/cli/minimize.md @@ -0,0 +1,10 @@ +```text +Minimize the focused window + +Usage: minimize + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-pause.md b/docs/cli/toggle-pause.md new file mode 100644 index 00000000..0f21d57b --- /dev/null +++ b/docs/cli/toggle-pause.md @@ -0,0 +1,10 @@ +```text +Toggle the paused state for all window tiling + +Usage: toggle-pause + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/unmanage.md b/docs/cli/unmanage.md new file mode 100644 index 00000000..0f779d5a --- /dev/null +++ b/docs/cli/unmanage.md @@ -0,0 +1,10 @@ +```text +Unmanage a window that was forcibly managed + +Usage: unmanage + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/unmanaged-window-operation-behaviour.md b/docs/cli/unmanaged-window-operation-behaviour.md new file mode 100644 index 00000000..8166e331 --- /dev/null +++ b/docs/cli/unmanaged-window-operation-behaviour.md @@ -0,0 +1,16 @@ +```text +Set the operation behavior when the focused window is not managed + +Usage: unmanaged-window-operation-behaviour + +Arguments: + + Possible values: + - op: Process commands on temporarily unmanaged/floated windows + - no-op: Ignore commands on temporarily unmanaged/floated windows + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 00d68065..ef6a4405 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -25,7 +25,8 @@ its place here. - **Layout**: the arrangement (BSP, columns, rows, ...) that turns a work area and a number of containers into one rectangle, a **tile**, for each container. - **Event**: what the compositor reports about a window: it was shown, destroyed, given - the focus, minimized or restored ([`WindowManagerEvent`]). + the focus, minimized or restored ([`WindowManagerEvent`]). Two events come from komorebi + itself: a command asks it to manage the focused window, or to stop managing it. - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order (focus a window, move it, change the layout, resize it, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). - **Direction**: where an order goes from the focused container: a side of its tile @@ -307,6 +308,26 @@ stays where it is. container given by its indices. A lock changes nothing until containers are inserted, removed or swapped around it, which the workspace does through `LockableSequence`. +`Minimize` and `Close` ask the backend to minimize or close the window the compositor has +focused, and change nothing else: the window leaves the layout when the compositor reports it, +through the `Minimize` and `Destroy` events. `UnmanageFocusedWindow` and `ManageFocusedWindow` +do not change the model either: they raise an `Unmanage` or a `Manage` event for the focused +window on the channel the backend's events go through +([`WindowManager::unmanage_focused_window`], [`WindowManager::manage_focused_window`]), and +the window manager handles them in order with the compositor's. An `Unmanage` is handled like a +`Destroy` of a window that stays open: the window leaves its workspace, is centered in the work +area, and its id goes into a list of unmanaged windows that `handle_event` checks before it acts +on any other event about a window; a `Manage` takes the id out of the list and is handled like a +`Show`. A `Destroy` takes the id out of the list too. + +`TogglePause` sets [`WindowManager::is_paused`]: while it is set, `handle_event` returns at once +for every event, and [`read_commands_uds`] hands only `TogglePause`, `State` and `Stop` to the +window manager. `UnmanagedWindowOperationBehaviour` sets +[`WindowManager::unmanaged_window_operation_behaviour`]: with `NoOp`, +[`WindowManager::process_command`] refuses every message while the window the compositor has +focused is in no container of the focused workspace +([`WindowManager::handle_unmanaged_window_behaviour`]). + `ResizeWindowEdge` and `ResizeWindowAxis` resize the focused container ([`WindowManager::resize_window`]). A resize is an adjustment of the container's tile, kept in [`Workspace::resize_dimensions`], one per container, which the layout applies when it calculates @@ -375,7 +396,8 @@ module's unit. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized window out, move the focus, move the focused container, change the layout, resize or - promote the focused container, float a window, lock a container). + promote the focused container, float a window, lock a container, manage and unmanage a + window). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -441,6 +463,8 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none | | A locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window`, `test_locked_containers_remove_window`, `a_window_that_opens_does_not_push_a_locked_container_from_its_index` | `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 window the user unmanaged stays out of the layout until it is managed again | framework path: `handle_event` checks the list of unmanaged windows before it acts on any event but a removal | `unmanage_takes_the_focused_window_out_until_manage_takes_it_back` | none | +| A paused window manager moves no window | framework path: `handle_event` returns before anything else, and [`read_commands_uds`] drops every message but `TogglePause`, `State` and `Stop` | `while_paused_no_event_changes_the_layout_and_manage_takes_in_a_window_it_missed`, `while_paused_only_toggle_pause_state_and_stop_are_handled` | 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 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 | @@ -578,7 +602,9 @@ A window is shown, and ends up on a tile: scrolling layout; [`komorebi/tests/resize.rs`](../../komorebi/tests/resize.rs), resizing; [`komorebi/tests/promote.rs`](../../komorebi/tests/promote.rs), promoting; [`komorebi/tests/float.rs`](../../komorebi/tests/float.rs), floating; - [`komorebi/tests/lock.rs`](../../komorebi/tests/lock.rs), locking. + [`komorebi/tests/lock.rs`](../../komorebi/tests/lock.rs), locking; + [`komorebi/tests/manage.rs`](../../komorebi/tests/manage.rs), minimizing, closing, + unmanaging and managing the focused window, and pausing. - [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, @@ -620,6 +646,11 @@ A window is shown, and ends up on a tile: [`WindowManager::resize_window`]: ../../komorebi/src/window_manager.rs [`WindowManager::toggle_float`]: ../../komorebi/src/window_manager.rs [`WindowManager::toggle_lock`]: ../../komorebi/src/window_manager.rs +[`WindowManager::manage_focused_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::unmanage_focused_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::is_paused`]: ../../komorebi/src/window_manager.rs +[`WindowManager::unmanaged_window_operation_behaviour`]: ../../komorebi/src/window_manager.rs +[`WindowManager::handle_unmanaged_window_behaviour`]: ../../komorebi/src/window_manager.rs [`WindowManagementBehaviour::toggle_float_placement`]: ../../komorebi/src/core/mod.rs [`WindowManager::promote_container_to_front`]: ../../komorebi/src/window_manager.rs [`WindowManager::promote_container_swap`]: ../../komorebi/src/window_manager.rs diff --git a/docs/index.md b/docs/index.md index 77226bf8..e198924c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -35,8 +35,10 @@ daemon, ask it what it is doing and read its log. [Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window, [Moving windows](usage/moving-windows.md) how to move the focused window to another tile, [Layouts](usage/layouts.md) how to change the arrangement of the tiles, -[Resizing windows](usage/resizing-windows.md) how to change the size of one, and -[Floating windows](usage/floating-windows.md) how to take a window out of the layout. +[Resizing windows](usage/resizing-windows.md) how to change the size of one, +[Floating windows](usage/floating-windows.md) how to take a window out of the layout, and +[Managing windows](usage/managing-windows.md) how to minimize, close and unmanage the focused +window and pause the daemon. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/managing-windows.md b/docs/usage/managing-windows.md new file mode 100644 index 00000000..f12cba3a --- /dev/null +++ b/docs/usage/managing-windows.md @@ -0,0 +1,69 @@ +# Managing windows + +komorebi tiles every normal application window that KWin reports, and leaves dialogs, splash +screens and other windows that are not for tiling alone. The commands here act on the window +that has the focus in KWin, take a window out of the layout or back into it, and pause the +daemon. + +## Minimizing and closing + +[`komorebic minimize`](../cli/minimize.md) asks KWin to minimize the window that has the focus, +and [`komorebic close`](../cli/close.md) asks it to close the window, as the buttons of its title +bar do. + +```sh +komorebic minimize +komorebic close +``` + +The window leaves the layout when KWin reports that it was minimized or closed, and the other +windows of the workspace share the work area. A minimized window comes back into the layout, in a +container of its own, when it is restored. + +## Taking a window out of the layout + +[`komorebic unmanage`](../cli/unmanage.md) takes the window that has the focus out of the layout. +It stays open, in the middle of the work area with the size it had, and komorebi leaves it alone +from then on: it does not tile it again, and it does not move it. +[`komorebic manage`](../cli/manage.md), with that window focused, puts it back in the layout, +after the focused window. + +```sh +komorebic unmanage +komorebic manage +``` + +`komorebic manage` also takes in a window komorebi missed, such as one that opened while the +daemon was paused. The daemon forgets an unmanaged window when it closes, and when the daemon +stops. + +## Commands while the focused window is not tiled + +By default, a command acts on the workspace whatever window has the focus. With +[`komorebic unmanaged-window-operation-behaviour no-op`](../cli/unmanaged-window-operation-behaviour.md), +the daemon ignores every command while the window that has the focus is not one of the windows it +tiles: a floating window, a window it does not manage, or one taken out with +`komorebic unmanage`. The daemon logs "ignoring commands while active window is not managed by +komorebi" for each. + +```sh +komorebic unmanaged-window-operation-behaviour no-op +komorebic unmanaged-window-operation-behaviour op +``` + +The commands that are ignored include `komorebic state`, `komorebic stop` and the command that +sets the behavior back to `op`: give the focus to a tiled window first. + +## Pausing + +[`komorebic toggle-pause`](../cli/toggle-pause.md) pauses the daemon, and the same command +resumes it. While it is paused, komorebi does not act on what KWin reports, so it moves no +window, and of its commands it carries out only `toggle-pause`, `state` and `stop`. The daemon's +state says whether it is paused, as `is_paused`. + +```sh +komorebic toggle-pause +``` + +What KWin reported while the daemon was paused is not acted on afterwards: a window that opened +in the meantime is not tiled until it is managed with `komorebic manage`. diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index af51ea46..699ebbc3 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -198,7 +198,7 @@ where /// # let daemon = std::thread::spawn(move || -> std::io::Result<()> { /// # let (mut stream, _) = listener.accept()?; /// # BufReader::new(stream.try_clone()?).read_line(&mut String::new())?; -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// # stream.write_all(state.as_bytes()) /// # }); /// use komorebi_client::SocketMessage; @@ -260,7 +260,7 @@ pub fn send_query(message: &SocketMessage) -> std::io::Result { /// # let mut message = String::new(); /// # BufReader::new(stream).read_line(&mut message)?; /// # let subscriber = komorebi_client::DATA_DIR.join("bar.sock"); -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// # let notification = format!(r#"{{"event":{message},"state":{state}}}"#); /// # std::os::unix::net::UnixStream::connect(subscriber)?.write_all(notification.as_bytes())?; /// # Ok(message) diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index cff153ae..ca685759 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -348,6 +348,9 @@ pub enum SocketMessage { CycleMoveWindow(CycleDirection), ResizeWindowEdge(OperationDirection, Sizing), ResizeWindowAxis(Axis, Sizing), + // ForceFocus, + Close, + Minimize, Promote, PromoteSwap, PromoteFocus, @@ -356,7 +359,10 @@ pub enum SocketMessage { UnlockMonitorWorkspaceContainer(usize, usize, usize), ToggleLock, ToggleFloat, + UnmanagedWindowOperationBehaviour(OperationBehaviour), // Current Workspace Commands + ManageFocusedWindow, + UnmanageFocusedWindow, ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), ScrollingLayoutColumns(NonZeroUsize), @@ -367,6 +373,7 @@ pub enum SocketMessage { // MonitorIndexPreference(usize, i32, i32, i32, i32), ToggleTiling, Stop, + TogglePause, Retile, RetileWithResizeDimensions, QuickSave, diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index a7397297..bdfedbb5 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -95,6 +95,9 @@ lazy_static! { static ref FLOATING_WINDOW_TOGGLE_ASPECT_RATIO: Arc> = Arc::new(Mutex::new( AspectRatio::Predefined(PredefinedAspectRatio::Widescreen) )); + /// The windows `UnmanageFocusedWindow` took out of the layout: komorebi leaves them alone + /// until `ManageFocusedWindow` takes them back, or until they close + static ref UNMANAGED_WINDOW_IDS: Arc>> = Arc::new(Mutex::new(vec![])); } /// The padding, in pixels, between the edge of a monitor's work area and the tiles of its @@ -131,7 +134,7 @@ pub enum NotificationEvent { /// use komorebi::core::SocketMessage; /// use komorebi::window_manager_event::WindowManagerEvent; /// -/// let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; +/// let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// /// let shown = format!( /// r#"{{"event":{{"type":"Show","content":[{{"type":"KWin","content":"WindowAdded"}},{{"id":7}}]}},"state":{state}}}"# @@ -206,7 +209,7 @@ pub struct Notification { /// ]); /// /// let state: State = serde_json::from_str( -/// r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#, +/// r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#, /// )?; /// let event = NotificationEvent::Socket(SocketMessage::Retile); /// notify_subscribers(Notification { event, state }, false)?; diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 9a610dbb..1964cf0c 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -44,6 +44,17 @@ //! - **ToggleFloat** takes the focused window out of the layout into the floating windows of the //! workspace, which komorebi does not move, or puts a floating window back //! ([`WindowManager::toggle_float`]). +//! - **Minimize** and **Close** ask the compositor to minimize or close the window that has the +//! focus. The window leaves the layout when the compositor reports that it did. +//! - **UnmanageFocusedWindow** takes the window that has the focus out of the layout and leaves it +//! alone until it closes, and **ManageFocusedWindow** takes it back +//! ([`WindowManager::unmanage_focused_window`], [`WindowManager::manage_focused_window`]). +//! - **UnmanagedWindowOperationBehaviour** sets whether a message is carried out while the window +//! that has the focus is not tiled ([`WindowManager::handle_unmanaged_window_behaviour`]). With +//! `NoOp`, every message is refused then, this one included. +//! - **TogglePause** pauses the window manager, or resumes it: while it is paused, it handles no +//! event, and of the messages only **TogglePause**, **State** and **Stop** +//! ([`read_commands_uds`]). //! - **ResizeWindowEdge** and **ResizeWindowAxis** resize the focused container by the //! [`WindowManager::resize_delta`] that **ResizeDelta** sets ([`WindowManager::resize_window`]), //! and **QuickSave**, **QuickLoad**, **Save** and **Load** write the resize adjustments of the @@ -62,6 +73,7 @@ use crate::Notification; use crate::NotificationEvent; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; +use crate::backend::backend; use crate::core::Axis; use crate::core::Layout; use crate::core::LayoutOptions; @@ -73,6 +85,7 @@ use crate::core::StateQuery; use crate::monitor::MonitorInformation; use crate::notify_subscribers; use crate::state::State; +use crate::window::Window; use crate::window_manager::WindowManager; use color_eyre::eyre; use color_eyre::eyre::Context; @@ -142,6 +155,8 @@ impl WindowManager { /// /// # Errors /// + /// - The unmanaged window operation behavior is `NoOp` and the window that has the focus is not + /// tiled, for one of the reasons [`WindowManager::handle_unmanaged_window_behaviour`] gives. /// - A query about the focused monitor, workspace or container when there is none. /// - The focus cannot be moved, for one of the reasons /// [`WindowManager::focus_container_in_direction`] and @@ -155,6 +170,8 @@ impl WindowManager { /// `UnlockMonitorWorkspaceContainer` is not there (a container that is not there is ignored). /// - The focused window cannot be floated or put back, for one of the reasons /// [`WindowManager::toggle_float`] gives. + /// - `Minimize`, `Close`, `ManageFocusedWindow` or `UnmanageFocusedWindow` when the compositor + /// reports no focused window, or the backend refuses to minimize or close it. /// - The file of `QuickSave` or `Save` cannot be written, or the file of `QuickLoad` or /// `Load` cannot be read or is not a list of resize adjustments. /// - The window manager fails to retile, for one of the reasons @@ -174,6 +191,8 @@ impl WindowManager { // We don't have From implemented for &mut WindowManager let initial_state = State::from(self.as_ref()); + self.handle_unmanaged_window_behaviour()?; + match message { SocketMessage::Promote => self.promote_container_to_front()?, SocketMessage::PromoteSwap => self.promote_container_swap()?, @@ -280,6 +299,24 @@ impl WindowManager { self.update_focused_workspace(false, false)?; } + SocketMessage::Minimize => { + let foreground_window = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + Window::from(foreground_window).minimize()?; + } + SocketMessage::Close => { + let foreground_window = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + Window::from(foreground_window).close()?; + } + SocketMessage::ManageFocusedWindow => { + self.manage_focused_window()?; + } + SocketMessage::UnmanageFocusedWindow => { + self.unmanage_focused_window()?; + } SocketMessage::LockMonitorWorkspaceContainer( monitor_idx, workspace_idx, @@ -321,6 +358,15 @@ impl WindowManager { SocketMessage::FlipLayout(layout_flip) => self.flip_layout(layout_flip)?, SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, SocketMessage::CycleLayout(direction) => self.cycle_layout(direction)?, + SocketMessage::TogglePause => { + if self.is_paused { + tracing::info!("resuming"); + } else { + tracing::info!("pausing"); + } + + self.is_paused = !self.is_paused; + } SocketMessage::Retile => self.retile_all(false)?, SocketMessage::RetileWithResizeDimensions => self.retile_all(true)?, SocketMessage::ToggleLock => self.toggle_lock()?, @@ -450,6 +496,9 @@ impl WindowManager { SocketMessage::ToggleMouseFollowsFocus => { self.mouse_follows_focus = !self.mouse_follows_focus; } + SocketMessage::UnmanagedWindowOperationBehaviour(behaviour) => { + self.unmanaged_window_operation_behaviour = behaviour; + } SocketMessage::AddSubscriberSocket(ref socket) => { let mut sockets = SUBSCRIPTION_SOCKETS.lock(); let socket_path = DATA_DIR.join(socket); @@ -544,7 +593,9 @@ impl WindowManager { /// [`WindowManager::process_command`] with the connection to answer on /// /// A message that arrives while the window manager has been locked for a second is logged and -/// dropped. +/// dropped. While the window manager is paused, the first message that is not `TogglePause`, +/// `State` or `Stop` is dropped, and the first that is one of them is handled; either way, the +/// lines after it are not read. /// /// # Errors /// @@ -570,6 +621,18 @@ pub fn read_commands_uds( ); } Some(mut wm) => { + if wm.is_paused { + return match message { + SocketMessage::TogglePause | SocketMessage::State | SocketMessage::Stop => { + Ok(wm.process_command(message, &mut stream)?) + } + _ => { + tracing::trace!("ignoring while paused"); + Ok(()) + } + }; + } + wm.process_command(message.clone(), &mut stream)?; } } @@ -767,6 +830,32 @@ mod tests { Ok(()) } + #[test] + fn while_paused_only_toggle_pause_state_and_stop_are_handled() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(741)); + daemon.ask(SocketMessage::Retile)?; + let tile = daemon.fake.rect_of(741); + daemon.ask(SocketMessage::TogglePause)?; + daemon + .fake + .move_window_by_user(741, rect(300, 300, 400, 400)); + + assert_eq!(daemon.ask(SocketMessage::Retile)?, ""); + assert_eq!(daemon.fake.rect_of(741), Some(rect(300, 300, 400, 400))); + // the message that is dropped is the last one read on its connection + assert_eq!( + daemon.send("{\"type\":\"Retile\"}\n{\"type\":\"State\"}\n")?, + "" + ); + let state: serde_json::Value = serde_json::from_str(&daemon.ask(SocketMessage::State)?)?; + assert_eq!(state["is_paused"], true); + + daemon.ask(SocketMessage::TogglePause)?; + daemon.ask(SocketMessage::Retile)?; + assert_eq!(daemon.fake.rect_of(741), tile); + Ok(()) + } + #[test] fn a_line_that_is_not_a_message_is_an_error() { let daemon = Daemon::new(FakeBackend::with_one_monitor()); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index d8719f69..8b052d74 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -1,12 +1,16 @@ //! How the window manager answers what the compositor reports: [`WindowManager::process_event`]. //! -//! An event about a window komorebi does not manage ([`Window::should_manage`]) changes nothing. -//! Otherwise: +//! Nothing changes while the window manager is paused (`TogglePause`). An event about a window +//! komorebi does not manage ([`Window::should_manage`]), or about one the user took out of the +//! layout with `UnmanageFocusedWindow`, changes nothing either. Otherwise: //! -//! - **Show**: the window gets a container of its own after the focused one, and the workspace is -//! tiled again. The first window on an empty workspace is given the focus. -//! - **Destroy**: the window is taken out of whichever workspace has it, and if that is the one in -//! front it is tiled again. +//! - **Show**, and **Manage** (`ManageFocusedWindow`): the window gets a container of its own after +//! the focused one, and the workspace is tiled again. The first window on an empty workspace is +//! given the focus. +//! - **Destroy**, and **Unmanage** (`UnmanageFocusedWindow`): the window is taken out of whichever +//! workspace has it, and if that is the one in front it is tiled again. A window that is +//! unmanaged stays open, centered in the work area so that it is not left behind the tiles, and +//! komorebi leaves it alone until it is managed again. //! - **FocusChange**: the workspace is tiled again and the container of the window that has the //! focus becomes the focused container. In the scrolling layout the workspace is tiled after //! that instead, so that the strip scrolls to the window that has the focus. @@ -23,6 +27,7 @@ use crate::Notification; use crate::NotificationEvent; +use crate::UNMANAGED_WINDOW_IDS; use crate::backend::backend; use crate::core::DefaultLayout; use crate::core::Layout; @@ -86,16 +91,25 @@ impl WindowManager { #[instrument(skip_all)] fn handle_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> { + if self.is_paused { + tracing::trace!("ignoring while paused"); + return Ok(()); + } + let Some(window) = event.window() else { return Ok(()); }; let window_id = window.id; - // A destroyed window can no longer be asked whether it should be managed, so a removal is - // let through without asking - let is_removal = matches!(event, WindowManagerEvent::Destroy(_, _)); + // A destroyed window can no longer be asked whether it should be managed, and a window the + // user unmanaged is let go of whatever it is, so a removal is let through without asking + let is_removal = matches!( + event, + WindowManagerEvent::Destroy(_, _) | WindowManagerEvent::Unmanage(_) + ); - let should_manage = is_removal || window.should_manage(); + let should_manage = is_removal + || (window.should_manage() && !UNMANAGED_WINDOW_IDS.lock().contains(&window_id)); if !should_manage { tracing::debug!("ignoring event as window should not be managed: {window}"); @@ -146,7 +160,7 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, false)?; } } - WindowManagerEvent::Show(_, _) => { + WindowManagerEvent::Show(_, _) | WindowManagerEvent::Manage(_) => { let mut create = true; if self.focused_workspace()?.contains_window(window_id) { @@ -179,11 +193,14 @@ impl WindowManager { } } } - WindowManagerEvent::Destroy(_, _) => { + WindowManagerEvent::Destroy(_, _) | WindowManagerEvent::Unmanage(_) => { + let destroyed = matches!(event, WindowManagerEvent::Destroy(_, _)); + // the window may be on any workspace, not only the one in front let location = self.known_window_ids.get(&window_id).cloned(); if let Some((m_idx, w_idx)) = location { + let behaviour = self.window_management_behaviour; let focused = m_idx == self.focused_monitor_idx() && Some(w_idx) == self.focused_workspace_idx().ok(); @@ -192,7 +209,25 @@ impl WindowManager { .get_mut(m_idx) .and_then(|m| m.workspaces_mut().get_mut(w_idx)) { - let _ = workspace.remove_window(window_id); + let removed = workspace.remove_window(window_id); + + if !destroyed + && focused + && let Ok(mut window) = removed + { + // we stopped managing a window that is still open, so it should not end up + // hidden behind the ones we do manage + let placement = if behaviour.floating_layer_override { + behaviour.floating_layer_placement + } else if behaviour.float_override { + behaviour.float_override_placement + } else { + behaviour.float_rule_placement + }; + + window + .center(&workspace.globals.work_area, placement.should_resize())?; + } } if focused { @@ -201,7 +236,13 @@ impl WindowManager { } } - self.minimized_windows.remove(&window_id); + if destroyed { + self.minimized_windows.remove(&window_id); + UNMANAGED_WINDOW_IDS.lock().retain(|id| *id != window_id); + } else { + // we only want to add the window ID after the window has been removed + UNMANAGED_WINDOW_IDS.lock().push(window_id); + } } WindowManagerEvent::Minimize(_, _) => { self.extract_minimized_window(window_id)?; diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 9d497d84..a75fcbbf 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -8,6 +8,7 @@ //! [`SocketMessage::State`]: crate::core::SocketMessage::State //! [`Notification`]: crate::Notification +use crate::core::OperationBehaviour; use crate::core::Rect; use crate::monitor::Monitor; use crate::ring::Ring; @@ -53,7 +54,9 @@ use std::collections::VecDeque; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct State { pub monitors: Ring, + pub is_paused: bool, pub resize_delta: i32, + pub unmanaged_window_operation_behaviour: OperationBehaviour, pub work_area_offset: Option, pub mouse_follows_focus: bool, } @@ -105,17 +108,19 @@ impl From<&WindowManager> for State { Self { monitors: stripped_monitors, + is_paused: wm.is_paused, work_area_offset: wm.work_area_offset, resize_delta: wm.resize_delta, mouse_follows_focus: wm.mouse_follows_focus, + unmanaged_window_operation_behaviour: wm.unmanaged_window_operation_behaviour, } } } impl State { /// Returns true if and only if the window manager's monitors (with their workspaces, - /// containers and windows), its work area offset or its mouse follows focus setting differ - /// from this state's + /// containers and windows), whether it is paused, its unmanaged window operation behavior, its + /// work area offset or its mouse follows focus setting differ from this state's /// /// A window is compared by its id only, so a window that moved or was renamed is not a /// change. @@ -126,6 +131,14 @@ impl State { return true; } + if self.is_paused != new.is_paused { + return true; + } + + if self.unmanaged_window_operation_behaviour != new.unmanaged_window_operation_behaviour { + return true; + } + if self.work_area_offset != new.work_area_offset { return true; } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 815fbd04..e317fc3b 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -19,6 +19,7 @@ use crate::DATA_DIR; use crate::LibraryError; use crate::SUBSCRIPTION_SOCKETS; +use crate::UNMANAGED_WINDOW_IDS; use crate::backend::backend; use crate::container::Container; use crate::core::Arrangement; @@ -26,6 +27,7 @@ use crate::core::Axis; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::OperationBehaviour; use crate::core::OperationDirection; use crate::core::Rect; use crate::core::Sizing; @@ -36,6 +38,7 @@ use crate::monitor::Monitor; use crate::ring::Ring; use crate::window::Window; use crate::window_manager_event::WindowManagerEvent; +use crate::window_manager_event_listener; use crate::workspace::Workspace; use color_eyre::eyre; use color_eyre::eyre::OptionExt; @@ -58,8 +61,14 @@ pub struct WindowManager { /// The socket the daemon takes messages on, `komorebi.sock` in [`struct@DATA_DIR`] unless /// [`WindowManager::new`] was given another path pub command_listener: UnixListener, + /// Whether `TogglePause` has paused the window manager: while it is paused, it handles no + /// event, and of the messages only `TogglePause`, `State` and `Stop` + pub is_paused: bool, /// How many pixels `ResizeWindowEdge` and `ResizeWindowAxis` resize by pub resize_delta: i32, + /// Whether a message is carried out while the window that has the focus is not one komorebi + /// tiles ([`WindowManager::handle_unmanaged_window_behaviour`]) + pub unmanaged_window_operation_behaviour: OperationBehaviour, /// How new and floated windows are placed: `ToggleFloat` reads its `toggle_float_placement` pub window_management_behaviour: WindowManagementBehaviour, /// Whether the pointer is moved to the window that is given the focus, which is the default @@ -114,7 +123,9 @@ impl WindowManager { Ok(Self { monitors: Ring::default(), command_listener: listener, + is_paused: false, resize_delta: 50, + unmanaged_window_operation_behaviour: Default::default(), window_management_behaviour: WindowManagementBehaviour::default(), mouse_follows_focus: true, work_area_offset: None, @@ -949,6 +960,36 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, true) } + /// With [`OperationBehaviour::NoOp`], refuses a message while the window that has the focus + /// in the compositor is not in a container of the focused workspace: a window komorebi does + /// not manage, one the user unmanaged, or a floating window + /// + /// With [`OperationBehaviour::Op`], the default, every message is carried out. + /// + /// # Errors + /// + /// With [`OperationBehaviour::NoOp`]: + /// + /// - There is no focused workspace, or the compositor reports no focused window. + /// - The focused window is not in a container of the focused workspace. + #[tracing::instrument(skip(self))] + pub fn handle_unmanaged_window_behaviour(&self) -> eyre::Result<()> { + if matches!( + self.unmanaged_window_operation_behaviour, + OperationBehaviour::NoOp + ) { + let workspace = self.focused_workspace()?; + let focused_hwnd = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + if !workspace.contains_managed_window(focused_hwnd) { + bail!("ignoring commands while active window is not managed by komorebi"); + } + } + + Ok(()) + } + pub fn update_known_window_ids(&mut self) { tracing::trace!("updating list of known window_ids"); let mut known_window_ids = HashMap::new(); @@ -971,6 +1012,48 @@ impl WindowManager { self.known_window_ids = known_window_ids; } } + + /// Asks the window manager to manage the window that has the focus in the compositor again + /// after [`WindowManager::unmanage_focused_window`], by raising a + /// [`WindowManagerEvent::Manage`] for it, which is handled like a window that opens + /// + /// # Errors + /// + /// The compositor reports no focused window. + #[tracing::instrument(skip(self))] + pub fn manage_focused_window(&mut self) -> eyre::Result<()> { + let window_id = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + + UNMANAGED_WINDOW_IDS.lock().retain(|id| *id != window_id); + + window_manager_event_listener::send_notification(WindowManagerEvent::Manage(Window::from( + window_id, + ))); + + Ok(()) + } + + /// Asks the window manager to stop managing the window that has the focus in the compositor, + /// by raising a [`WindowManagerEvent::Unmanage`] for it: the window leaves the layout, and + /// komorebi leaves it alone until [`WindowManager::manage_focused_window`] or until it closes + /// + /// # Errors + /// + /// The compositor reports no focused window. + #[tracing::instrument(skip(self))] + pub fn unmanage_focused_window(&mut self) -> eyre::Result<()> { + let window_id = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + + window_manager_event_listener::send_notification(WindowManagerEvent::Unmanage( + Window::from(window_id), + )); + + Ok(()) + } } #[cfg(test)] diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index 15e6a6f2..d815bd80 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -3,19 +3,23 @@ //! ([`WindowManager::process_event`](crate::window_manager::WindowManager::process_event)). //! //! An event is about one window and carries it, and the compositor signal it came from -//! ([`SystemNotification`]), which is only for logging. +//! ([`SystemNotification`]), which is only for logging. Two events come from komorebi itself +//! rather than from the compositor: [`WindowManagerEvent::Manage`] and +//! [`WindowManagerEvent::Unmanage`], which the commands that manage and unmanage the focused window +//! raise. use crate::window::Window; use serde::Deserialize; use serde::Serialize; use strum::Display; -/// The compositor signal a [`WindowManagerEvent`] came from +/// Where a [`WindowManagerEvent`] came from: a compositor signal, or komorebi itself #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, PartialEq, Eq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(tag = "type", content = "content")] pub enum SystemNotification { KWin(KWinNotification), + Manual(ManualNotification), } /// The KWin script signals the bridge listens to @@ -34,6 +38,14 @@ pub enum KWinNotification { WindowRestored, } +/// Events komorebi raises itself, for example from a command +#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, PartialEq, Eq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum ManualNotification { + Manage, + Unmanage, +} + /// Window events: each carries the window it is about. #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] @@ -44,6 +56,10 @@ pub enum WindowManagerEvent { Destroy(SystemNotification, Window), Minimize(SystemNotification, Window), Restore(SystemNotification, Window), + /// The user asked komorebi to manage the window (`ManageFocusedWindow`) + Manage(Window), + /// The user asked komorebi to stop managing the window (`UnmanageFocusedWindow`) + Unmanage(Window), } impl WindowManagerEvent { @@ -54,7 +70,9 @@ impl WindowManagerEvent { | WindowManagerEvent::Show(_, window) | WindowManagerEvent::Destroy(_, window) | WindowManagerEvent::Minimize(_, window) - | WindowManagerEvent::Restore(_, window) => *window, + | WindowManagerEvent::Restore(_, window) + | WindowManagerEvent::Manage(window) + | WindowManagerEvent::Unmanage(window) => *window, }) } @@ -75,7 +93,10 @@ impl WindowManagerEvent { | WindowManagerEvent::Minimize(n, _) | WindowManagerEvent::Restore(n, _) => match n { SystemNotification::KWin(k) => k.to_string(), + SystemNotification::Manual(m) => m.to_string(), }, + WindowManagerEvent::Manage(_) => ManualNotification::Manage.to_string(), + WindowManagerEvent::Unmanage(_) => ManualNotification::Unmanage.to_string(), } } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 61f48c14..bd2ca5d7 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -368,6 +368,18 @@ impl Workspace { false } + /// Returns true if and only if the window is in one of the containers, which leaves out the + /// floating windows: the windows komorebi tiles + pub fn contains_managed_window(&self, window_id: u32) -> bool { + for container in self.containers() { + if container.contains_window(window_id) { + return true; + } + } + + false + } + pub fn remove_focused_container(&mut self) -> Option { let focused_idx = self.focused_container_idx(); let container = self.remove_container_by_idx(focused_idx); @@ -1520,6 +1532,38 @@ mod tests { assert_eq!(focused_container.focused_window_idx(), 1); } + #[test] + fn test_contains_managed_window() { + let mut workspace = Workspace::default(); + + { + // Container with 3 windows + let mut container = Container::default(); + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + workspace.add_container_to_back(container); + } + + { + // Container with 1 window + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(4)); + workspace.add_container_to_back(container); + } + + // Should return true, window is in container 1 + assert!(workspace.contains_managed_window(4)); + + // Should return true, all the windows are in container 0 + for i in 0..3 { + assert!(workspace.contains_managed_window(i)); + } + + // Should return false since window was never added + assert!(!workspace.contains_managed_window(5)); + } + #[test] fn test_new_floating_window() { let mut workspace = Workspace::default(); diff --git a/komorebi/tests/manage.rs b/komorebi/tests/manage.rs new file mode 100644 index 00000000..173d2b7c --- /dev/null +++ b/komorebi/tests/manage.rs @@ -0,0 +1,245 @@ +//! Minimizing, closing, unmanaging and managing the focused window, pausing the window manager, +//! and the unmanaged window operation behavior, against an in-memory desktop: the messages go in +//! through [`WindowManager::process_command`], and what comes out is what the backend was asked +//! for and the order of the containers. +//! +//! `UnmanageFocusedWindow` and `ManageFocusedWindow` raise an event on the process-wide channel of +//! [`window_manager_event_listener`], where the daemon's events thread would take it: the tests +//! that read the channel hold [`CHANNEL`] so that they do not take each other's events. +//! +//! Window ids are in the 27_000s. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::OperationBehaviour; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::state::State; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use komorebi::window_manager_event_listener; +use std::sync::Arc; +use std::sync::Mutex; +use std::time::Duration; + +static CHANNEL: Mutex<()> = Mutex::new(()); + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn minimized(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Minimize( + SystemNotification::KWin(KWinNotification::WindowMinimized), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor, and a window for each of +/// `ids`, opened in that order. The last one has the focus. +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmm-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + for &id in ids { + open(&fake, &mut wm, id); + } + fake.set_foreground(ids.last().copied()); + + (fake, wm) +} + +fn open(fake: &Arc, wm: &mut WindowManager, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); +} + +fn send( + fake: &Arc, + wm: &mut WindowManager, + message: SocketMessage, +) -> color_eyre::Result<()> { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())) +} + +/// Takes the event about window `id` off the channel the daemon's events thread reads, and has +/// the window manager handle it, as that thread does +fn handle_raised(fake: &Arc, wm: &mut WindowManager, id: u32) -> WindowManagerEvent { + let events = window_manager_event_listener::event_rx(); + loop { + let event = events + .recv_timeout(Duration::from_secs(5)) + .expect("an event about the window is raised"); + if event.window_id() == Some(id) { + with_backend(fake.clone(), || wm.process_event(event)).unwrap(); + return event; + } + } +} + +/// The window of each container of the focused workspace, in order +fn order(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().unwrap().id) + .collect() +} + +#[test] +fn minimize_and_close_ask_the_compositor_about_the_window_that_has_the_focus() { + let (fake, mut wm) = desktop_with(&[27_001, 27_002]); + fake.clear_commands(); + + send(&fake, &mut wm, SocketMessage::Minimize).unwrap(); + assert_eq!(fake.commands(), [Command::Minimize(27_002)]); + // the window leaves the layout when the compositor reports it minimized, not before + assert_eq!(order(&wm), [27_001, 27_002]); + with_backend(fake.clone(), || wm.process_event(minimized(27_002))).unwrap(); + assert_eq!(order(&wm), [27_001]); + + fake.set_foreground(Some(27_001)); + fake.clear_commands(); + send(&fake, &mut wm, SocketMessage::Close).unwrap(); + assert_eq!(fake.commands(), [Command::Close(27_001)]); + + fake.set_foreground(None); + assert_eq!( + send(&fake, &mut wm, SocketMessage::Close).map_err(|error| error.to_string()), + Err(String::from("there is no foreground window")) + ); +} + +#[test] +fn unmanage_takes_the_focused_window_out_until_manage_takes_it_back() { + let _channel = CHANNEL + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let (fake, mut wm) = desktop_with(&[27_011, 27_012]); + let tile = fake.rect_of(27_012).unwrap(); + + send(&fake, &mut wm, SocketMessage::UnmanageFocusedWindow).unwrap(); + let event = handle_raised(&fake, &mut wm, 27_012); + assert!( + matches!(event, WindowManagerEvent::Unmanage(_)), + "{event:?}" + ); + + assert_eq!(order(&wm), [27_011]); + // the window stays open, centered in the 1920x1050 work area with the size of its tile + assert_eq!( + fake.rect_of(27_012), + Some(Rect { + left: (1920 - tile.right) / 2, + top: (1050 - tile.bottom) / 2, + right: tile.right, + bottom: tile.bottom, + }) + ); + + // the compositor announcing it again does not bring it back + with_backend(fake.clone(), || wm.process_event(added(27_012))).unwrap(); + assert_eq!(order(&wm), [27_011]); + + send(&fake, &mut wm, SocketMessage::ManageFocusedWindow).unwrap(); + let event = handle_raised(&fake, &mut wm, 27_012); + assert!(matches!(event, WindowManagerEvent::Manage(_)), "{event:?}"); + + assert_eq!(order(&wm), [27_011, 27_012]); +} + +#[test] +fn while_paused_no_event_changes_the_layout_and_manage_takes_in_a_window_it_missed() { + let _channel = CHANNEL + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let (fake, mut wm) = desktop_with(&[27_021]); + + send(&fake, &mut wm, SocketMessage::TogglePause).unwrap(); + assert!(State::from(&wm).is_paused); + open(&fake, &mut wm, 27_022); + assert_eq!(order(&wm), [27_021], "a window that opens is left alone"); + + send(&fake, &mut wm, SocketMessage::TogglePause).unwrap(); + assert!(!State::from(&wm).is_paused); + open(&fake, &mut wm, 27_023); + assert_eq!( + order(&wm), + [27_021, 27_023], + "the event that was missed is not handled afterwards" + ); + + fake.set_foreground(Some(27_022)); + send(&fake, &mut wm, SocketMessage::ManageFocusedWindow).unwrap(); + handle_raised(&fake, &mut wm, 27_022); + assert_eq!(order(&wm), [27_021, 27_023, 27_022]); +} + +#[test] +fn with_no_op_every_message_is_refused_while_the_focused_window_is_not_tiled() { + let (fake, mut wm) = desktop_with(&[27_031, 27_032]); + // a dialog, which komorebi does not manage, takes the focus + fake.open_window(27_033, "foot", "foot", "a dialog"); + fake.set_normal(27_033, false); + + send( + &fake, + &mut wm, + SocketMessage::UnmanagedWindowOperationBehaviour(OperationBehaviour::NoOp), + ) + .unwrap(); + assert_eq!( + State::from(&wm).unmanaged_window_operation_behaviour, + OperationBehaviour::NoOp + ); + send(&fake, &mut wm, SocketMessage::Retile).unwrap(); + + fake.set_foreground(Some(27_033)); + let refused = Err(String::from( + "ignoring commands while active window is not managed by komorebi", + )); + assert_eq!( + send(&fake, &mut wm, SocketMessage::Retile).map_err(|error| error.to_string()), + refused + ); + // this message too, while the dialog has the focus + assert_eq!( + send( + &fake, + &mut wm, + SocketMessage::UnmanagedWindowOperationBehaviour(OperationBehaviour::Op), + ) + .map_err(|error| error.to_string()), + refused + ); + + fake.set_foreground(Some(27_032)); + send( + &fake, + &mut wm, + SocketMessage::UnmanagedWindowOperationBehaviour(OperationBehaviour::Op), + ) + .unwrap(); + fake.set_foreground(Some(27_033)); + send(&fake, &mut wm, SocketMessage::Retile).unwrap(); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index c55c6a7d..c6d19657 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -18,6 +18,10 @@ //! tile, or the focus to it. //! - `toggle-float` takes the focused window out of the layout, or puts it back, and //! `toggle-lock` locks the focused container at its index, or unlocks it. +//! - `minimize` and `close` minimize and close the focused window, `unmanage` takes it out of +//! the layout until `manage` takes it back, `unmanaged-window-operation-behaviour` sets whether +//! the daemon carries out an order while the focused window is not one it tiles, and +//! `toggle-pause` pauses the daemon and resumes it. //! - `resize-edge` and `resize-axis` resize the focused window by the `resize-delta`, and //! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of //! the tiles of the focused workspace and load them back. @@ -40,6 +44,7 @@ use fs_tail::TailedFile; use komorebi_client::Axis; use komorebi_client::CycleDirection; use komorebi_client::DefaultLayout; +use komorebi_client::OperationBehaviour; use komorebi_client::OperationDirection; use komorebi_client::Sizing; use komorebi_client::SocketMessage; @@ -99,6 +104,7 @@ gen_enum_subcommand_args! { // WatchConfiguration: BooleanState, MouseFollowsFocus: BooleanState, Query: StateQuery, + UnmanagedWindowOperationBehaviour: OperationBehaviour, PromoteWindow: OperationDirection, } @@ -260,6 +266,12 @@ enum SubCommand { PreselectDirection(PreselectDirection), /// Cancel a workspace preselect set by the preselect-direction command, if one exists CancelPreselect, + /// Minimize the focused window + Minimize, + /// Close the focused window + Close, + // /// Forcibly focus the window at the cursor with a left mouse click + // ForceFocus, /// Change focus to the window in the specified cycle direction #[clap(arg_required_else_help = true)] CycleFocus(CycleFocus), @@ -304,12 +316,21 @@ enum SubCommand { PromoteWindow(PromoteWindow), /// Force the retiling of all managed windows Retile, + /// Toggle the paused state for all window tiling + TogglePause, /// Toggle window tiling on the focused workspace ToggleTiling, /// Toggle floating mode for the focused window ToggleFloat, /// Toggle a lock for the focused container, ensuring it will not be displaced by any new windows ToggleLock, + /// Force komorebi to manage the focused window + Manage, + /// Unmanage a window that was forcibly managed + Unmanage, + /// Set the operation behavior when the focused window is not managed + #[clap(arg_required_else_help = true)] + UnmanagedWindowOperationBehaviour(UnmanagedWindowOperationBehaviour), /// Enable or disable mouse follows focus on all workspaces #[clap(arg_required_else_help = true)] MouseFollowsFocus(MouseFollowsFocus), @@ -450,6 +471,9 @@ fn main() -> eyre::Result<()> { SubCommand::CycleMove(args) => { send_message(&SocketMessage::CycleMoveWindow(args.cycle_direction))?; } + SubCommand::TogglePause => { + send_message(&SocketMessage::TogglePause)?; + } SubCommand::ChangeLayout(args) => { send_message(&SocketMessage::ChangeLayout(args.default_layout))?; } @@ -471,6 +495,18 @@ fn main() -> eyre::Result<()> { SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } + SubCommand::Close => { + send_message(&SocketMessage::Close)?; + } + SubCommand::Minimize => { + send_message(&SocketMessage::Minimize)?; + } + SubCommand::Manage => { + send_message(&SocketMessage::ManageFocusedWindow)?; + } + SubCommand::Unmanage => { + send_message(&SocketMessage::UnmanageFocusedWindow)?; + } SubCommand::Promote => { send_message(&SocketMessage::Promote)?; } @@ -513,6 +549,11 @@ fn main() -> eyre::Result<()> { send_message(&SocketMessage::LayoutRatios(args.columns, args.rows))?; } } + SubCommand::UnmanagedWindowOperationBehaviour(args) => { + send_message(&SocketMessage::UnmanagedWindowOperationBehaviour( + args.operation_behaviour, + ))?; + } SubCommand::ToggleMouseFollowsFocus => { send_message(&SocketMessage::ToggleMouseFollowsFocus)?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 27338ffd..93f36fbd 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -297,6 +297,23 @@ fn the_promote_subcommands_send_their_message() { ); } +#[test] +fn the_subcommands_about_the_focused_window_and_pausing_send_their_message() { + sends(&["minimize"], r#"{"type":"Minimize"}"#); + sends(&["close"], r#"{"type":"Close"}"#); + sends(&["manage"], r#"{"type":"ManageFocusedWindow"}"#); + sends(&["unmanage"], r#"{"type":"UnmanageFocusedWindow"}"#); + sends(&["toggle-pause"], r#"{"type":"TogglePause"}"#); + sends( + &["unmanaged-window-operation-behaviour", "no-op"], + r#"{"type":"UnmanagedWindowOperationBehaviour","content":"NoOp"}"#, + ); + sends( + &["unmanaged-window-operation-behaviour", "op"], + r#"{"type":"UnmanagedWindowOperationBehaviour","content":"Op"}"#, + ); +} + #[test] fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { sends( @@ -354,6 +371,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { [ "cancel-preselect.md", "change-layout.md", + "close.md", "completions.md", "cycle-focus.md", "cycle-layout.md", @@ -364,6 +382,8 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "layout-ratios.md", "load-resize.md", "log.md", + "manage.md", + "minimize.md", "monitor-information.md", "mouse-follows-focus.md", "move.md", @@ -388,7 +408,10 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "toggle-float.md", "toggle-lock.md", "toggle-mouse-follows-focus.md", + "toggle-pause.md", "toggle-tiling.md", + "unmanage.md", + "unmanaged-window-operation-behaviour.md", "unsubscribe-socket.md", ] ); diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 984b5f63..118fc25a 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -5,7 +5,9 @@ # windows are inside the outputs and do not lie on each other. A command is also expected to be # understood (exit status 0). The Rust tests check what each command does against the fake; this # suite checks that none of them breaks the daemon in a real session, and that what the daemon -# asks KWin for is what KWin carries out. Every command `komorebic` has is in the sweep. +# asks KWin for is what KWin carries out. Every command `komorebic` has is in the sweep, but +# `minimize` and `unmanage`, which take a window out of komorebi's hands and have a section of +# their own. import shlex from komorebi_vm import Checks, Kde, daemon @@ -188,10 +190,17 @@ toggle-lock toggle-lock toggle-tiling toggle-tiling +toggle-pause +toggle-pause +unmanaged-window-operation-behaviour op +unmanaged-window-operation-behaviour no-op +unmanaged-window-operation-behaviour op mouse-follows-focus enable mouse-follows-focus disable toggle-mouse-follows-focus toggle-mouse-follows-focus +manage +close retile """ for line in SWEEP.strip().splitlines(): @@ -204,6 +213,42 @@ for line in SWEEP.strip().splitlines(): continue checks.ok(f"komorebic {line}") +print("== 3b. minimize, unmanage and manage the focused window") +focused = kde.active() +title = kde.title(focused) +before = kde.managed() +kde.wait_for(lambda: kde.focused_title() == title, timeout=10) +kde.komorebic("minimize") +checks.check( + f"minimize: komorebi lets go of {title} when KWin minimizes it", + kde.wait_for(lambda: kde.managed() == before - 1, timeout=10) + and kde.wid(title) != "", +) +kde.activate(focused) +checks.check( + f"{title}, restored, is tiled again", + kde.wait_for(lambda: kde.managed() == before and healthy() == 0, timeout=10), +) +kde.wait_for(lambda: kde.focused_title() == title, timeout=10) +kde.komorebic("unmanage") +checks.check( + f"unmanage: komorebi lets go of {title}, which stays open", + kde.wait_for(lambda: kde.managed() == before - 1, timeout=10) and kde.wid(title) != "", +) + + +def centered() -> bool: + r = kde.rect(focused) + return abs(r.x + r.w // 2 - W // 2) <= CELL and abs(r.y + r.h // 2 - H // 2) <= CELL + + +checks.check(f"{title} is in the middle of the work area", kde.wait_for(centered, timeout=10)) +kde.komorebic("manage") +checks.check( + f"manage: {title} is tiled again", + kde.wait_for(lambda: kde.managed() == before and healthy() == 0, timeout=10), +) + print("== 4. what komorebic only prints") for args in ["state", "monitor-information", "data-directory"]: checks.check(f"komorebic {args}", kde.run(f"komorebic {args}")[0] == 0) From c95be9391ec094c5ae0c5d6ac68ea8d386d4a8f5 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 17:12:31 -0700 Subject: [PATCH 027/255] feat(wm): padding and work-area offsets Every workspace was tiled with the default padding of 5 pixels around and between its tiles, and the work area offsets could not be set. The padding commands set a workspace's own workspace padding and container padding, by the indices of its monitor and itself or for the focused workspace, and the adjust commands make the focused workspace's larger or smaller. `global-work-area-offset`, `monitor-work-area-offset` and `workspace-work-area-offset` keep a part of the work area free of tiles, and a workspace's offset now wins over its monitor's, which wins over the global one. A monitor's window-based offset applies while the workspace in front has no more windows than the monitor's limit, and `toggle-window-based-work-area-offset` turns it off and on for the focused workspace. The vm-commands sweep sets and resets every offset and padding. --- README.md | 3 +- docs/cli/adjust-container-padding.md | 19 ++ docs/cli/adjust-workspace-padding.md | 19 ++ docs/cli/container-padding.md | 20 ++ .../focused-workspace-container-padding.md | 14 + docs/cli/focused-workspace-padding.md | 14 + docs/cli/global-work-area-offset.md | 23 ++ docs/cli/monitor-work-area-offset.md | 26 ++ .../toggle-window-based-work-area-offset.md | 10 + docs/cli/workspace-padding.md | 20 ++ docs/cli/workspace-work-area-offset.md | 29 +++ docs/dev/ARCHITECTURE.md | 35 ++- docs/index.md | 6 +- docs/usage/padding-and-offsets.md | 76 ++++++ komorebi/src/core/mod.rs | 10 + komorebi/src/monitor.rs | 10 + komorebi/src/process_command.rs | 70 +++++ komorebi/src/state.rs | 5 + komorebi/src/window_manager.rs | 114 ++++++++ komorebi/src/workspace.rs | 38 ++- komorebi/tests/padding.rs | 244 ++++++++++++++++++ komorebic/src/main.rs | 207 +++++++++++++++ komorebic/tests/cli.rs | 66 +++++ nix/tests/vm/suites/commands/test.py | 20 ++ 24 files changed, 1083 insertions(+), 15 deletions(-) create mode 100644 docs/cli/adjust-container-padding.md create mode 100644 docs/cli/adjust-workspace-padding.md create mode 100644 docs/cli/container-padding.md create mode 100644 docs/cli/focused-workspace-container-padding.md create mode 100644 docs/cli/focused-workspace-padding.md create mode 100644 docs/cli/global-work-area-offset.md create mode 100644 docs/cli/monitor-work-area-offset.md create mode 100644 docs/cli/toggle-window-based-work-area-offset.md create mode 100644 docs/cli/workspace-padding.md create mode 100644 docs/cli/workspace-work-area-offset.md create mode 100644 docs/usage/padding-and-offsets.md create mode 100644 komorebi/tests/padding.rs diff --git a/README.md b/README.md index c7a87e3f..81f544b5 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,8 @@ is a strip of columns that runs past the edges of the monitor and scrolls to the window that has the focus. `minimize` and `close` ask KWin to minimize or close the focused window, `unmanage` takes it out of the layout until `manage` takes it back, and `toggle-pause` stops the daemon acting on events and orders -until it is resumed. +until it is resumed. The padding commands set the gaps around the tiles, and +the work area offsets keep parts of a monitor free of tiles. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/adjust-container-padding.md b/docs/cli/adjust-container-padding.md new file mode 100644 index 00000000..496cff5a --- /dev/null +++ b/docs/cli/adjust-container-padding.md @@ -0,0 +1,19 @@ +```text +Adjust container padding on the focused workspace + +Usage: adjust-container-padding + +Arguments: + + Possible values: + - increase: Increase + - decrease: Decrease + + + Pixels to adjust by as an integer + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/adjust-workspace-padding.md b/docs/cli/adjust-workspace-padding.md new file mode 100644 index 00000000..32add7c5 --- /dev/null +++ b/docs/cli/adjust-workspace-padding.md @@ -0,0 +1,19 @@ +```text +Adjust workspace padding on the focused workspace + +Usage: adjust-workspace-padding + +Arguments: + + Possible values: + - increase: Increase + - decrease: Decrease + + + Pixels to adjust by as an integer + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/container-padding.md b/docs/cli/container-padding.md new file mode 100644 index 00000000..4dd1bfe5 --- /dev/null +++ b/docs/cli/container-padding.md @@ -0,0 +1,20 @@ +```text +Set the container padding for the specified workspace + +Usage: container-padding + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + + + Pixels to pad with as an integer + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focused-workspace-container-padding.md b/docs/cli/focused-workspace-container-padding.md new file mode 100644 index 00000000..45302a9a --- /dev/null +++ b/docs/cli/focused-workspace-container-padding.md @@ -0,0 +1,14 @@ +```text +Set container padding on the focused workspace + +Usage: focused-workspace-container-padding + +Arguments: + + Pixels size to set as an integer + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focused-workspace-padding.md b/docs/cli/focused-workspace-padding.md new file mode 100644 index 00000000..de2ebe2d --- /dev/null +++ b/docs/cli/focused-workspace-padding.md @@ -0,0 +1,14 @@ +```text +Set workspace padding on the focused workspace + +Usage: focused-workspace-padding + +Arguments: + + Pixels size to set as an integer + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/global-work-area-offset.md b/docs/cli/global-work-area-offset.md new file mode 100644 index 00000000..8dbb1cd6 --- /dev/null +++ b/docs/cli/global-work-area-offset.md @@ -0,0 +1,23 @@ +```text +Set offsets to exclude parts of the work area from tiling + +Usage: global-work-area-offset + +Arguments: + + Size of the left work area offset (set right to left * 2 to maintain right padding) + + + Size of the top work area offset (set bottom to the same value to maintain bottom padding) + + + Size of the right work area offset + + + Size of the bottom work area offset + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/monitor-work-area-offset.md b/docs/cli/monitor-work-area-offset.md new file mode 100644 index 00000000..d01e1b7f --- /dev/null +++ b/docs/cli/monitor-work-area-offset.md @@ -0,0 +1,26 @@ +```text +Set offsets for a monitor to exclude parts of the work area from tiling + +Usage: monitor-work-area-offset + +Arguments: + + Monitor index (zero-indexed) + + + Size of the left work area offset (set right to left * 2 to maintain right padding) + + + Size of the top work area offset (set bottom to the same value to maintain bottom padding) + + + Size of the right work area offset + + + Size of the bottom work area offset + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-window-based-work-area-offset.md b/docs/cli/toggle-window-based-work-area-offset.md new file mode 100644 index 00000000..a4814769 --- /dev/null +++ b/docs/cli/toggle-window-based-work-area-offset.md @@ -0,0 +1,10 @@ +```text +Toggle application of the window-based work area offset for the focused workspace + +Usage: toggle-window-based-work-area-offset + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/workspace-padding.md b/docs/cli/workspace-padding.md new file mode 100644 index 00000000..91728311 --- /dev/null +++ b/docs/cli/workspace-padding.md @@ -0,0 +1,20 @@ +```text +Set the workspace padding for the specified workspace + +Usage: workspace-padding + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + + + Pixels to pad with as an integer + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/workspace-work-area-offset.md b/docs/cli/workspace-work-area-offset.md new file mode 100644 index 00000000..34858b1b --- /dev/null +++ b/docs/cli/workspace-work-area-offset.md @@ -0,0 +1,29 @@ +```text +Set offsets for a workspace to exclude parts of the work area from tiling + +Usage: workspace-work-area-offset + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index (zero-indexed) + + + Size of the left work area offset (set right to left * 2 to maintain right padding) + + + Size of the top work area offset (set bottom to the same value to maintain bottom padding) + + + Size of the right work area offset + + + Size of the bottom work area offset + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index ef6a4405..276a3d20 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -85,8 +85,10 @@ element focused, so that "the focused workspace" or "the focused container" mean the same thing at every level. - A **monitor** ([`Monitor`]) is one of the backend's monitors: its bounds, its work area, - its padding, an optional work area offset, and its workspaces. It shows the focused one. -- A **workspace** ([`Workspace`]) has a layout, its padding, its containers, in order, and its + its padding, an optional work area offset, an optional window-based offset with the number of + windows up to which it applies, and its workspaces. It shows the focused one. +- A **workspace** ([`Workspace`]) has a layout, its padding, an optional work area offset of its + own, whether it takes the monitor's window-based offset, its containers, in order, and its floating windows, which are in no container and which the layout does not tile. - A **container** ([`Container`]) has its windows. A new window gets a container of its own. A container can be locked, which keeps it at its index while others are inserted, @@ -95,9 +97,11 @@ the same thing at every level. Everything else about the window, and every change to it, goes through the backend. Tiling a workspace ([`Workspace::update`]) is a function of this tree and a work area. The -monitor gives its focused workspace the work area, the padding to fall back to and the -offset ([`WorkspaceGlobals`]). The workspace takes the offset and its padding off the work -area, the layout gives one tile per container, in order, each shrunk by the container +monitor gives its focused workspace the work area, the padding to fall back to, the offset +(its own, or else the window manager's) and its window-based offset ([`WorkspaceGlobals`]). +The workspace takes the offset (its own, or else the monitor's) off the work area, then the +window-based offset while it has no more containers than the monitor's limit, then its +padding; the layout gives one tile per container, in order, each shrunk by the container padding, and every window of a container is asked to move onto its tile with `set_rect`. A tile is clamped to the work area, so it cannot reach onto a neighboring monitor. @@ -328,6 +332,15 @@ window manager. `UnmanagedWindowOperationBehaviour` sets focused is in no container of the focused workspace ([`WindowManager::handle_unmanaged_window_behaviour`]). +`WorkspacePadding`, `ContainerPadding` and their `FocusedWorkspace` forms set a workspace's own +padding, and `AdjustWorkspacePadding` and `AdjustContainerPadding` change the focused +workspace's by a number of pixels, which needs a padding of its own to change +([`WindowManager::adjust_workspace_padding`]). `WorkAreaOffset`, `MonitorWorkAreaOffset` and +`WorkspaceWorkAreaOffset` set the offset of the window manager, of a monitor or of a workspace, +and `ToggleWindowBasedWorkAreaOffset` sets whether the focused workspace takes its monitor's +window-based offset ([`Workspace::apply_window_based_work_area_offset`]). Each tiles the +workspace in front again, or every monitor. + `ResizeWindowEdge` and `ResizeWindowAxis` resize the focused container ([`WindowManager::resize_window`]). A resize is an adjustment of the container's tile, kept in [`Workspace::resize_dimensions`], one per container, which the layout applies when it calculates @@ -396,8 +409,8 @@ module's unit. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized window out, move the focus, move the focused container, change the layout, resize or - promote the focused container, float a window, lock a container, manage and unmanage a - window). + promote the focused container, float a window, lock a container, set the padding of a + workspace, manage and unmanage a window). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -484,6 +497,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A container moved onto a locked index is locked in its place, and the lock leaves the container that moved away | framework path: [`Workspace::swap_containers`] swaps through `LockableSequence`, which keeps the lock with the index | `test_swap_respecting_locks_various_cases`, `a_lock_stays_with_its_index_when_a_window_is_moved_onto_it` | `containers_mut()` is the `VecDeque` itself | | A window komorebi puts off the screen stays there | framework path: the bridge asks again for the position of a window KWin pulled back after a `geo` command, for a second, three times at most | `a window KWin pulls back from where it was asked to be is asked for the position again`, `a window that cannot go where it was asked is asked again three times at most`, `vm-scrolling` | a window that cannot go where it was asked is left where KWin put it | | A resize leaves no tile smaller than a tenth of the work area, or than it was | framework path: [`WindowManager::resize_window`] calculates the tiles for the adjustment, and cuts the adjustment down until they all fit | `a_resize_leaves_every_tile_about_a_tenth_of_the_work_area_wide_at_least` | the paddings are taken off afterwards, so a tile can end up a little smaller | +| The offset of a workspace wins over its monitor's, which wins over the window manager's | framework path: [`Monitor::update_workspace_globals`] gives the workspace the monitor's offset or else the window manager's, and [`Workspace::update`] takes its own before that | `the_workspaces_offset_wins_over_the_monitors_which_wins_over_the_global_one` | none | | A workspace whose tiling is off moves no window | framework path: [`Workspace::update`] returns before the layout when [`Workspace::tile`] is false | `with_tiling_off_no_window_is_moved_until_it_is_back_on` | none | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | none | @@ -604,7 +618,9 @@ A window is shown, and ends up on a tile: [`komorebi/tests/float.rs`](../../komorebi/tests/float.rs), floating; [`komorebi/tests/lock.rs`](../../komorebi/tests/lock.rs), locking; [`komorebi/tests/manage.rs`](../../komorebi/tests/manage.rs), minimizing, closing, - unmanaging and managing the focused window, and pausing. + unmanaging and managing the focused window, and pausing; + [`komorebi/tests/padding.rs`](../../komorebi/tests/padding.rs), the paddings and the work area + offsets. - [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, @@ -646,6 +662,9 @@ A window is shown, and ends up on a tile: [`WindowManager::resize_window`]: ../../komorebi/src/window_manager.rs [`WindowManager::toggle_float`]: ../../komorebi/src/window_manager.rs [`WindowManager::toggle_lock`]: ../../komorebi/src/window_manager.rs +[`WindowManager::adjust_workspace_padding`]: ../../komorebi/src/window_manager.rs +[`Workspace::apply_window_based_work_area_offset`]: ../../komorebi/src/workspace.rs +[`Monitor::update_workspace_globals`]: ../../komorebi/src/monitor.rs [`WindowManager::manage_focused_window`]: ../../komorebi/src/window_manager.rs [`WindowManager::unmanage_focused_window`]: ../../komorebi/src/window_manager.rs [`WindowManager::is_paused`]: ../../komorebi/src/window_manager.rs diff --git a/docs/index.md b/docs/index.md index e198924c..d4498d01 100644 --- a/docs/index.md +++ b/docs/index.md @@ -36,9 +36,11 @@ daemon, ask it what it is doing and read its log. [Moving windows](usage/moving-windows.md) how to move the focused window to another tile, [Layouts](usage/layouts.md) how to change the arrangement of the tiles, [Resizing windows](usage/resizing-windows.md) how to change the size of one, -[Floating windows](usage/floating-windows.md) how to take a window out of the layout, and +[Floating windows](usage/floating-windows.md) how to take a window out of the layout, [Managing windows](usage/managing-windows.md) how to minimize, close and unmanage the focused -window and pause the daemon. +window and pause the daemon, and +[Padding and work area offsets](usage/padding-and-offsets.md) how to put gaps around the tiles +and keep parts of a monitor free of them. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/padding-and-offsets.md b/docs/usage/padding-and-offsets.md new file mode 100644 index 00000000..a058c9a6 --- /dev/null +++ b/docs/usage/padding-and-offsets.md @@ -0,0 +1,76 @@ +# Padding and work area offsets + +komorebi tiles the windows of a workspace in the work area of its monitor, which is the part of +the monitor that KWin reports free of Plasma's panels. Padding puts gaps around the tiles, and an +offset keeps a part of the work area free of tiles. + +## Padding + +A workspace has two paddings, in pixels: + +- the **workspace padding**, between the edges of the work area and the tiles; +- the **container padding**, around each tile, so that two tiles side by side are twice that far + apart. + +A workspace that has no padding of its own takes 5 pixels for each. + +[`komorebic focused-workspace-padding`](../cli/focused-workspace-padding.md) and +[`komorebic focused-workspace-container-padding`](../cli/focused-workspace-container-padding.md) +set the paddings of the focused workspace, and +[`komorebic workspace-padding`](../cli/workspace-padding.md) and +[`komorebic container-padding`](../cli/container-padding.md) those of a workspace given by the +index of its monitor and its own, counted from 0. + +```sh +komorebic focused-workspace-padding 20 +komorebic focused-workspace-container-padding 10 +komorebic workspace-padding 0 1 0 +komorebic container-padding 0 1 0 +``` + +[`komorebic adjust-workspace-padding`](../cli/adjust-workspace-padding.md) and +[`komorebic adjust-container-padding`](../cli/adjust-container-padding.md) make a padding of the +focused workspace larger or smaller by a number of pixels. They change a padding the workspace +has of its own, set by one of the commands above: on a workspace that has none, the daemon logs +"there is no workspace padding" or "there is no container padding". A padding is not made +smaller than 0. + +```sh +komorebic adjust-workspace-padding increase 5 +komorebic adjust-container-padding decrease 5 +``` + +## Work area offsets + +An offset is four numbers. The first two move the top left corner of the work area right and +down; the last two make the work area narrower and shorter. So `0 40 0 40` keeps a strip of 40 +pixels at the top free, `0 0 0 40` a strip at the bottom, and `40 0 40 0` a strip on the left. + +[`komorebic global-work-area-offset`](../cli/global-work-area-offset.md) sets the offset of every +monitor, [`komorebic monitor-work-area-offset`](../cli/monitor-work-area-offset.md) the offset of +one monitor, which it takes instead of the global one, and +[`komorebic workspace-work-area-offset`](../cli/workspace-work-area-offset.md) the offset of one +workspace, which it takes instead of both. Each tiles every monitor again, as +[`komorebic retile`](../cli/retile.md) does. + +```sh +komorebic global-work-area-offset 0 40 0 40 +komorebic monitor-work-area-offset 1 0 0 0 40 +komorebic workspace-work-area-offset 0 2 40 0 40 0 +``` + +A monitor can also have a window-based offset, which applies on top of the other one while the +workspace in front has no more windows than the monitor's limit, 1 unless it is given another. +With a window-based offset, a window that is alone on a wide monitor does not have to take its +whole width. No command sets a monitor's window-based offset: it is part of the configuration of +a monitor. +[`komorebic toggle-window-based-work-area-offset`](../cli/toggle-window-based-work-area-offset.md) +turns it off for the focused workspace, and on again. + +```sh +komorebic toggle-window-based-work-area-offset +``` + +The daemon's state has the offsets as `work_area_offset` (of the window manager, of each monitor +and of each workspace), and a monitor's window-based offset and limit as +`window_based_work_area_offset` and `window_based_work_area_offset_limit`. diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index ca685759..d6701e68 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -363,6 +363,8 @@ pub enum SocketMessage { // Current Workspace Commands ManageFocusedWindow, UnmanageFocusedWindow, + AdjustContainerPadding(Sizing, i32), + AdjustWorkspacePadding(Sizing, i32), ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), ScrollingLayoutColumns(NonZeroUsize), @@ -380,6 +382,14 @@ pub enum SocketMessage { QuickLoad, Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf), Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + ContainerPadding(usize, usize, i32), + FocusedWorkspaceContainerPadding(i32), + WorkspacePadding(usize, usize, i32), + FocusedWorkspacePadding(i32), + WorkAreaOffset(Rect), + MonitorWorkAreaOffset(usize, Rect), + WorkspaceWorkAreaOffset(usize, usize, Rect), + ToggleWindowBasedWorkAreaOffset, ResizeDelta(i32), State, MonitorInformation, diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index c7c52cf7..7be95cea 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -54,6 +54,8 @@ pub struct Monitor { pub size: Rect, pub work_area_offset: Option, pub work_area_size: Rect, + pub window_based_work_area_offset: Option, + pub window_based_work_area_offset_limit: isize, pub container_padding: Option, pub workspace_padding: Option, } @@ -77,6 +79,8 @@ pub fn new( size, work_area_size, work_area_offset: None, + window_based_work_area_offset: None, + window_based_work_area_offset_limit: 1, workspaces, container_padding: None, workspace_padding: None, @@ -103,6 +107,8 @@ impl Monitor { size, work_area_offset: None, work_area_size, + window_based_work_area_offset: None, + window_based_work_area_offset_limit: 1, container_padding: None, workspace_padding: None, } @@ -137,6 +143,8 @@ impl Monitor { .or(Some(DEFAULT_WORKSPACE_PADDING.load(Ordering::Relaxed))); let work_area = self.work_area_size; let work_area_offset = self.work_area_offset.or(offset); + let window_based_work_area_offset = self.window_based_work_area_offset; + let window_based_work_area_offset_limit = self.window_based_work_area_offset_limit; if let Some(workspace) = self.workspaces_mut().get_mut(workspace_idx) { workspace.globals = WorkspaceGlobals { @@ -144,6 +152,8 @@ impl Monitor { workspace_padding, work_area, work_area_offset, + window_based_work_area_offset, + window_based_work_area_offset_limit, } } } diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 1964cf0c..1984fd7b 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -44,6 +44,18 @@ //! - **ToggleFloat** takes the focused window out of the layout into the floating windows of the //! workspace, which komorebi does not move, or puts a floating window back //! ([`WindowManager::toggle_float`]). +//! - **WorkspacePadding** and **ContainerPadding** set the paddings of a workspace given by the +//! index of its monitor and its own, **FocusedWorkspacePadding** and +//! **FocusedWorkspaceContainerPadding** those of the focused workspace, and +//! **AdjustWorkspacePadding** and **AdjustContainerPadding** make the focused workspace's larger +//! or smaller ([`WindowManager::set_workspace_padding`], +//! [`WindowManager::set_container_padding`], [`WindowManager::adjust_workspace_padding`], +//! [`WindowManager::adjust_container_padding`]). +//! - **WorkAreaOffset**, **MonitorWorkAreaOffset** and **WorkspaceWorkAreaOffset** set the work +//! area offset of every monitor, of one monitor or of one workspace, and tile every monitor again +//! (a monitor or a workspace that is not there is ignored), and +//! **ToggleWindowBasedWorkAreaOffset** sets whether the focused workspace takes its monitor's +//! window-based offset. //! - **Minimize** and **Close** ask the compositor to minimize or close the window that has the //! focus. The window leaves the layout when the compositor reports that it did. //! - **UnmanageFocusedWindow** takes the window that has the focus out of the layout and leaves it @@ -170,6 +182,9 @@ impl WindowManager { /// `UnlockMonitorWorkspaceContainer` is not there (a container that is not there is ignored). /// - The focused window cannot be floated or put back, for one of the reasons /// [`WindowManager::toggle_float`] gives. + /// - The monitor or the workspace of `WorkspacePadding` or `ContainerPadding` is not there, or + /// the focused workspace has no padding of its own for `AdjustWorkspacePadding` or + /// `AdjustContainerPadding` to change. /// - `Minimize`, `Close`, `ManageFocusedWindow` or `UnmanageFocusedWindow` when the compositor /// reports no focused window, or the backend refuses to minimize or close it. /// - The file of `QuickSave` or `Save` cannot be written, or the file of `QuickLoad` or @@ -370,6 +385,13 @@ impl WindowManager { SocketMessage::Retile => self.retile_all(false)?, SocketMessage::RetileWithResizeDimensions => self.retile_all(true)?, SocketMessage::ToggleLock => self.toggle_lock()?, + SocketMessage::ToggleWindowBasedWorkAreaOffset => { + let workspace = self.focused_workspace_mut()?; + workspace.apply_window_based_work_area_offset = + !workspace.apply_window_based_work_area_offset; + + self.retile_all(true)?; + } SocketMessage::ToggleTiling => { self.toggle_tiling()?; } @@ -439,9 +461,57 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::ContainerPadding(monitor_idx, workspace_idx, size) => { + self.set_container_padding(monitor_idx, workspace_idx, size)?; + } + SocketMessage::WorkspacePadding(monitor_idx, workspace_idx, size) => { + self.set_workspace_padding(monitor_idx, workspace_idx, size)?; + } + SocketMessage::FocusedWorkspaceContainerPadding(adjustment) => { + let focused_monitor_idx = self.focused_monitor_idx(); + + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + + self.set_container_padding(focused_monitor_idx, focused_workspace_idx, adjustment)?; + } + SocketMessage::FocusedWorkspacePadding(adjustment) => { + let focused_monitor_idx = self.focused_monitor_idx(); + + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + + self.set_workspace_padding(focused_monitor_idx, focused_workspace_idx, adjustment)?; + } + SocketMessage::WorkAreaOffset(rect) => { + self.work_area_offset = Option::from(rect); + self.retile_all(false)?; + } + SocketMessage::MonitorWorkAreaOffset(monitor_idx, rect) => { + if let Some(monitor) = self.monitors_mut().get_mut(monitor_idx) { + monitor.work_area_offset = Option::from(rect); + self.retile_all(false)?; + } + } + SocketMessage::WorkspaceWorkAreaOffset(monitor_idx, workspace_idx, rect) => { + if let Some(monitor) = self.monitors_mut().get_mut(monitor_idx) + && let Some(workspace) = monitor.workspaces_mut().get_mut(workspace_idx) + { + workspace.work_area_offset = Option::from(rect); + self.retile_all(false)? + } + } SocketMessage::ResizeDelta(delta) => { self.resize_delta = delta; } + SocketMessage::AdjustContainerPadding(sizing, adjustment) => { + self.adjust_container_padding(sizing, adjustment)?; + } + SocketMessage::AdjustWorkspacePadding(sizing, adjustment) => { + self.adjust_workspace_padding(sizing, adjustment)?; + } SocketMessage::ScrollingLayoutColumns(count) => { let focused_workspace = self.focused_workspace_mut()?; diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index a75fcbbf..2df52fed 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -76,6 +76,8 @@ impl From<&WindowManager> for State { size: monitor.size, work_area_size: monitor.work_area_size, work_area_offset: monitor.work_area_offset, + window_based_work_area_offset: monitor.window_based_work_area_offset, + window_based_work_area_offset_limit: monitor.window_based_work_area_offset_limit, workspaces: { let mut ws = Ring::default(); *ws.elements_mut() = monitor @@ -92,6 +94,9 @@ impl From<&WindowManager> for State { latest_layout: workspace.latest_layout.clone(), resize_dimensions: workspace.resize_dimensions.clone(), tile: workspace.tile, + work_area_offset: workspace.work_area_offset, + apply_window_based_work_area_offset: workspace + .apply_window_based_work_area_offset, globals: workspace.globals, preselected_container_idx: None, promotion_swap_container_idx: None, diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index e317fc3b..7275aee6 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1013,6 +1013,120 @@ impl WindowManager { } } + /// Gives the workspace at `workspace_idx` on the monitor at `monitor_idx` a workspace padding + /// of `size` pixels, around its tiles, and tiles the focused workspace again + /// + /// # Errors + /// + /// There is no monitor or no workspace at the index, or the focused workspace cannot be tiled + /// again. + #[tracing::instrument(skip(self))] + pub fn set_workspace_padding( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + size: i32, + ) -> eyre::Result<()> { + tracing::info!("setting workspace padding"); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("there is no monitor")?; + + workspace.workspace_padding = Option::from(size); + + self.update_focused_workspace(false, false) + } + + /// Gives the workspace at `workspace_idx` on the monitor at `monitor_idx` a container padding + /// of `size` pixels, around each tile, and tiles the focused workspace again + /// + /// # Errors + /// + /// There is no monitor or no workspace at the index, or the focused workspace cannot be tiled + /// again. + #[tracing::instrument(skip(self))] + pub fn set_container_padding( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + size: i32, + ) -> eyre::Result<()> { + tracing::info!("setting container padding"); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("there is no monitor")?; + + workspace.container_padding = Option::from(size); + + self.update_focused_workspace(false, false) + } + + /// Makes the workspace padding of the focused workspace `adjustment` pixels larger or smaller, + /// and tiles it again + /// + /// # Errors + /// + /// There is no focused workspace, it has no workspace padding of its own (set with + /// [`WindowManager::set_workspace_padding`]), or it cannot be tiled again. + #[tracing::instrument(skip(self))] + pub fn adjust_workspace_padding( + &mut self, + sizing: Sizing, + adjustment: i32, + ) -> eyre::Result<()> { + tracing::info!("adjusting workspace padding"); + + let workspace = self.focused_workspace_mut()?; + + let padding = workspace + .workspace_padding + .ok_or_eyre("there is no workspace padding")?; + + workspace.workspace_padding = Option::from(sizing.adjust_by(padding, adjustment)); + + self.update_focused_workspace(false, false) + } + + /// Makes the container padding of the focused workspace `adjustment` pixels larger or smaller, + /// and tiles it again + /// + /// # Errors + /// + /// There is no focused workspace, it has no container padding of its own (set with + /// [`WindowManager::set_container_padding`]), or it cannot be tiled again. + #[tracing::instrument(skip(self))] + pub fn adjust_container_padding( + &mut self, + sizing: Sizing, + adjustment: i32, + ) -> eyre::Result<()> { + tracing::info!("adjusting container padding"); + + let workspace = self.focused_workspace_mut()?; + + let padding = workspace + .container_padding + .ok_or_eyre("there is no container padding")?; + + workspace.container_padding = Option::from(sizing.adjust_by(padding, adjustment)); + + self.update_focused_workspace(false, false) + } + /// Asks the window manager to manage the window that has the focus in the compositor again /// after [`WindowManager::unmanage_focused_window`], by raising a /// [`WindowManagerEvent::Manage`] for it, which is handled like a window that opens diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index bd2ca5d7..edc3e7bc 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -37,6 +37,10 @@ pub struct Workspace { pub latest_layout: Vec, pub resize_dimensions: Vec>, pub tile: bool, + /// The work area offset of this workspace, which it takes instead of its monitor's + pub work_area_offset: Option, + /// Whether this workspace takes its monitor's window-based offset (true by default) + pub apply_window_based_work_area_offset: bool, #[serde(skip)] pub globals: WorkspaceGlobals, #[serde(skip_serializing_if = "Option::is_none")] @@ -56,11 +60,13 @@ impl Default for Workspace { container_padding: None, resize_dimensions: vec![], layout: Layout::Default(DefaultLayout::BSP), + work_area_offset: None, latest_layout: vec![], layout_flip: None, layout_options: None, globals: Default::default(), tile: true, + apply_window_based_work_area_offset: true, floating_windows: Default::default(), preselected_container_idx: None, promotion_swap_container_idx: None, @@ -69,13 +75,15 @@ impl Default for Workspace { } #[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq)] -/// The work area a monitor gives the workspace it shows, and the padding and the offset the -/// workspace falls back to when it sets none of its own +/// The work area a monitor gives the workspace it shows, the padding and the offset the +/// workspace falls back to when it sets none of its own, and the monitor's window-based offset pub struct WorkspaceGlobals { pub container_padding: Option, pub workspace_padding: Option, pub work_area: Rect, pub work_area_offset: Option, + pub window_based_work_area_offset: Option, + pub window_based_work_area_offset_limit: isize, } /// `komorebi_layouts::Rect::percentage_within_horizontal_bounds`, which that crate compiles only @@ -532,7 +540,10 @@ impl Workspace { impl Workspace { /// Tiles the workspace: asks the layout for a tile per container in the work area, less the - /// offset and the workspace padding, and puts every window of each container on its tile. + /// offset (the workspace's own, or else the one its monitor gives it), the monitor's + /// window-based offset while there are no more containers than its limit and + /// [`Workspace::apply_window_based_work_area_offset`] is set, and the workspace padding, and + /// puts every window of each container on its tile. /// /// Containers that have no windows left are dropped first, except the one a preselection /// reserved, and so is a window that is in more than one container. A tile is clamped to the @@ -565,7 +576,9 @@ impl Workspace { .or(self.globals.workspace_padding) .unwrap_or_default(); let work_area = self.globals.work_area; - let work_area_offset = self.globals.work_area_offset; + let work_area_offset = self.work_area_offset.or(self.globals.work_area_offset); + let window_based_work_area_offset = self.globals.window_based_work_area_offset; + let window_based_work_area_offset_limit = self.globals.window_based_work_area_offset_limit; let mut adjusted_work_area = work_area_offset.map_or_else( || work_area, @@ -580,6 +593,23 @@ impl Workspace { }, ); + if self.containers().len() <= window_based_work_area_offset_limit as usize + && self.apply_window_based_work_area_offset + { + adjusted_work_area = window_based_work_area_offset.map_or_else( + || adjusted_work_area, + |offset| { + let mut with_offset = adjusted_work_area; + with_offset.left += offset.left; + with_offset.top += offset.top; + with_offset.right -= offset.right; + with_offset.bottom -= offset.bottom; + + with_offset + }, + ); + } + adjusted_work_area.add_padding(workspace_padding); self.enforce_resize_constraints(); diff --git a/komorebi/tests/padding.rs b/komorebi/tests/padding.rs new file mode 100644 index 00000000..92c5c936 --- /dev/null +++ b/komorebi/tests/padding.rs @@ -0,0 +1,244 @@ +//! The padding around and between the tiles, and the offsets that keep parts of the work area +//! free of tiles, against an in-memory desktop: the messages go in through +//! [`WindowManager::process_command`], and what comes out is where the backend was asked to put +//! the windows. +//! +//! The fake's one monitor is 1920x1080 with a work area of 1920x1050, and a workspace falls back to +//! a workspace padding and a container padding of 5 pixels each. +//! +//! Window ids are in the 28_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::Rect; +use komorebi::core::Sizing; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor, and a window for each of +/// `ids`, opened in that order +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmp-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + for &id in ids { + open(&fake, &mut wm, id); + } + + (fake, wm) +} + +fn open(fake: &Arc, wm: &mut WindowManager, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); +} + +fn send( + fake: &Arc, + wm: &mut WindowManager, + message: SocketMessage, +) -> color_eyre::Result<()> { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())) +} + +fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect { + Rect { + left, + top, + right, + bottom, + } +} + +/// A desktop with one window and no padding, so that the window's frame is its tile +fn one_window_without_padding(id: u32) -> (Arc, WindowManager) { + let (fake, mut wm) = desktop_with(&[id]); + send(&fake, &mut wm, SocketMessage::FocusedWorkspacePadding(0)).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::FocusedWorkspaceContainerPadding(0), + ) + .unwrap(); + assert_eq!(fake.rect_of(id), Some(rect(0, 0, 1920, 1050))); + (fake, wm) +} + +#[test] +fn the_paddings_of_the_focused_workspace_are_set_and_adjusted() { + let (fake, mut wm) = desktop_with(&[28_001]); + assert_eq!(fake.rect_of(28_001), Some(rect(10, 10, 1900, 1030))); + + // with no padding of its own, the workspace has none to adjust + assert_eq!( + send( + &fake, + &mut wm, + SocketMessage::AdjustWorkspacePadding(Sizing::Increase, 5) + ) + .map_err(|error| error.to_string()), + Err(String::from("there is no workspace padding")) + ); + + send(&fake, &mut wm, SocketMessage::FocusedWorkspacePadding(20)).unwrap(); + assert_eq!(fake.rect_of(28_001), Some(rect(25, 25, 1870, 1000))); + + send( + &fake, + &mut wm, + SocketMessage::FocusedWorkspaceContainerPadding(0), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_001), Some(rect(20, 20, 1880, 1010))); + + send( + &fake, + &mut wm, + SocketMessage::AdjustWorkspacePadding(Sizing::Increase, 5), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_001), Some(rect(25, 25, 1870, 1000))); + + send( + &fake, + &mut wm, + SocketMessage::AdjustContainerPadding(Sizing::Increase, 10), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_001), Some(rect(35, 35, 1850, 980))); + + // a padding is not made smaller than nothing: a decrease past 0 changes nothing + send( + &fake, + &mut wm, + SocketMessage::AdjustContainerPadding(Sizing::Decrease, 30), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_001), Some(rect(35, 35, 1850, 980))); +} + +#[test] +fn the_paddings_of_a_workspace_are_set_by_its_indices() { + let (fake, mut wm) = desktop_with(&[28_011]); + + send(&fake, &mut wm, SocketMessage::ContainerPadding(0, 0, 0)).unwrap(); + send(&fake, &mut wm, SocketMessage::WorkspacePadding(0, 0, 0)).unwrap(); + assert_eq!(fake.rect_of(28_011), Some(rect(0, 0, 1920, 1050))); + + assert_eq!( + send(&fake, &mut wm, SocketMessage::WorkspacePadding(1, 0, 0)) + .map_err(|error| error.to_string()), + Err(String::from("there is no monitor")) + ); +} + +#[test] +fn the_workspaces_offset_wins_over_the_monitors_which_wins_over_the_global_one() { + let (fake, mut wm) = one_window_without_padding(28_021); + + send( + &fake, + &mut wm, + SocketMessage::WorkAreaOffset(rect(0, 40, 0, 40)), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_021), Some(rect(0, 40, 1920, 1010))); + + send( + &fake, + &mut wm, + SocketMessage::MonitorWorkAreaOffset(0, rect(100, 0, 100, 0)), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_021), Some(rect(100, 0, 1820, 1050))); + + send( + &fake, + &mut wm, + SocketMessage::WorkspaceWorkAreaOffset(0, 0, rect(0, 0, 0, 200)), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_021), Some(rect(0, 0, 1920, 850))); + + // a monitor or a workspace that is not there is ignored + send( + &fake, + &mut wm, + SocketMessage::MonitorWorkAreaOffset(3, rect(0, 0, 0, 0)), + ) + .unwrap(); + send( + &fake, + &mut wm, + SocketMessage::WorkspaceWorkAreaOffset(0, 3, rect(0, 0, 0, 0)), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_021), Some(rect(0, 0, 1920, 850))); +} + +#[test] +fn the_window_based_offset_is_taken_up_to_its_window_limit_and_can_be_turned_off() { + let (fake, mut wm) = one_window_without_padding(28_031); + // the monitor's window-based offset applies while the workspace has at most one window + let monitor = wm.monitors_mut().get_mut(0).unwrap(); + monitor.window_based_work_area_offset = Some(rect(200, 0, 400, 0)); + assert_eq!(monitor.window_based_work_area_offset_limit, 1); + + send(&fake, &mut wm, SocketMessage::Retile).unwrap(); + assert_eq!(fake.rect_of(28_031), Some(rect(200, 0, 1520, 1050))); + + open(&fake, &mut wm, 28_032); + assert_eq!(fake.rect_of(28_031), Some(rect(0, 0, 960, 1050))); + assert_eq!(fake.rect_of(28_032), Some(rect(960, 0, 960, 1050))); + + fake.close_window_now(28_032); + with_backend(fake.clone(), || wm.process_event(removed(28_032))).unwrap(); + assert_eq!(fake.rect_of(28_031), Some(rect(200, 0, 1520, 1050))); + + send( + &fake, + &mut wm, + SocketMessage::ToggleWindowBasedWorkAreaOffset, + ) + .unwrap(); + assert_eq!(fake.rect_of(28_031), Some(rect(0, 0, 1920, 1050))); + + send( + &fake, + &mut wm, + SocketMessage::ToggleWindowBasedWorkAreaOffset, + ) + .unwrap(); + assert_eq!(fake.rect_of(28_031), Some(rect(200, 0, 1520, 1050))); +} + +fn removed(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Destroy( + SystemNotification::KWin(KWinNotification::WindowRemoved), + Window::from(id), + ) +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index c6d19657..3b9b64ea 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -18,6 +18,11 @@ //! tile, or the focus to it. //! - `toggle-float` takes the focused window out of the layout, or puts it back, and //! `toggle-lock` locks the focused container at its index, or unlocks it. +//! - `focused-workspace-padding`, `focused-workspace-container-padding`, `workspace-padding`, +//! `container-padding` and the two `adjust-*-padding` set the padding around the tiles and +//! between them, and `global-work-area-offset`, `monitor-work-area-offset`, +//! `workspace-work-area-offset` and `toggle-window-based-work-area-offset` keep parts of the work +//! area free of tiles. //! - `minimize` and `close` minimize and close the focused window, `unmanage` takes it out of //! the layout until `manage` takes it back, `unmanaged-window-operation-behaviour` sets whether //! the daemon carries out an order while the focused window is not one it tiles, and @@ -46,6 +51,7 @@ use komorebi_client::CycleDirection; use komorebi_client::DefaultLayout; use komorebi_client::OperationBehaviour; use komorebi_client::OperationDirection; +use komorebi_client::Rect; use komorebi_client::Sizing; use komorebi_client::SocketMessage; use komorebi_client::StateQuery; @@ -108,6 +114,66 @@ gen_enum_subcommand_args! { PromoteWindow: OperationDirection, } +macro_rules! gen_focused_workspace_padding_subcommand_args { + // SubCommand Pattern + ( $( $name:ident ),+ $(,)? ) => { + $( + #[derive(clap::Parser)] + pub struct $name { + /// Pixels size to set as an integer + size: i32, + } + )+ + }; +} + +gen_focused_workspace_padding_subcommand_args! { + FocusedWorkspaceContainerPadding, + FocusedWorkspacePadding, +} + +macro_rules! gen_padding_subcommand_args { + // SubCommand Pattern + ( $( $name:ident ),+ $(,)? ) => { + $( + #[derive(clap::Parser)] + pub struct $name { + /// Monitor index (zero-indexed) + monitor: usize, + /// Workspace index on the specified monitor (zero-indexed) + workspace: usize, + /// Pixels to pad with as an integer + size: i32, + } + )+ + }; +} + +gen_padding_subcommand_args! { + ContainerPadding, + WorkspacePadding, +} + +macro_rules! gen_padding_adjustment_subcommand_args { + // SubCommand Pattern + ( $( $name:ident ),+ $(,)? ) => { + $( + #[derive(clap::Parser)] + pub struct $name { + #[clap(value_enum)] + sizing: Sizing, + /// Pixels to adjust by as an integer + adjustment: i32, + } + )+ + }; +} + +gen_padding_adjustment_subcommand_args! { + AdjustContainerPadding, + AdjustWorkspacePadding, +} + #[derive(Parser)] struct Resize { #[clap(value_enum)] @@ -142,6 +208,48 @@ struct UnsubscribeSocket { socket: String, } +#[derive(Parser)] +struct GlobalWorkAreaOffset { + /// Size of the left work area offset (set right to left * 2 to maintain right padding) + left: i32, + /// Size of the top work area offset (set bottom to the same value to maintain bottom padding) + top: i32, + /// Size of the right work area offset + right: i32, + /// Size of the bottom work area offset + bottom: i32, +} + +#[derive(Parser)] +struct MonitorWorkAreaOffset { + /// Monitor index (zero-indexed) + monitor: usize, + /// Size of the left work area offset (set right to left * 2 to maintain right padding) + left: i32, + /// Size of the top work area offset (set bottom to the same value to maintain bottom padding) + top: i32, + /// Size of the right work area offset + right: i32, + /// Size of the bottom work area offset + bottom: i32, +} + +#[derive(Parser)] +struct WorkspaceWorkAreaOffset { + /// Monitor index (zero-indexed) + monitor: usize, + /// Workspace index (zero-indexed) + workspace: usize, + /// Size of the left work area offset (set right to left * 2 to maintain right padding) + left: i32, + /// Size of the top work area offset (set bottom to the same value to maintain bottom padding) + top: i32, + /// Size of the right work area offset + right: i32, + /// Size of the bottom work area offset + bottom: i32, +} + #[derive(Parser)] #[allow(clippy::struct_excessive_bools)] struct Start { @@ -288,6 +396,32 @@ enum SubCommand { /// Set the resize delta (used by resize-edge and resize-axis) #[clap(arg_required_else_help = true)] ResizeDelta(ResizeDelta), + // /// Set the invisible border dimensions around each window + // #[clap(arg_required_else_help = true)] + // InvisibleBorders(InvisibleBorders), + /// Set offsets to exclude parts of the work area from tiling + #[clap(arg_required_else_help = true)] + GlobalWorkAreaOffset(GlobalWorkAreaOffset), + /// Set offsets for a monitor to exclude parts of the work area from tiling + #[clap(arg_required_else_help = true)] + MonitorWorkAreaOffset(MonitorWorkAreaOffset), + /// Set offsets for a workspace to exclude parts of the work area from tiling + #[clap(arg_required_else_help = true)] + WorkspaceWorkAreaOffset(WorkspaceWorkAreaOffset), + /// Toggle application of the window-based work area offset for the focused workspace + ToggleWindowBasedWorkAreaOffset, + /// Set container padding on the focused workspace + #[clap(arg_required_else_help = true)] + FocusedWorkspaceContainerPadding(FocusedWorkspaceContainerPadding), + /// Set workspace padding on the focused workspace + #[clap(arg_required_else_help = true)] + FocusedWorkspacePadding(FocusedWorkspacePadding), + /// Adjust container padding on the focused workspace + #[clap(arg_required_else_help = true)] + AdjustContainerPadding(AdjustContainerPadding), + /// Adjust workspace padding on the focused workspace + #[clap(arg_required_else_help = true)] + AdjustWorkspacePadding(AdjustWorkspacePadding), /// Set the layout on the focused workspace #[clap(arg_required_else_help = true)] ChangeLayout(ChangeLayout), @@ -316,6 +450,12 @@ enum SubCommand { PromoteWindow(PromoteWindow), /// Force the retiling of all managed windows Retile, + /// Set the container padding for the specified workspace + #[clap(arg_required_else_help = true)] + ContainerPadding(ContainerPadding), + /// Set the workspace padding for the specified workspace + #[clap(arg_required_else_help = true)] + WorkspacePadding(WorkspacePadding), /// Toggle the paused state for all window tiling TogglePause, /// Toggle window tiling on the focused workspace @@ -519,6 +659,9 @@ fn main() -> eyre::Result<()> { SubCommand::PromoteWindow(args) => { send_message(&SocketMessage::PromoteWindow(args.operation_direction))?; } + SubCommand::ToggleWindowBasedWorkAreaOffset => { + send_message(&SocketMessage::ToggleWindowBasedWorkAreaOffset)?; + } SubCommand::ToggleTiling => { send_message(&SocketMessage::ToggleTiling)?; } @@ -537,6 +680,70 @@ fn main() -> eyre::Result<()> { SubCommand::ResizeDelta(args) => { send_message(&SocketMessage::ResizeDelta(args.pixels))?; } + SubCommand::MonitorWorkAreaOffset(args) => { + send_message(&SocketMessage::MonitorWorkAreaOffset( + args.monitor, + Rect { + left: args.left, + top: args.top, + right: args.right, + bottom: args.bottom, + }, + ))?; + } + SubCommand::GlobalWorkAreaOffset(args) => { + send_message(&SocketMessage::WorkAreaOffset(Rect { + left: args.left, + top: args.top, + right: args.right, + bottom: args.bottom, + }))?; + } + + SubCommand::WorkspaceWorkAreaOffset(args) => { + send_message(&SocketMessage::WorkspaceWorkAreaOffset( + args.monitor, + args.workspace, + Rect { + left: args.left, + top: args.top, + right: args.right, + bottom: args.bottom, + }, + ))?; + } + SubCommand::ContainerPadding(args) => { + send_message(&SocketMessage::ContainerPadding( + args.monitor, + args.workspace, + args.size, + ))?; + } + SubCommand::WorkspacePadding(args) => { + send_message(&SocketMessage::WorkspacePadding( + args.monitor, + args.workspace, + args.size, + ))?; + } + SubCommand::FocusedWorkspacePadding(args) => { + send_message(&SocketMessage::FocusedWorkspacePadding(args.size))?; + } + SubCommand::FocusedWorkspaceContainerPadding(args) => { + send_message(&SocketMessage::FocusedWorkspaceContainerPadding(args.size))?; + } + SubCommand::AdjustWorkspacePadding(args) => { + send_message(&SocketMessage::AdjustWorkspacePadding( + args.sizing, + args.adjustment, + ))?; + } + SubCommand::AdjustContainerPadding(args) => { + send_message(&SocketMessage::AdjustContainerPadding( + args.sizing, + args.adjustment, + ))?; + } SubCommand::ScrollingLayoutColumns(args) => { send_message(&SocketMessage::ScrollingLayoutColumns(args.count))?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 93f36fbd..9d8c8c79 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -297,6 +297,62 @@ fn the_promote_subcommands_send_their_message() { ); } +#[test] +fn the_padding_subcommands_send_the_workspace_and_the_pixels_they_are_given() { + sends( + &["focused-workspace-padding", "20"], + r#"{"type":"FocusedWorkspacePadding","content":20}"#, + ); + sends( + &["focused-workspace-container-padding", "10"], + r#"{"type":"FocusedWorkspaceContainerPadding","content":10}"#, + ); + sends( + &["workspace-padding", "0", "1", "12"], + r#"{"type":"WorkspacePadding","content":[0,1,12]}"#, + ); + sends( + &["container-padding", "1", "0", "8"], + r#"{"type":"ContainerPadding","content":[1,0,8]}"#, + ); + sends( + &["adjust-workspace-padding", "increase", "5"], + r#"{"type":"AdjustWorkspacePadding","content":["Increase",5]}"#, + ); + sends( + &["adjust-container-padding", "decrease", "3"], + r#"{"type":"AdjustContainerPadding","content":["Decrease",3]}"#, + ); +} + +#[test] +fn the_offset_subcommands_send_the_offset_they_are_given() { + sends( + &["global-work-area-offset", "10", "20", "30", "40"], + r#"{"type":"WorkAreaOffset","content":{"left":10,"top":20,"right":30,"bottom":40}}"#, + ); + sends( + &["monitor-work-area-offset", "1", "10", "20", "30", "40"], + r#"{"type":"MonitorWorkAreaOffset","content":[1,{"left":10,"top":20,"right":30,"bottom":40}]}"#, + ); + sends( + &[ + "workspace-work-area-offset", + "1", + "2", + "10", + "20", + "30", + "40", + ], + r#"{"type":"WorkspaceWorkAreaOffset","content":[1,2,{"left":10,"top":20,"right":30,"bottom":40}]}"#, + ); + sends( + &["toggle-window-based-work-area-offset"], + r#"{"type":"ToggleWindowBasedWorkAreaOffset"}"#, + ); +} + #[test] fn the_subcommands_about_the_focused_window_and_pausing_send_their_message() { sends(&["minimize"], r#"{"type":"Minimize"}"#); @@ -369,22 +425,29 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { assert_eq!( pages, [ + "adjust-container-padding.md", + "adjust-workspace-padding.md", "cancel-preselect.md", "change-layout.md", "close.md", "completions.md", + "container-padding.md", "cycle-focus.md", "cycle-layout.md", "cycle-move.md", "data-directory.md", "flip-layout.md", "focus.md", + "focused-workspace-container-padding.md", + "focused-workspace-padding.md", + "global-work-area-offset.md", "layout-ratios.md", "load-resize.md", "log.md", "manage.md", "minimize.md", "monitor-information.md", + "monitor-work-area-offset.md", "mouse-follows-focus.md", "move.md", "preselect-direction.md", @@ -410,9 +473,12 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "toggle-mouse-follows-focus.md", "toggle-pause.md", "toggle-tiling.md", + "toggle-window-based-work-area-offset.md", "unmanage.md", "unmanaged-window-operation-behaviour.md", "unsubscribe-socket.md", + "workspace-padding.md", + "workspace-work-area-offset.md", ] ); diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 118fc25a..e2d6b5f3 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -192,6 +192,26 @@ toggle-tiling toggle-tiling toggle-pause toggle-pause +global-work-area-offset 10 10 20 20 +global-work-area-offset 0 0 0 0 +monitor-work-area-offset 0 10 10 20 20 +monitor-work-area-offset 0 0 0 0 0 +workspace-work-area-offset 0 0 10 10 20 20 +workspace-work-area-offset 0 0 0 0 0 0 +toggle-window-based-work-area-offset +toggle-window-based-work-area-offset +focused-workspace-container-padding 20 +focused-workspace-container-padding 10 +focused-workspace-padding 20 +focused-workspace-padding 10 +adjust-container-padding increase 5 +adjust-container-padding decrease 5 +adjust-workspace-padding increase 5 +adjust-workspace-padding decrease 5 +container-padding 0 0 12 +container-padding 0 0 10 +workspace-padding 0 0 12 +workspace-padding 0 0 10 unmanaged-window-operation-behaviour op unmanaged-window-operation-behaviour no-op unmanaged-window-operation-behaviour op From 1b10611022499877bbdca86aede84e2e1fa4c7ef Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 17:24:36 -0700 Subject: [PATCH 028/255] feat(wm): ignore, manage and float rules komorebi managed every normal window that is alive, and there was no way to keep an application out of the layout. The rule engine decides whether a window is managed: an ignore rule keeps the windows it matches out, unless a manage rule matches them too, and a float rule puts a window in the floating windows of its workspace when it opens. A rule matches a window by its title, its executable, its class or the path of its executable. Plasma's shell and KRunner are ignored from the start. `komorebic ignore-rule` and `manage-rule` add a rule, `session-float-rule` floats the focused window and the windows like it until the daemon stops, `clear-session-float-rules` removes those rules, and `global-state` shows the rules. The `DebugWindow` message says why a window is managed or not. Applications often open a window before they give it its title, so the bridge now reports a title change, and a window komorebi does not have is asked about again when its title changes, for a rule on the title to decide. The vm-commands sweep adds and shows rules, and a section of its own checks that a window an ignore rule matches by its first title is tiled once it has another. vm-kwin-events checks that a window giving itself another title reaches the daemon as a title update. --- Cargo.lock | 13 + README.md | 5 +- docs/cli/clear-session-float-rules.md | 10 + docs/cli/global-state.md | 10 + docs/cli/ignore-rule.md | 21 + docs/cli/manage-rule.md | 21 + docs/cli/session-float-rule.md | 10 + docs/cli/session-float-rules.md | 10 + docs/dev/ARCHITECTURE.md | 48 +- docs/index.md | 2 + docs/usage/managing-windows.md | 9 +- docs/usage/rules.md | 71 +++ komorebi/Cargo.toml | 1 + komorebi/src/core/mod.rs | 12 + komorebi/src/desktop.rs | 7 +- komorebi/src/kwin/bridge.js | 11 +- komorebi/src/kwin/bridge.test.js | 16 + komorebi/src/kwin/kwin-api.d.ts | 1 + komorebi/src/kwin/state.rs | 34 ++ komorebi/src/lib.rs | 31 ++ komorebi/src/process_command.rs | 203 +++++++- komorebi/src/process_event.rs | 101 +++- komorebi/src/state.rs | 65 +++ komorebi/src/window.rs | 597 +++++++++++++++++++++++- komorebi/src/window_manager.rs | 2 +- komorebi/src/window_manager_event.rs | 8 +- komorebi/tests/rule_commands.rs | 238 ++++++++++ komorebi/tests/rules.rs | 74 +++ komorebic/src/main.rs | 64 +++ komorebic/tests/cli.rs | 44 ++ nix/tests/vm/suites/commands/test.py | 50 +- nix/tests/vm/suites/kwin-events/test.py | 23 +- 32 files changed, 1755 insertions(+), 57 deletions(-) create mode 100644 docs/cli/clear-session-float-rules.md create mode 100644 docs/cli/global-state.md create mode 100644 docs/cli/ignore-rule.md create mode 100644 docs/cli/manage-rule.md create mode 100644 docs/cli/session-float-rule.md create mode 100644 docs/cli/session-float-rules.md create mode 100644 docs/usage/rules.md create mode 100644 komorebi/tests/rule_commands.rs create mode 100644 komorebi/tests/rules.rs diff --git a/Cargo.lock b/Cargo.lock index d269c192..5bc70386 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -987,6 +987,7 @@ dependencies = [ "nanoid", "parking_lot", "pastey", + "regex", "schemars 1.2.3", "serde", "serde_json_lenient", @@ -1517,6 +1518,18 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + [[package]] name = "regex-automata" version = "0.4.18" diff --git a/README.md b/README.md index 81f544b5..5a6a1b70 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,10 @@ the window that has the focus. `minimize` and `close` ask KWin to minimize or close the focused window, `unmanage` takes it out of the layout until `manage` takes it back, and `toggle-pause` stops the daemon acting on events and orders until it is resumed. The padding commands set the gaps around the tiles, and -the work area offsets keep parts of a monitor free of tiles. +the work area offsets keep parts of a monitor free of tiles. Rules decide which +windows are managed at all: `ignore-rule` keeps an application out of the +layout, `manage-rule` tiles it whatever the ignore rules say, and +`session-float-rule` floats the focused window and the windows like it. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/clear-session-float-rules.md b/docs/cli/clear-session-float-rules.md new file mode 100644 index 00000000..698c8f51 --- /dev/null +++ b/docs/cli/clear-session-float-rules.md @@ -0,0 +1,10 @@ +```text +Clear all session float rules + +Usage: clear-session-float-rules + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/global-state.md b/docs/cli/global-state.md new file mode 100644 index 00000000..2db19928 --- /dev/null +++ b/docs/cli/global-state.md @@ -0,0 +1,10 @@ +```text +Show a JSON representation of the current global state + +Usage: global-state + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/ignore-rule.md b/docs/cli/ignore-rule.md new file mode 100644 index 00000000..832fa7a8 --- /dev/null +++ b/docs/cli/ignore-rule.md @@ -0,0 +1,21 @@ +```text +Add a rule to ignore the specified application + +Usage: ignore-rule + +Arguments: + + Possible values: + - exe: Executable name + - class: Role or subrole + - title: Window title + - path: Executable path + + + Identifier as a string + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/manage-rule.md b/docs/cli/manage-rule.md new file mode 100644 index 00000000..7ded06f9 --- /dev/null +++ b/docs/cli/manage-rule.md @@ -0,0 +1,21 @@ +```text +Add a rule to always manage the specified application + +Usage: manage-rule + +Arguments: + + Possible values: + - exe: Executable name + - class: Role or subrole + - title: Window title + - path: Executable path + + + Identifier as a string + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/session-float-rule.md b/docs/cli/session-float-rule.md new file mode 100644 index 00000000..dbe3f86b --- /dev/null +++ b/docs/cli/session-float-rule.md @@ -0,0 +1,10 @@ +```text +Add a rule to float the foreground window for the rest of this session + +Usage: session-float-rule + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/session-float-rules.md b/docs/cli/session-float-rules.md new file mode 100644 index 00000000..9e741f33 --- /dev/null +++ b/docs/cli/session-float-rules.md @@ -0,0 +1,10 @@ +```text +Show all session float rules + +Usage: session-float-rules + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 276a3d20..22c68945 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -29,6 +29,9 @@ its place here. itself: a command asks it to manage the focused window, or to stop managing it. - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order (focus a window, move it, change the layout, resize it, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). +- **Rule**: a condition on a window's title, executable, class or path ([`MatchingRule`]), in + one of the process-wide lists that decide whether a window is managed (the ignore and the + manage rules) and whether it floats when it opens (the float rules). - **Direction**: where an order goes from the focused container: a side of its tile ([`OperationDirection`]), or the next or the previous container of the workspace ([`CycleDirection`]). @@ -108,9 +111,9 @@ tile is clamped to the work area, so it cannot reach onto a neighboring monitor. The [`WindowManager`] keeps the monitors, the windows the user minimized (they are in no workspace until they are restored), and an index from each window it manages to the monitor and workspace that have it. It is loaded from the backend at startup: every -monitor, and every open window that is normal, alive and not minimized, on the focused -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. +monitor, and every open window that is normal, alive, not minimized and not ignored by a +rule, on the focused 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 @@ -324,9 +327,25 @@ area, and its id goes into a list of unmanaged windows that `handle_event` check on any other event about a window; a `Manage` takes the id out of the list and is handled like a `Show`. A `Destroy` takes the id out of the list too. +Whether a window is managed is [`Window::should_manage`]: the window has to be alive and normal, +and then the rules decide ([`should_act`]). An ignore rule that matches keeps the window out +unless a manage rule matches it too. The float rules do not decide whether a window is managed, +but a `Show` puts a window one matches in the workspace's floating windows instead of a container +(a `Manage` does not ask them). The rules live in process-wide lists in `lib.rs`: +`IgnoreRule` and `ManageRule` add a rule that names an application by one of the four +([`ApplicationIdentifier`]), and take the windows that it names exactly out of the containers of +the workspaces in front; `SessionFloatRule` adds a float rule made of the focused window's +executable, title and class, all three to be equal, and floats it, and `ClearSessionFloatRules` +takes those rules out again. `GlobalState` answers with the ignore and the manage rules +([`GlobalState`]), and `DebugWindow` with what [`Window::should_manage`] read of a window and +which rules matched ([`RuleDebug`]). A rule decides when a window is shown; the bridge reports +a title change (`caption`), which is a `TitleUpdate` event, and a `TitleUpdate` about a window +the index does not have, and that is not minimized, is sent again as a `Show`, so that a rule +about the title it has now decides. + `TogglePause` sets [`WindowManager::is_paused`]: while it is set, `handle_event` returns at once -for every event, and [`read_commands_uds`] hands only `TogglePause`, `State` and `Stop` to the -window manager. `UnmanagedWindowOperationBehaviour` sets +for every event, and [`read_commands_uds`] hands only `TogglePause`, `State`, `GlobalState` and +`Stop` to the window manager. `UnmanagedWindowOperationBehaviour` sets [`WindowManager::unmanaged_window_operation_behaviour`]: with `NoOp`, [`WindowManager::process_command`] refuses every message while the window the compositor has focused is in no container of the focused workspace @@ -402,7 +421,7 @@ module's unit. holding one the same accessors (`containers()`, `focused_container_mut()`, ...). - [`monitor`](../../komorebi/src/monitor.rs), [`workspace`](../../komorebi/src/workspace.rs), [`container`](../../komorebi/src/container.rs), [`window`](../../komorebi/src/window.rs): - the four levels of the tree. + the four levels of the tree; `window` also has the rule engine ([`should_act`]). - [`lockable_sequence`](../../komorebi/src/lockable_sequence.rs): inserting, removing and swapping in a list where some elements are locked in place, which is how a workspace changes its containers. @@ -475,9 +494,9 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none | | A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none | | A locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window`, `test_locked_containers_remove_window`, `a_window_that_opens_does_not_push_a_locked_container_from_its_index` | `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 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`, `an_ignore_rule_keeps_a_window_unmanaged` | `ManageRule` | | A window the user unmanaged stays out of the layout until it is managed again | framework path: `handle_event` checks the list of unmanaged windows before it acts on any event but a removal | `unmanage_takes_the_focused_window_out_until_manage_takes_it_back` | none | -| A paused window manager moves no window | framework path: `handle_event` returns before anything else, and [`read_commands_uds`] drops every message but `TogglePause`, `State` and `Stop` | `while_paused_no_event_changes_the_layout_and_manage_takes_in_a_window_it_missed`, `while_paused_only_toggle_pause_state_and_stop_are_handled` | none | +| A paused window manager moves no window | framework path: `handle_event` returns before anything else, and [`read_commands_uds`] drops every message but `TogglePause`, `State`, `GlobalState` and `Stop` | `while_paused_no_event_changes_the_layout_and_manage_takes_in_a_window_it_missed`, `while_paused_only_toggle_pause_state_and_stop_are_handled` | 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 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 | @@ -525,7 +544,9 @@ A window is shown, and ends up on a tile: [`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. + whether the window is alive and normal, and then the rules whether it is to be managed. If + it is not, the event changes nothing. If a float rule matches it, it goes into the + workspace's floating windows and the steps below do not apply. 3. The index of managed windows is rebuilt from the containers. If the workspace in front already has the window, or the index has it on another monitor or workspace, the event creates nothing. @@ -620,7 +641,9 @@ A window is shown, and ends up on a tile: [`komorebi/tests/manage.rs`](../../komorebi/tests/manage.rs), minimizing, closing, unmanaging and managing the focused window, and pausing; [`komorebi/tests/padding.rs`](../../komorebi/tests/padding.rs), the paddings and the work area - offsets. + offsets; [`komorebi/tests/rules.rs`](../../komorebi/tests/rules.rs) and + [`komorebi/tests/rule_commands.rs`](../../komorebi/tests/rule_commands.rs), the rules and the + messages that add and show them. - [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, @@ -645,6 +668,11 @@ A window is shown, and ends up on a tile: [`Container`]: ../../komorebi/src/container.rs [`Window`]: ../../komorebi/src/window.rs [`Window::should_manage`]: ../../komorebi/src/window.rs +[`should_act`]: ../../komorebi/src/window.rs +[`RuleDebug`]: ../../komorebi/src/window.rs +[`GlobalState`]: ../../komorebi/src/state.rs +[`MatchingRule`]: ../../komorebi/src/core/config_generation.rs +[`ApplicationIdentifier`]: ../../komorebi/src/core/mod.rs [`Window::set_position`]: ../../komorebi/src/window.rs [`Workspace::new_container_for_window`]: ../../komorebi/src/workspace.rs [`WindowManager`]: ../../komorebi/src/window_manager.rs diff --git a/docs/index.md b/docs/index.md index d4498d01..77f40c0d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -41,6 +41,8 @@ daemon, ask it what it is doing and read its log. window and pause the daemon, and [Padding and work area offsets](usage/padding-and-offsets.md) how to put gaps around the tiles and keep parts of a monitor free of them. +[Rules](usage/rules.md) explains how to keep an application out of the layout, always tile it, or +float its windows. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/managing-windows.md b/docs/usage/managing-windows.md index f12cba3a..80c3a086 100644 --- a/docs/usage/managing-windows.md +++ b/docs/usage/managing-windows.md @@ -1,7 +1,8 @@ # Managing windows komorebi tiles every normal application window that KWin reports, and leaves dialogs, splash -screens and other windows that are not for tiling alone. The commands here act on the window +screens and other windows that are not for tiling alone, and the windows that [rules](rules.md) +say to ignore. The commands here act on the window that has the focus in KWin, take a window out of the layout or back into it, and pause the daemon. @@ -34,7 +35,7 @@ komorebic manage ``` `komorebic manage` also takes in a window komorebi missed, such as one that opened while the -daemon was paused. The daemon forgets an unmanaged window when it closes, and when the daemon +daemon was paused, but not a window an ignore rule covers. The daemon forgets an unmanaged window when it closes, and when the daemon stops. ## Commands while the focused window is not tiled @@ -58,8 +59,8 @@ sets the behavior back to `op`: give the focus to a tiled window first. [`komorebic toggle-pause`](../cli/toggle-pause.md) pauses the daemon, and the same command resumes it. While it is paused, komorebi does not act on what KWin reports, so it moves no -window, and of its commands it carries out only `toggle-pause`, `state` and `stop`. The daemon's -state says whether it is paused, as `is_paused`. +window, and of its commands it carries out only `toggle-pause`, `state`, `global-state` and +`stop`. The daemon's state says whether it is paused, as `is_paused`. ```sh komorebic toggle-pause diff --git a/docs/usage/rules.md b/docs/usage/rules.md new file mode 100644 index 00000000..9bd34a9b --- /dev/null +++ b/docs/usage/rules.md @@ -0,0 +1,71 @@ +# Rules + +A rule names an application by one of four things about its windows, and says what komorebi does +with them: + +- `exe`: the name of the program's executable, such as `kate`; +- `class`: the app id of a Wayland window, such as `org.kde.kate`, or the class of an X11 window; +- `title`: the title of the window; +- `path`: the full path of the executable, such as `/usr/bin/kate`. + +[`komorebic state`](../cli/state.md) shows them for every window komorebi has, as the `title`, +`exe`, `class` and `path` of its `details`. + +## Ignoring an application + +[`komorebic ignore-rule`](../cli/ignore-rule.md) makes komorebi leave the windows of an +application alone. A rule given this way matches a title or a class that starts or ends with what +it names, and an executable or a path that is exactly what it names. The windows it matches are +not tiled when they open, and the tiled windows of the workspaces in front whose executable, +class, title or path is exactly what it names leave the layout. + +```sh +komorebic ignore-rule exe steam +komorebic ignore-rule class org.kde.kcalc +komorebic ignore-rule title "Picture-in-Picture" +``` + +`komorebic float-rule` is the same command. Plasma's desktop and panels (`plasmashell`) and +KRunner are ignored from the start. + +[`komorebic manage-rule`](../cli/manage-rule.md) makes komorebi tile the windows of an +application that an ignore rule covers, from the next one that opens. + +```sh +komorebic manage-rule class org.kde.plasmashell +``` + +[`komorebic manage`](managing-windows.md#taking-a-window-out-of-the-layout) does not take in a +window an ignore rule covers: a manage rule does. + +## When a rule decides + +A rule decides when a window opens. Applications often open a window before they give it its +title, so the title a rule sees then can be a placeholder. When the title of a window komorebi +does not have changes, komorebi asks the rules again, so a window that a title rule ignored while +it had its first title is tiled once its title no longer matches. A window komorebi tiles stays +tiled whatever its title becomes. + +## Floating the windows of an application + +[`komorebic session-float-rule`](../cli/session-float-rule.md) takes the focused window out of +the layout into the floating windows of its workspace, and adds a rule that floats every window +that opens with the same executable, class and title. +[`komorebic session-float-rules`](../cli/session-float-rules.md) shows those rules, and +[`komorebic clear-session-float-rules`](../cli/clear-session-float-rules.md) removes them: the +windows that float already stay floating. + +```sh +komorebic session-float-rule +komorebic session-float-rules +komorebic clear-session-float-rules +``` + +A window that a float rule matches floats when it opens, and +[`komorebic toggle-float`](floating-windows.md) puts one in the layout. + +## How long rules last + +The rules given with these commands last until the daemon stops. +[`komorebic global-state`](../cli/global-state.md) shows the ignore and the manage rules the daemon +has, and its data directory. diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 674252c1..fe19b180 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -17,6 +17,7 @@ lazy_static = { workspace = true } nanoid = "0.4" parking_lot = "0.12" pastey = { workspace = true } +regex = "1" schemars = { workspace = true, optional = true } serde = { workspace = true } serde_json = { workspace = true, features = ["preserve_order"] } diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index d6701e68..dfcddc89 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -391,7 +391,18 @@ pub enum SocketMessage { WorkspaceWorkAreaOffset(usize, usize, Rect), ToggleWindowBasedWorkAreaOffset, ResizeDelta(i32), + SessionFloatRule, + SessionFloatRules, + ClearSessionFloatRules, + #[serde(alias = "FloatRule")] + IgnoreRule(ApplicationIdentifier, String), + ManageRule(ApplicationIdentifier, String), + // IdentifyObjectNameChangeApplication(ApplicationIdentifier, String), + // IdentifyTrayApplication(ApplicationIdentifier, String), + // IdentifyLayeredApplication(ApplicationIdentifier, String), + // IdentifyBorderOverflowApplication(ApplicationIdentifier, String), State, + GlobalState, MonitorInformation, Query(StateQuery), MouseFollowsFocus(bool), @@ -403,6 +414,7 @@ pub enum SocketMessage { RemoveSubscriberSocket(String), // AddSubscriberPipe(String), // RemoveSubscriberPipe(String), + DebugWindow(u32), } impl SocketMessage { diff --git a/komorebi/src/desktop.rs b/komorebi/src/desktop.rs index 65eee012..20444314 100644 --- a/komorebi/src/desktop.rs +++ b/komorebi/src/desktop.rs @@ -40,6 +40,7 @@ use crate::backend::backend; use crate::container::Container; use crate::core::Rect; use crate::monitor::Monitor; +use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; use color_eyre::eyre; @@ -144,7 +145,8 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { /// monitor they are on, so that starting komorebi tiles what is on screen. /// /// A window is on the monitor whose bounds contain its middle. A window that is minimized, that -/// komorebi does not manage ([`Window::should_manage`]), or that is on no monitor is left alone. +/// komorebi does not manage ([`Window::should_manage`]: not a normal window, or one the rules +/// ignore), or that is on no monitor is left alone. /// Nothing is moved: tiling is [`WindowManager::retile_all`]'s job. /// /// # Errors @@ -192,7 +194,8 @@ pub fn load_workspace_information(wm: &mut WindowManager) -> eyre::Result<()> { } let window = Window::from(info.id); - if !window.should_manage() { + let mut rule_debug = RuleDebug::default(); + if !window.should_manage(None, &mut rule_debug)? { continue; } diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index 2c4cab02..3c7121d3 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -44,8 +44,9 @@ /** * 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. + * `activated` with no `id` means no window has the focus; `caption` is a window's new title; + * `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, @@ -56,9 +57,10 @@ * @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: "caption", id: string, caption: string }} Caption * @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 + * @typedef {Snapshot | Added | Removed | Activated | Minimized | Geometry | Caption | CursorAnswer | Failed} BridgeEvent */ /** @@ -267,6 +269,9 @@ function track(w, announce) { w.minimizedChanged.connect(function () { emit("minimized", { id: id, v: !!w.minimized }); }); + w.captionChanged.connect(function () { + emit("caption", { id: id, caption: String(w.caption) }); + }); } workspace.windowAdded.connect(function (w) { diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index 2d51ddae..d8abd4b0 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -86,6 +86,7 @@ function window({ desktops: [], frameGeometryChanged: new Signal(), minimizedChanged: new Signal(), + captionChanged: new Signal(), closeWindow: () => assert.fail("a window that is in no KWin was closed"), ...rest, }; @@ -347,6 +348,21 @@ test("a window maximized one way only is not maximized", () => { ); }); +test("a title change is reported with the title the window has now", () => { + const w = window({ id: "{beta}", caption: "beta" }); + const k = kwin({ windows: [w] }); + + w.caption = "beta-renamed"; + w.captionChanged.emit(); + + assert.deepStrictEqual(k.events().at(-1), { + type: "caption", + seq: 2, + id: "{beta}", + caption: "beta-renamed", + }); +}); + test("every call goes to the daemon's names, with one JSON string", () => { const k = kwin(); k.answer([]); diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts index 4b1e077e..18e4e6c9 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -85,6 +85,7 @@ interface KWinWindow { readonly desktops: VirtualDesktop[]; readonly frameGeometryChanged: Signal<[oldGeometry: QRectF]>; readonly minimizedChanged: Signal; + readonly captionChanged: Signal; closeWindow(): void; } diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index 2bd92a99..8324d6d1 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -330,6 +330,7 @@ impl Table { /// with no `id`, took it away from every window. /// - `minimized`: a window was minimized or brought back ([`WindowManagerEvent::Minimize`], /// [`WindowManagerEvent::Restore`]). + /// - `caption`: a window's title changed ([`WindowManagerEvent::TitleUpdate`]). /// - `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. @@ -345,6 +346,7 @@ impl Table { Some("removed") => self.on_removed(event, now), Some("activated") => self.on_activated(event), Some("minimized") => self.on_minimized(event), + Some("caption") => self.on_caption(event), Some("geometry") => { if let Some(entry) = self.entry_mut(event) { entry.info.rect = rect(&event["geo"]); @@ -514,6 +516,26 @@ impl Table { WindowManagerEvent::Restore(kwin(KWinNotification::WindowRestored), window) })] } + + fn on_caption(&mut self, event: &Value) -> Vec { + let Some(id) = self.id_of(event) else { + return vec![]; + }; + + let Some(entry) = self.windows.get_mut(&id) else { + return vec![]; + }; + entry.info.title = event["caption"].as_str().unwrap_or_default().to_string(); + + if entry.info.normal { + vec![Output::Event(WindowManagerEvent::TitleUpdate( + kwin(KWinNotification::CaptionChanged), + Window::from(id), + ))] + } else { + vec![] + } + } } /// The executable of a process, by name and by path. @@ -858,6 +880,18 @@ mod tests { ); } + #[test] + fn a_title_change_raises_a_title_update() { + let mut t = table(vec![win("a", &["d1"])]); + let out = t.handle( + &json!({ "type": "caption", "id": "a", "caption": "renamed" }), + Instant::now(), + ); + + assert_eq!(events(&out), vec!["TitleUpdate 1"]); + assert_eq!(t.window(1).unwrap().title, "renamed"); + } + #[test] fn a_cursor_query_answer_is_passed_on_and_remembered() { let mut t = table(vec![]); diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index bdfedbb5..3f0e3882 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -21,8 +21,12 @@ //! [`struct@DATA_DIR`]: after each event and each message the window manager handles, //! [`notify_subscribers`] sends every subscriber a [`Notification`] of it, with the state. +use crate::core::ApplicationIdentifier; use crate::core::SocketMessage; use crate::core::SubscribeOptions; +use crate::core::config_generation::IdWithIdentifier; +use crate::core::config_generation::MatchingRule; +use crate::core::config_generation::MatchingStrategy; use crate::state::State; use crate::window::AspectRatio; use crate::window::PredefinedAspectRatio; @@ -30,6 +34,7 @@ use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; use lazy_static::lazy_static; use parking_lot::Mutex; +use regex::Regex; use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; @@ -95,6 +100,32 @@ lazy_static! { static ref FLOATING_WINDOW_TOGGLE_ASPECT_RATIO: Arc> = Arc::new(Mutex::new( AspectRatio::Predefined(PredefinedAspectRatio::Widescreen) )); + /// The compiled regular expression of each rule whose matching strategy is `Regex`, by the + /// rule's id + static ref REGEX_IDENTIFIERS: Arc>> = + Arc::new(Mutex::new(HashMap::new())); + /// Windows that are tiled even when an ignore rule covers them (`ManageRule`) + static ref MANAGE_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(vec![])); + /// Windows that are never tiled, unless a manage rule says otherwise. Most of what would belong + /// here (the panel, krunner, popups) is not a normal window and is filtered before rules run. + pub static ref IGNORE_IDENTIFIERS: Arc>> = Arc::new(Mutex::new( + ["plasmashell", "org.kde.plasmashell", "krunner", "org.kde.krunner"] + .into_iter() + .map(|class| MatchingRule::Simple(IdWithIdentifier { + kind: ApplicationIdentifier::Class, + id: String::from(class), + matching_strategy: Option::from(MatchingStrategy::Equals), + })) + .collect() + )); + /// The float rules `SessionFloatRule` added, which `ClearSessionFloatRules` takes out of + /// [`struct@FLOATING_APPLICATIONS`] again + static ref SESSION_FLOATING_APPLICATIONS: Arc>> = + Arc::new(Mutex::new(Vec::new())); + /// Windows that are managed as floating windows from the moment they open + static ref FLOATING_APPLICATIONS: Arc>> = Arc::new(Mutex::new(vec![])); + /// Window classes that are never managed, whatever the rules say + static ref PERMAIGNORE_CLASSES: Arc>> = Arc::new(Mutex::new(vec![])); /// The windows `UnmanageFocusedWindow` took out of the layout: komorebi leaves them alone /// until `ManageFocusedWindow` takes them back, or until they close static ref UNMANAGED_WINDOW_IDS: Arc>> = Arc::new(Mutex::new(vec![])); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 1984fd7b..2485ed96 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -9,6 +9,11 @@ //! - **State**: the window manager's [`State`], as JSON. //! - **MonitorInformation**: the id, the name and the bounds of each monitor, as JSON. //! - **Query**: one value as text, the answer to a [`StateQuery`]. +//! - **GlobalState**: the ignore and the manage rules and the data directory ([`GlobalState`]), as +//! JSON. +//! - **SessionFloatRules**: the float rules **SessionFloatRule** added, as JSON. +//! - **DebugWindow**: what [`Window::should_manage`] read of a window and which rules matched it +//! ([`RuleDebug`]), as JSON, or nothing for a window that is not there. //! //! The others answer nothing: //! @@ -64,8 +69,13 @@ //! - **UnmanagedWindowOperationBehaviour** sets whether a message is carried out while the window //! that has the focus is not tiled ([`WindowManager::handle_unmanaged_window_behaviour`]). With //! `NoOp`, every message is refused then, this one included. +//! - **IgnoreRule** adds a rule that keeps the windows of an application out of the layout, and +//! takes the ones it names exactly out of the workspaces in front; **ManageRule** adds a rule +//! that has them tiled whatever the ignore rules say. **SessionFloatRule** floats the window +//! that has the focus and adds a rule that floats the windows that open with its executable, +//! title and class, and **ClearSessionFloatRules** removes those rules. //! - **TogglePause** pauses the window manager, or resumes it: while it is paused, it handles no -//! event, and of the messages only **TogglePause**, **State** and **Stop** +//! event, and of the messages only **TogglePause**, **State**, **GlobalState** and **Stop** //! ([`read_commands_uds`]). //! - **ResizeWindowEdge** and **ResizeWindowAxis** resize the focused container by the //! [`WindowManager::resize_delta`] that **ResizeDelta** sets ([`WindowManager::resize_window`]), @@ -81,11 +91,16 @@ //! ([`notify_subscribers`]). use crate::DATA_DIR; +use crate::FLOATING_APPLICATIONS; +use crate::IGNORE_IDENTIFIERS; +use crate::MANAGE_IDENTIFIERS; use crate::Notification; use crate::NotificationEvent; +use crate::SESSION_FLOATING_APPLICATIONS; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; use crate::backend::backend; +use crate::core::ApplicationIdentifier; use crate::core::Axis; use crate::core::Layout; use crate::core::LayoutOptions; @@ -94,9 +109,14 @@ use crate::core::Rect; use crate::core::ScrollingLayoutOptions; use crate::core::SocketMessage; use crate::core::StateQuery; +use crate::core::config_generation::IdWithIdentifier; +use crate::core::config_generation::MatchingRule; +use crate::core::config_generation::MatchingStrategy; use crate::monitor::MonitorInformation; use crate::notify_subscribers; +use crate::state::GlobalState; use crate::state::State; +use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; use color_eyre::eyre; @@ -185,8 +205,10 @@ impl WindowManager { /// - The monitor or the workspace of `WorkspacePadding` or `ContainerPadding` is not there, or /// the focused workspace has no padding of its own for `AdjustWorkspacePadding` or /// `AdjustContainerPadding` to change. - /// - `Minimize`, `Close`, `ManageFocusedWindow` or `UnmanageFocusedWindow` when the compositor - /// reports no focused window, or the backend refuses to minimize or close it. + /// - `Minimize`, `Close`, `ManageFocusedWindow`, `UnmanageFocusedWindow` or `SessionFloatRule` + /// when the compositor reports no focused window, or the backend refuses to minimize, close or + /// float it. + /// - `IgnoreRule` cannot take a window out of a workspace, or tile the workspace again. /// - The file of `QuickSave` or `Save` cannot be written, or the file of `QuickLoad` or /// `Load` cannot be read or is not a list of resize adjustments. /// - The window manager fails to retile, for one of the reasons @@ -407,6 +429,18 @@ impl WindowManager { tracing::info!("replying to state done"); } + SocketMessage::GlobalState => { + let state = match serde_json::to_string_pretty(&GlobalState::default()) { + Ok(state) => state, + Err(error) => error.to_string(), + }; + + tracing::info!("replying to global state"); + + reply.write_all(state.as_bytes())?; + + tracing::info!("replying to global state done"); + } SocketMessage::MonitorInformation => { let mut monitors = vec![]; for monitor in self.monitors() { @@ -461,6 +495,148 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::SessionFloatRule => { + let foreground_window = Window::from( + backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?, + ); + let (exe, title, class) = ( + foreground_window.exe(), + foreground_window.title(), + foreground_window.class(), + ); + + if let (Some(exe), Some(title), Some(class)) = (exe, title, class) { + let rule = MatchingRule::Composite(vec![ + IdWithIdentifier { + kind: ApplicationIdentifier::Exe, + id: exe, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + IdWithIdentifier { + kind: ApplicationIdentifier::Title, + id: title, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + IdWithIdentifier { + kind: ApplicationIdentifier::Class, + id: class, + matching_strategy: Option::from(MatchingStrategy::Equals), + }, + ]); + + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + floating_applications.push(rule.clone()); + let mut session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); + session_floating_applications.push(rule.clone()); + + self.toggle_float(true)?; + } + } + SocketMessage::SessionFloatRules => { + let session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); + let rules = serde_json::to_string_pretty(&*session_floating_applications) + .unwrap_or_else(|error| error.to_string()); + + reply.write_all(rules.as_bytes())?; + } + SocketMessage::ClearSessionFloatRules => { + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + let mut session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); + floating_applications.retain(|r| !session_floating_applications.contains(r)); + session_floating_applications.clear() + } + SocketMessage::IgnoreRule(identifier, ref id) => { + let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + + let mut should_push = true; + for i in &*ignore_identifiers { + if let MatchingRule::Simple(i) = i + && i.id.eq(id) + { + should_push = false; + } + } + + if should_push { + ignore_identifiers.push(MatchingRule::Simple(IdWithIdentifier { + kind: identifier, + id: id.clone(), + matching_strategy: Option::from(MatchingStrategy::Legacy), + })); + } + + let offset = self.work_area_offset; + + let mut window_ids_to_purge = vec![]; + for (i, monitor) in self.monitors().iter().enumerate() { + for container in monitor + .focused_workspace() + .ok_or_eyre("there is no workspace")? + .containers() + { + for window in container.windows() { + match identifier { + ApplicationIdentifier::Path => { + if window.path().unwrap_or_default().to_string_lossy() == *id { + window_ids_to_purge.push((i, window.id)); + } + } + ApplicationIdentifier::Exe => { + if window.exe().unwrap_or_default() == *id { + window_ids_to_purge.push((i, window.id)); + } + } + ApplicationIdentifier::Class => { + if window.class().unwrap_or_default() == *id { + window_ids_to_purge.push((i, window.id)); + } + } + ApplicationIdentifier::Title => { + if window.title().unwrap_or_default() == *id { + window_ids_to_purge.push((i, window.id)); + } + } + } + } + } + } + + for (monitor_idx, id) in window_ids_to_purge { + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + monitor + .focused_workspace_mut() + .ok_or_eyre("there is no focused workspace")? + .remove_window(id)?; + + monitor.update_focused_workspace(offset)?; + } + } + SocketMessage::ManageRule(identifier, ref id) => { + let mut manage_identifiers = MANAGE_IDENTIFIERS.lock(); + + let mut should_push = true; + for m in &*manage_identifiers { + if let MatchingRule::Simple(m) = m + && m.id.eq(id) + { + should_push = false; + } + } + + if should_push { + manage_identifiers.push(MatchingRule::Simple(IdWithIdentifier { + kind: identifier, + id: id.clone(), + matching_strategy: Option::from(MatchingStrategy::Legacy), + })); + } + } SocketMessage::ContainerPadding(monitor_idx, workspace_idx, size) => { self.set_container_padding(monitor_idx, workspace_idx, size)?; } @@ -641,6 +817,16 @@ impl WindowManager { workspace.resize_dimensions = resize; self.update_focused_workspace(false, false)?; } + SocketMessage::DebugWindow(window_id) => { + let window = Window::from(window_id); + if window.is_valid() { + let mut rule_debug = RuleDebug::default(); + let _ = window.should_manage(None, &mut rule_debug); + let schema = serde_json::to_string_pretty(&rule_debug)?; + + reply.write_all(schema.as_bytes())?; + } + } } self.update_known_window_ids(); @@ -664,8 +850,8 @@ impl WindowManager { /// /// A message that arrives while the window manager has been locked for a second is logged and /// dropped. While the window manager is paused, the first message that is not `TogglePause`, -/// `State` or `Stop` is dropped, and the first that is one of them is handled; either way, the -/// lines after it are not read. +/// `State`, `GlobalState` or `Stop` is dropped, and the first that is one of them is handled; +/// either way, the lines after it are not read. /// /// # Errors /// @@ -693,9 +879,10 @@ pub fn read_commands_uds( Some(mut wm) => { if wm.is_paused { return match message { - SocketMessage::TogglePause | SocketMessage::State | SocketMessage::Stop => { - Ok(wm.process_command(message, &mut stream)?) - } + SocketMessage::TogglePause + | SocketMessage::State + | SocketMessage::GlobalState + | SocketMessage::Stop => Ok(wm.process_command(message, &mut stream)?), _ => { tracing::trace!("ignoring while paused"); Ok(()) diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 8b052d74..fc017144 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -1,12 +1,14 @@ //! How the window manager answers what the compositor reports: [`WindowManager::process_event`]. //! //! Nothing changes while the window manager is paused (`TogglePause`). An event about a window -//! komorebi does not manage ([`Window::should_manage`]), or about one the user took out of the -//! layout with `UnmanageFocusedWindow`, changes nothing either. Otherwise: +//! komorebi does not manage ([`Window::should_manage`]: a dialog, or a window an ignore rule +//! covers and no manage rule rescues), or about one the user took out of the layout with +//! `UnmanageFocusedWindow`, changes nothing either. Otherwise: //! //! - **Show**, and **Manage** (`ManageFocusedWindow`): the window gets a container of its own after //! the focused one, and the workspace is tiled again. The first window on an empty workspace is -//! given the focus. +//! given the focus. A window a float rule matches goes into the workspace's floating windows +//! instead, on a Show (a Manage tiles it whatever the rules say). //! - **Destroy**, and **Unmanage** (`UnmanageFocusedWindow`): the window is taken out of whichever //! workspace has it, and if that is the one in front it is tiled again. A window that is //! unmanaged stays open, centered in the work area so that it is not left behind the tiles, and @@ -16,6 +18,8 @@ //! that instead, so that the strip scrolls to the window that has the focus. //! - **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. +//! - **TitleUpdate**: a window komorebi does not have, and that was not minimized, is announced +//! again as a Show, so that a rule that matches on the title it has now decides. //! //! 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. @@ -25,16 +29,23 @@ //! //! [`Window::should_manage`]: crate::window::Window::should_manage +use crate::FLOATING_APPLICATIONS; use crate::Notification; use crate::NotificationEvent; +use crate::REGEX_IDENTIFIERS; use crate::UNMANAGED_WINDOW_IDS; use crate::backend::backend; use crate::core::DefaultLayout; use crate::core::Layout; use crate::notify_subscribers; use crate::state::State; +use crate::window::RuleDebug; +use crate::window::should_act; use crate::window_manager::WindowManager; +use crate::window_manager_event::KWinNotification; +use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; +use crate::window_manager_event_listener; use color_eyre::eyre; use parking_lot::Mutex; use std::sync::Arc; @@ -101,15 +112,17 @@ impl WindowManager { }; let window_id = window.id; - // A destroyed window can no longer be asked whether it should be managed, and a window the - // user unmanaged is let go of whatever it is, so a removal is let through without asking + // A destroyed window can no longer be asked whether it should be managed, and rules must + // not stop us dropping a window we do manage, so this is settled before the rules are let is_removal = matches!( event, WindowManagerEvent::Destroy(_, _) | WindowManagerEvent::Unmanage(_) ); + let mut rule_debug = RuleDebug::default(); let should_manage = is_removal - || (window.should_manage() && !UNMANAGED_WINDOW_IDS.lock().contains(&window_id)); + || (window.should_manage(Some(event), &mut rule_debug)? + && !UNMANAGED_WINDOW_IDS.lock().contains(&window_id)); if !should_manage { tracing::debug!("ignoring event as window should not be managed: {window}"); @@ -182,14 +195,65 @@ impl WindowManager { } if create { + let behaviour = self.window_management_behaviour; let workspace = self.focused_workspace_mut()?; - workspace.new_container_for_window(&window)?; - self.update_focused_workspace(false, false)?; - if self.focused_workspace()?.containers().len() == 1 { - // If after adding this window the workspace only contains 1 window, it - // was previously empty, so give this window the focus - window.focus(self.mouse_follows_focus)?; + let floating_applications = FLOATING_APPLICATIONS.lock(); + let mut should_float = false; + + if !floating_applications.is_empty() { + let regex_identifiers = REGEX_IDENTIFIERS.lock(); + + if let (Some(title), Some(exe_name), Some(class), Some(path)) = + (window.title(), window.exe(), window.class(), window.path()) + { + should_float = should_act( + &title, + &exe_name, + &[&class], + &path.to_string_lossy(), + &floating_applications, + ®ex_identifiers, + ) + .is_some(); + } + } + drop(floating_applications); + + if behaviour.float_override + || behaviour.floating_layer_override + || (should_float && !matches!(event, WindowManagerEvent::Manage(_))) + { + let placement = if behaviour.floating_layer_override { + // Floating layer override placement + behaviour.floating_layer_placement + } else if behaviour.float_override { + // Float override placement + behaviour.float_override_placement + } else { + // Float rule placement + behaviour.float_rule_placement + }; + // Center floating windows according to the proper placement if not + // on a floating workspace + let center_spawned_floats = placement.should_center() && workspace.tile; + workspace.floating_windows_mut().push_back(window); + if center_spawned_floats { + let mut floating_window = window; + floating_window + .center(&workspace.globals.work_area, placement.should_resize())?; + } + + self.update_focused_workspace(false, false)?; + } else { + workspace.new_container_for_window(&window)?; + self.update_focused_workspace(false, false)?; + + if self.focused_workspace()?.containers().len() == 1 { + // If after adding this window the workspace only contains 1 window, it + // was previously empty, so give this window the focus + window.focus(self.mouse_follows_focus)?; + } } } } @@ -256,6 +320,19 @@ impl WindowManager { self.update_focused_workspace(false, false)?; } }, + WindowManagerEvent::TitleUpdate(_, _) => { + // Windows are routinely announced before their title is set. Now that it is, a rule + // that matches on the title can finally decide, so a window that was not picked up + // gets another chance to be. + if !self.known_window_ids.contains_key(&window_id) + && !self.minimized_windows.contains_key(&window_id) + { + window_manager_event_listener::send_notification(WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + window, + )); + } + } } self.update_known_window_ids(); diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 2df52fed..6aaf51aa 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -5,11 +5,18 @@ //! subscribers in every [`Notification`]. [`State::has_been_modified`] decides whether an event or //! a message changed it, for the subscribers that want a notification only then. //! +//! [`GlobalState`] is what the daemon has besides the window manager, the rules and the data +//! directory, which it writes in answer to `GlobalState`. +//! //! [`SocketMessage::State`]: crate::core::SocketMessage::State //! [`Notification`]: crate::Notification +use crate::DATA_DIR; +use crate::IGNORE_IDENTIFIERS; +use crate::MANAGE_IDENTIFIERS; use crate::core::OperationBehaviour; use crate::core::Rect; +use crate::core::config_generation::MatchingRule; use crate::monitor::Monitor; use crate::ring::Ring; use crate::window_manager::WindowManager; @@ -17,6 +24,64 @@ use crate::workspace::Workspace; use serde::Deserialize; use serde::Serialize; use std::collections::VecDeque; +use std::path::PathBuf; + +/// What the daemon has that is not part of the window manager, as it answers +/// [`SocketMessage::GlobalState`](crate::core::SocketMessage::GlobalState): the ignore and the manage +/// rules, and the data directory +/// +/// # Example +/// +/// ```rust +/// use komorebi::state::GlobalState; +/// +/// let state = GlobalState::default(); +/// // plasmashell and krunner are ignored from the start +/// let json = serde_json::to_string(&state.ignore_identifiers)?; +/// assert!(json.contains(r#""id":"org.kde.plasmashell""#), "{json}"); +/// assert!(state.manage_identifiers.is_empty()); +/// assert_eq!(state.data_dir, *komorebi::DATA_DIR); +/// +/// # Ok::<(), Box>(()) +/// ``` +#[allow(clippy::struct_excessive_bools)] +#[derive(Debug, Serialize, Deserialize)] +pub struct GlobalState { + // pub border_enabled: bool, + // pub border_colours: BorderColours, + // pub border_style: BorderStyle, + // pub border_offset: i32, + // pub border_width: i32, + // pub stackbar_mode: StackbarMode, + // pub stackbar_label: StackbarLabel, + // pub stackbar_focused_text_colour: Colour, + // pub stackbar_unfocused_text_colour: Colour, + // pub stackbar_tab_background_colour: Colour, + // pub stackbar_tab_width: i32, + // pub stackbar_height: i32, + // pub remove_titlebars: bool, + // #[serde(alias = "float_identifiers")] + pub ignore_identifiers: Vec, + pub manage_identifiers: Vec, + // pub layered_whitelist: Vec, + // pub tray_and_multi_window_identifiers: Vec, + // pub name_change_on_launch_identifiers: Vec, + // pub monitor_index_preferences: HashMap, + // pub ignored_duplicate_monitor_serial_ids: Vec, + // pub window_hiding_behaviour: HidingBehaviour, + pub data_dir: PathBuf, + // pub custom_ffm: bool, +} + +impl Default for GlobalState { + fn default() -> Self { + Self { + ignore_identifiers: IGNORE_IDENTIFIERS.lock().clone(), + manage_identifiers: MANAGE_IDENTIFIERS.lock().clone(), + data_dir: DATA_DIR.clone(), + } + } +} /// A copy of the window manager's monitors, with their workspaces, containers and windows, and /// of its settings, which serializes to JSON diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index e51cb942..909167f6 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -5,16 +5,32 @@ //! [`Backend`](crate::backend::Backend) when it is needed, and everything done to it (a move, the //! focus, a close) is a command to the backend. Nothing is cached, so a window that changed its //! title, or closed, is seen as it is now. +//! +//! [`Window::should_manage`] decides whether komorebi manages a window: it has to be a normal +//! application window that is alive, and then the ignore and manage rules decide +//! ([`should_act`], [`should_act_individual`]), writing what they found to a [`RuleDebug`]. +use crate::FLOATING_APPLICATIONS; use crate::FLOATING_WINDOW_TOGGLE_ASPECT_RATIO; +use crate::IGNORE_IDENTIFIERS; +use crate::MANAGE_IDENTIFIERS; +use crate::PERMAIGNORE_CLASSES; +use crate::REGEX_IDENTIFIERS; use crate::backend::backend; +use crate::core::ApplicationIdentifier; use crate::core::Rect; +use crate::core::config_generation::IdWithIdentifier; +use crate::core::config_generation::MatchingRule; +use crate::core::config_generation::MatchingStrategy; +use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use regex::Regex; use serde::Deserialize; use serde::Serialize; use serde::Serializer; use serde::ser::SerializeStruct; +use std::collections::HashMap; use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write; @@ -224,24 +240,60 @@ impl Window { }) } - /// Whether the window is one komorebi should tile: a window that is still alive and that the + /// Whether the window is one komorebi should tile: a window that is still alive, that the /// compositor considers a normal application window, as opposed to a dialog, a splash screen, - /// a utility window or a dock ([`WindowInfo::normal`](crate::backend::WindowInfo::normal)). + /// a utility window or a dock ([`WindowInfo::normal`](crate::backend::WindowInfo::normal)), + /// and that no ignore rule covers, or that a manage rule rescues /// - /// A window the compositor has no record of is not managed. Windows that are minimized when - /// komorebi starts are not picked up either + /// What was looked at and which rules matched is written to `debug`, which is how + /// `DebugWindow` answers. A window the compositor has no record of is not managed. Windows + /// that are minimized when komorebi starts are not picked up either /// ([`load_workspace_information`](crate::desktop::load_workspace_information)). - pub fn should_manage(&self) -> bool { + /// + /// # Errors + /// + /// None: every path returns `Ok`. + #[tracing::instrument(skip_all)] + pub fn should_manage( + &self, + event: Option, + debug: &mut RuleDebug, + ) -> eyre::Result { let Some(info) = self.info() else { - return false; + return Ok(false); }; if !info.alive { - return false; + return Ok(false); } // dialogs, splash screens, utility windows, docks and the like are not for tiling - info.normal + if !info.normal { + return Ok(false); + } + + debug.is_window = true; + + // windows are often announced before their title is set; a TitleUpdate re-evaluates them + debug.has_title = !info.title.is_empty(); + + debug.title = Some(info.title.clone()); + debug.exe_name = Some(info.exe.clone()); + debug.class = Some(info.class.clone()); + debug.path = Some(info.path.clone()); + + let eligible = window_is_eligible( + self.id, + &info.title, + &info.exe, + &[&info.class], + &info.path, + event, + debug, + ); + + debug.should_manage = eligible; + Ok(eligible) } } @@ -290,6 +342,435 @@ impl AspectRatio { } } +/// Why [`Window::should_manage`] decided as it did: what it read of the window, and the rule of +/// each kind that matched it +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct RuleDebug { + pub should_manage: bool, + pub is_window: bool, + // pub has_minimum_width: bool, + // pub has_minimum_height: bool, + pub has_title: bool, + // pub is_cloaked: bool, + // pub allow_cloaked: bool, + // pub allow_layered_transparency: bool, + // pub window_style: Option, + // pub extended_window_style: Option, + pub title: Option, + pub exe_name: Option, + pub class: Option, + pub path: Option, + pub matches_permaignore_class: Option, + pub matches_ignore_identifier: Option, + pub matches_managed_override: Option, + // pub matches_layered_whitelist: Option, + pub matches_floating_applications: Option, + // pub matches_wsl2_gui: Option, + // pub matches_no_titlebar: Option, +} + +/// Whether the rules let a window be managed: not when its class is one of +/// [`struct@PERMAIGNORE_CLASSES`], and not when an ignore rule matches it and no manage rule +/// does. Every rule that matches is written to `debug`, the float rules too, which do not decide +/// whether the window is managed. +#[allow(clippy::too_many_arguments)] +fn window_is_eligible( + _window_id: u32, + title: &str, + exe_name: &str, + classes: &[&str], + path: &str, + // style: &WindowStyle, + // ex_style: &ExtendedWindowStyle, + _event: Option, + debug: &mut RuleDebug, +) -> bool { + { + let permaignore_classes = PERMAIGNORE_CLASSES.lock(); + for class in classes { + if permaignore_classes.contains(&class.to_string()) { + debug.matches_permaignore_class = Some(class.to_string()); + return false; + } + } + } + + let regex_identifiers = REGEX_IDENTIFIERS.lock(); + + let ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + let should_ignore = if let Some(rule) = should_act( + title, + exe_name, + classes, + path, + &ignore_identifiers, + ®ex_identifiers, + ) { + debug.matches_ignore_identifier = Some(rule); + true + } else { + false + }; + + let manage_identifiers = MANAGE_IDENTIFIERS.lock(); + let managed_override = if let Some(rule) = should_act( + title, + exe_name, + classes, + path, + &manage_identifiers, + ®ex_identifiers, + ) { + debug.matches_managed_override = Some(rule); + true + } else { + false + }; + + let floating_identifiers = FLOATING_APPLICATIONS.lock(); + if let Some(rule) = should_act( + title, + exe_name, + classes, + path, + &floating_identifiers, + ®ex_identifiers, + ) { + debug.matches_floating_applications = Some(rule); + } + + if should_ignore && !managed_override { + return false; + } + + true +} + +/// Returns the last of `identifiers` that matches a window with this title, executable, classes +/// and path, if one does: a simple rule matches when its one condition does +/// ([`should_act_individual`]), and a composite rule when all of its conditions do +#[allow(clippy::cognitive_complexity, clippy::too_many_lines)] +pub fn should_act( + title: &str, + exe_name: &str, + classes: &[&str], + path: &str, + identifiers: &[MatchingRule], + regex_identifiers: &HashMap, +) -> Option { + let mut matching_rule = None; + for rule in identifiers { + match rule { + MatchingRule::Simple(identifier) => { + if should_act_individual( + title, + exe_name, + classes, + path, + identifier, + regex_identifiers, + ) { + matching_rule = Some(rule.clone()); + }; + } + MatchingRule::Composite(identifiers) => { + let mut composite_results = vec![]; + for identifier in identifiers { + composite_results.push(should_act_individual( + title, + exe_name, + classes, + path, + identifier, + regex_identifiers, + )); + } + + if composite_results.iter().all(|&x| x) { + matching_rule = Some(rule.clone()); + } + } + } + } + + matching_rule +} + +/// Returns true if and only if the condition `identifier` holds for a window with this title, +/// executable, classes and path +/// +/// The condition compares the title, the executable, any of the classes or the path with its id, +/// by its matching strategy. Without one, or with `Legacy`, a title or a class matches when it +/// starts or ends with the id, and an executable or a path when it is the id. A `Regex` id is +/// looked up in `regex_identifiers`, and an id with no compiled regex there matches nothing. A +/// `.exe` in the id is ignored. +pub fn should_act_individual( + title: &str, + exe_name: &str, + classes: &[&str], + path: &str, + identifier: &IdWithIdentifier, + regex_identifiers: &HashMap, +) -> bool { + let mut should_act = false; + + let mut identifier = identifier.clone(); + identifier.id = identifier.id.replace(".exe", ""); + + match identifier.matching_strategy { + None | Some(MatchingStrategy::Legacy) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.starts_with(&identifier.id) || title.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.starts_with(&identifier.id) || class.ends_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.eq(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::Equals) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.eq(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.eq(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotEqual) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.eq(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.eq(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::StartsWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.starts_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.starts_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotStartWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.starts_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.starts_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::EndsWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.ends_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.ends_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotEndWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.ends_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.ends_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::Contains) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.contains(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.contains(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotContain) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.contains(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.contains(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::Regex) => match identifier.kind { + ApplicationIdentifier::Title => { + if let Some(re) = regex_identifiers.get(&identifier.id) + && re.is_match(title) + { + should_act = true; + } + } + ApplicationIdentifier::Class => { + if let Some(re) = regex_identifiers.get(&identifier.id) { + for class in classes { + if re.is_match(class) { + should_act = true; + } + } + } + } + ApplicationIdentifier::Exe => { + if let Some(re) = regex_identifiers.get(&identifier.id) + && re.is_match(exe_name) + { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if let Some(re) = regex_identifiers.get(&identifier.id) + && re.is_match(path) + { + should_act = true; + } + } + }, + } + + should_act +} + #[cfg(test)] mod tests { use super::*; @@ -397,10 +878,12 @@ mod tests { fake.close_window_now(207); with_backend(fake, || { - assert!(Window::from(205).should_manage()); - assert!(!Window::from(206).should_manage()); - assert!(!Window::from(207).should_manage()); - assert!(!Window::from(208).should_manage()); + let should_manage = + |id| Window::from(id).should_manage(None, &mut RuleDebug::default()); + assert!(should_manage(205).unwrap()); + assert!(!should_manage(206).unwrap()); + assert!(!should_manage(207).unwrap()); + assert!(!should_manage(208).unwrap()); }); } @@ -416,4 +899,94 @@ mod tests { assert_eq!(json["details"]["path"], "/usr/bin/foot"); Ok(()) } + + fn condition( + kind: ApplicationIdentifier, + id: &str, + matching_strategy: Option, + ) -> IdWithIdentifier { + IdWithIdentifier { + kind, + id: id.to_string(), + matching_strategy, + } + } + + /// Whether `condition` holds for a Kate window editing notes.txt + fn holds_for_kate(condition: &IdWithIdentifier, regexes: &HashMap) -> bool { + should_act_individual( + "notes.txt — Kate", + "kate", + &["org.kde.kate"], + "/usr/bin/kate", + condition, + regexes, + ) + } + + /// Whether the condition holds for the Kate window, with no compiled regex + fn holds(kind: ApplicationIdentifier, id: &str, strategy: Option) -> bool { + holds_for_kate(&condition(kind, id, strategy), &HashMap::new()) + } + + #[test] + fn without_a_strategy_a_title_or_a_class_matches_at_either_end_and_an_executable_whole() { + use ApplicationIdentifier::*; + + assert!(holds(Title, "Kate", None)); + assert!(holds(Title, "notes", None)); + assert!(!holds(Title, "txt", None)); + assert!(holds(Class, "kate", None)); + assert!(holds(Exe, "kate.exe", None)); + assert!(!holds(Exe, "kat", None)); + assert!(holds(Path, "/usr/bin/kate", None)); + } + + #[test] + fn a_strategy_says_how_the_id_is_compared_and_a_regex_needs_its_compiled_form() { + use ApplicationIdentifier::*; + use MatchingStrategy::*; + + assert!(!holds(Class, "kate", Some(Equals))); + assert!(holds(Class, "org.kde.kate", Some(Equals))); + assert!(holds(Title, "txt", Some(Contains))); + assert!(holds(Exe, "foot", Some(DoesNotEqual))); + assert!(holds(Path, "/usr/", Some(StartsWith))); + + let regex = condition(Title, "^notes\\.", Some(Regex)); + assert!(!holds_for_kate(®ex, &HashMap::new())); + let compiled = HashMap::from([( + String::from("^notes\\."), + regex::Regex::new("^notes\\.").unwrap(), + )]); + assert!(holds_for_kate(®ex, &compiled)); + } + + #[test] + fn a_composite_rule_needs_every_condition_and_the_last_rule_that_matches_is_the_one() { + use ApplicationIdentifier::*; + let kate = condition(Class, "org.kde.kate", Some(MatchingStrategy::Equals)); + let notes = condition(Title, "notes", None); + let other = condition(Title, "other", None); + let rules = [ + MatchingRule::Composite(vec![kate.clone(), other]), + MatchingRule::Simple(kate.clone()), + MatchingRule::Composite(vec![kate, notes]), + ]; + + let matched = should_act( + "notes.txt — Kate", + "kate", + &["org.kde.kate"], + "/usr/bin/kate", + &rules, + &HashMap::new(), + ); + + assert_eq!(matched, Some(rules[2].clone())); + assert_eq!( + should_act("x", "x", &["x"], "x", &rules[..1], &HashMap::new()), + None + ); + } } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 7275aee6..9ab5f355 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -62,7 +62,7 @@ pub struct WindowManager { /// [`WindowManager::new`] was given another path pub command_listener: UnixListener, /// Whether `TogglePause` has paused the window manager: while it is paused, it handles no - /// event, and of the messages only `TogglePause`, `State` and `Stop` + /// event, and of the messages only `TogglePause`, `State`, `GlobalState` and `Stop` pub is_paused: bool, /// How many pixels `ResizeWindowEdge` and `ResizeWindowAxis` resize by pub resize_delta: i32, diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index d815bd80..314462a5 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -36,6 +36,8 @@ pub enum KWinNotification { WindowMinimized, /// `window.minimizedChanged` to false WindowRestored, + /// `window.captionChanged` + CaptionChanged, } /// Events komorebi raises itself, for example from a command @@ -56,6 +58,8 @@ pub enum WindowManagerEvent { Destroy(SystemNotification, Window), Minimize(SystemNotification, Window), Restore(SystemNotification, Window), + /// The window's title changed + TitleUpdate(SystemNotification, Window), /// The user asked komorebi to manage the window (`ManageFocusedWindow`) Manage(Window), /// The user asked komorebi to stop managing the window (`UnmanageFocusedWindow`) @@ -71,6 +75,7 @@ impl WindowManagerEvent { | WindowManagerEvent::Destroy(_, window) | WindowManagerEvent::Minimize(_, window) | WindowManagerEvent::Restore(_, window) + | WindowManagerEvent::TitleUpdate(_, window) | WindowManagerEvent::Manage(window) | WindowManagerEvent::Unmanage(window) => *window, }) @@ -91,7 +96,8 @@ impl WindowManagerEvent { | WindowManagerEvent::Show(n, _) | WindowManagerEvent::Destroy(n, _) | WindowManagerEvent::Minimize(n, _) - | WindowManagerEvent::Restore(n, _) => match n { + | WindowManagerEvent::Restore(n, _) + | WindowManagerEvent::TitleUpdate(n, _) => match n { SystemNotification::KWin(k) => k.to_string(), SystemNotification::Manual(m) => m.to_string(), }, diff --git a/komorebi/tests/rule_commands.rs b/komorebi/tests/rule_commands.rs new file mode 100644 index 00000000..ae730253 --- /dev/null +++ b/komorebi/tests/rule_commands.rs @@ -0,0 +1,238 @@ +//! The messages that add and show rules, and the title update that lets a rule decide once a +//! window has its title, against an in-memory desktop: the messages go in through +//! [`WindowManager::process_command`], and what comes out is which windows are tiled, which float +//! and what the daemon answers. +//! +//! The rule tables are process-wide, so each test names applications no other test of this file +//! names, and takes out the ignore rules it adds. +//! +//! Window ids are in the 29_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::ApplicationIdentifier; +use komorebi::core::SocketMessage; +use komorebi::core::config_generation::MatchingRule; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use komorebi::window_manager_event_listener; +use std::sync::Arc; +use std::time::Duration; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +fn title_changed(id: u32) -> WindowManagerEvent { + WindowManagerEvent::TitleUpdate( + SystemNotification::KWin(KWinNotification::CaptionChanged), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor and no windows +fn desktop() -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmr-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +/// Opens a window of the application `exe`, whose class is `class`, titled `title` +fn open(fake: &Arc, wm: &mut WindowManager, id: u32, app: (&str, &str, &str)) { + let (exe, class, title) = app; + fake.open_window(id, exe, class, title); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +/// What the daemon answers `message` with +fn ask(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) -> String { + let mut reply = Vec::new(); + with_backend(fake.clone(), || wm.process_command(message, &mut reply)).unwrap(); + String::from_utf8(reply).unwrap() +} + +/// The windows of the focused workspace's containers, in order +fn tiled(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().unwrap().id) + .collect() +} + +/// The floating windows of the focused workspace +fn floating(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .floating_windows() + .iter() + .map(|window| window.id) + .collect() +} + +fn forget_ignore_rule(id: &str) { + komorebi::IGNORE_IDENTIFIERS + .lock() + .retain(|rule| !matches!(rule, MatchingRule::Simple(rule) if rule.id == id)); +} + +const TERMINAL: (&str, &str, &str) = ("foot", "foot", "a terminal"); + +#[test] +fn an_ignore_rule_takes_the_windows_it_names_out_of_the_layout_and_keeps_new_ones_out() { + let (fake, mut wm) = desktop(); + let game = ("game-29", "org.example.game", "a game"); + open(&fake, &mut wm, 29_001, game); + open(&fake, &mut wm, 29_002, TERMINAL); + assert_eq!(tiled(&wm), [29_001, 29_002]); + + send( + &fake, + &mut wm, + SocketMessage::IgnoreRule(ApplicationIdentifier::Exe, String::from("game-29")), + ); + assert_eq!(tiled(&wm), [29_002]); + + open(&fake, &mut wm, 29_003, game); + forget_ignore_rule("game-29"); + assert_eq!(tiled(&wm), [29_002]); +} + +#[test] +fn a_manage_rule_tiles_a_window_an_ignore_rule_covers() { + let (fake, mut wm) = desktop(); + // plasmashell is ignored from the start + let shell = ("plasmashell", "org.kde.plasmashell", "Desktop @ DP-1"); + open(&fake, &mut wm, 29_011, shell); + assert!(tiled(&wm).is_empty()); + + send( + &fake, + &mut wm, + SocketMessage::ManageRule( + ApplicationIdentifier::Class, + String::from("org.kde.plasmashell"), + ), + ); + open(&fake, &mut wm, 29_012, shell); + + assert_eq!(tiled(&wm), [29_012]); +} + +#[test] +fn a_session_float_rule_floats_the_focused_window_and_the_ones_like_it_until_it_is_cleared() { + let (fake, mut wm) = desktop(); + let calculator = ("kcalc", "org.kde.kcalc", "KCalc"); + open(&fake, &mut wm, 29_021, calculator); + open(&fake, &mut wm, 29_022, TERMINAL); + // the user gives the calculator the focus + fake.set_foreground(Some(29_021)); + with_backend(fake.clone(), || wm.process_event(activated(29_021))).unwrap(); + + send(&fake, &mut wm, SocketMessage::SessionFloatRule); + assert_eq!((tiled(&wm), floating(&wm)), (vec![29_022], vec![29_021])); + let rules = ask(&fake, &mut wm, SocketMessage::SessionFloatRules); + assert!(rules.contains("\"org.kde.kcalc\""), "{rules}"); + + open(&fake, &mut wm, 29_023, calculator); + assert_eq!(floating(&wm), [29_021, 29_023], "the next one floats too"); + + send(&fake, &mut wm, SocketMessage::ClearSessionFloatRules); + assert_eq!(ask(&fake, &mut wm, SocketMessage::SessionFloatRules), "[]"); + open(&fake, &mut wm, 29_024, calculator); + assert_eq!(tiled(&wm), [29_022, 29_024]); +} + +#[test] +fn a_window_whose_title_no_longer_matches_an_ignore_rule_is_tiled_when_the_title_changes() { + let (fake, mut wm) = desktop(); + send( + &fake, + &mut wm, + SocketMessage::IgnoreRule(ApplicationIdentifier::Title, String::from("pending-29")), + ); + open( + &fake, + &mut wm, + 29_031, + ("browser-29", "org.example.browser", "pending-29"), + ); + assert!(tiled(&wm).is_empty()); + + fake.set_title(29_031, "a page"); + with_backend(fake.clone(), || wm.process_event(title_changed(29_031))).unwrap(); + forget_ignore_rule("pending-29"); + + // the title update announces the window again, on the channel the events thread reads + let events = window_manager_event_listener::event_rx(); + let shown = loop { + let event = events + .recv_timeout(Duration::from_secs(5)) + .expect("the window is announced again"); + if event.window_id() == Some(29_031) { + break event; + } + }; + assert!(matches!(shown, WindowManagerEvent::Show(..)), "{shown:?}"); + with_backend(fake.clone(), || wm.process_event(shown)).unwrap(); + assert_eq!(tiled(&wm), [29_031]); +} + +#[test] +fn global_state_has_the_rules_and_debug_window_says_why_a_window_is_not_managed() { + let (fake, mut wm) = desktop(); + open(&fake, &mut wm, 29_041, TERMINAL); + fake.open_window(29_042, "krunner", "org.kde.krunner", "KRunner"); + + let state: serde_json::Value = + serde_json::from_str(&ask(&fake, &mut wm, SocketMessage::GlobalState)).unwrap(); + let ignored = state["ignore_identifiers"].to_string(); + assert!(ignored.contains("\"org.kde.krunner\""), "{ignored}"); + assert!(state["manage_identifiers"].is_array()); + assert!(state["data_dir"].is_string()); + + let debug: serde_json::Value = + serde_json::from_str(&ask(&fake, &mut wm, SocketMessage::DebugWindow(29_042))).unwrap(); + assert_eq!(debug["should_manage"], false); + assert_eq!(debug["class"], "org.kde.krunner"); + assert_eq!(debug["matches_ignore_identifier"]["id"], "org.kde.krunner"); + + let debug: serde_json::Value = + serde_json::from_str(&ask(&fake, &mut wm, SocketMessage::DebugWindow(29_041))).unwrap(); + assert_eq!(debug["should_manage"], true); + + // a window there is not is not answered + assert_eq!(ask(&fake, &mut wm, SocketMessage::DebugWindow(29_049)), ""); +} diff --git a/komorebi/tests/rules.rs b/komorebi/tests/rules.rs new file mode 100644 index 00000000..b95c4388 --- /dev/null +++ b/komorebi/tests/rules.rs @@ -0,0 +1,74 @@ +//! The rules that decide whether a window is managed, against an in-memory desktop. +//! +//! Window ids are in the 10_000s; the rule tables are process-wide, so a test removes the rule it +//! adds. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::ApplicationIdentifier; +use komorebi::core::config_generation::IdWithIdentifier; +use komorebi::core::config_generation::MatchingRule; +use komorebi::core::config_generation::MatchingStrategy; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel) +fn desktop() -> (Arc, WindowManager) { + desktop_on(FakeBackend::with_one_monitor()) +} + +fn desktop_on(fake: FakeBackend) -> (Arc, WindowManager) { + let fake = Arc::new(fake); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmb-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +#[test] +fn an_ignore_rule_keeps_a_window_unmanaged() { + let (fake, mut wm) = desktop(); + fake.open_window( + 10_051, + "secret-app", + "org.example.secret", + "hidden from komorebi", + ); + + let rule = MatchingRule::Simple(IdWithIdentifier { + kind: ApplicationIdentifier::Class, + id: "org.example.secret".to_string(), + matching_strategy: Some(MatchingStrategy::Equals), + }); + komorebi::IGNORE_IDENTIFIERS.lock().push(rule.clone()); + + let result = with_backend(fake.clone(), || wm.process_event(added(10_051))); + + komorebi::IGNORE_IDENTIFIERS.lock().retain(|r| r != &rule); + result.unwrap(); + + assert!(!wm.focused_workspace().unwrap().contains_window(10_051)); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 3b9b64ea..b4b733b9 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -31,6 +31,11 @@ //! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of //! the tiles of the focused workspace and load them back. //! +//! `ignore-rule` and `manage-rule` add a rule that keeps an application out of the layout or +//! always in it, `session-float-rule` floats the focused window and every window like it until the +//! daemon stops, `session-float-rules` shows those rules and `clear-session-float-rules` removes +//! them, and `global-state` shows the rules the daemon has. +//! //! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens //! on a socket in the daemon's data directory, to which the daemon sends a notification after each //! event and each message it handles. @@ -46,6 +51,7 @@ use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; use fs_tail::TailedFile; +use komorebi_client::ApplicationIdentifier; use komorebi_client::Axis; use komorebi_client::CycleDirection; use komorebi_client::DefaultLayout; @@ -174,6 +180,31 @@ gen_padding_adjustment_subcommand_args! { AdjustWorkspacePadding, } +macro_rules! gen_application_target_subcommand_args { + // SubCommand Pattern + ( $( $name:ident ),+ $(,)? ) => { + $( + #[derive(clap::Parser)] + pub struct $name { + #[clap(value_enum)] + identifier: ApplicationIdentifier, + /// Identifier as a string + id: String, + } + )+ + }; +} + +gen_application_target_subcommand_args! { + IgnoreRule, + ManageRule, + // IdentifyTrayApplication, + // IdentifyLayeredApplication, + // IdentifyObjectNameChangeApplication, + // IdentifyBorderOverflowApplication, + // RemoveTitleBar, +} + #[derive(Parser)] struct Resize { #[clap(value_enum)] @@ -327,6 +358,8 @@ enum SubCommand { DataDirectory, /// Show a JSON representation of the current window manager state State, + /// Show a JSON representation of the current global state + GlobalState, /// Show information about connected monitors #[clap(alias = "monitor-info")] MonitorInformation, @@ -471,6 +504,19 @@ enum SubCommand { /// Set the operation behavior when the focused window is not managed #[clap(arg_required_else_help = true)] UnmanagedWindowOperationBehaviour(UnmanagedWindowOperationBehaviour), + /// Add a rule to float the foreground window for the rest of this session + SessionFloatRule, + /// Show all session float rules + SessionFloatRules, + /// Clear all session float rules + ClearSessionFloatRules, + /// Add a rule to ignore the specified application + #[clap(arg_required_else_help = true)] + #[clap(alias = "float-rule")] + IgnoreRule(IgnoreRule), + /// Add a rule to always manage the specified application + #[clap(arg_required_else_help = true)] + ManageRule(ManageRule), /// Enable or disable mouse follows focus on all workspaces #[clap(arg_required_else_help = true)] MouseFollowsFocus(MouseFollowsFocus), @@ -671,12 +717,30 @@ fn main() -> eyre::Result<()> { SubCommand::State => { print_query(&SocketMessage::State); } + SubCommand::GlobalState => { + print_query(&SocketMessage::GlobalState); + } SubCommand::Query(args) => { print_query(&SocketMessage::Query(args.state_query)); } SubCommand::MonitorInformation => { print_query(&SocketMessage::MonitorInformation); } + SubCommand::SessionFloatRule => { + send_message(&SocketMessage::SessionFloatRule)?; + } + SubCommand::SessionFloatRules => { + print_query(&SocketMessage::SessionFloatRules); + } + SubCommand::ClearSessionFloatRules => { + send_message(&SocketMessage::ClearSessionFloatRules)?; + } + SubCommand::IgnoreRule(args) => { + send_message(&SocketMessage::IgnoreRule(args.identifier, args.id))?; + } + SubCommand::ManageRule(args) => { + send_message(&SocketMessage::ManageRule(args.identifier, args.id))?; + } SubCommand::ResizeDelta(args) => { send_message(&SocketMessage::ResizeDelta(args.pixels))?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 9d8c8c79..bcd145a6 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -353,6 +353,44 @@ fn the_offset_subcommands_send_the_offset_they_are_given() { ); } +#[test] +fn the_rule_subcommands_send_the_application_they_are_given() { + sends( + &["ignore-rule", "exe", "steam"], + r#"{"type":"IgnoreRule","content":["Exe","steam"]}"#, + ); + sends( + &["float-rule", "class", "org.kde.kcalc"], + r#"{"type":"IgnoreRule","content":["Class","org.kde.kcalc"]}"#, + ); + sends( + &["manage-rule", "title", "Picture-in-Picture"], + r#"{"type":"ManageRule","content":["Title","Picture-in-Picture"]}"#, + ); + sends(&["session-float-rule"], r#"{"type":"SessionFloatRule"}"#); + sends( + &["clear-session-float-rules"], + r#"{"type":"ClearSessionFloatRules"}"#, + ); +} + +#[test] +fn global_state_and_session_float_rules_print_the_answer_of_the_daemon() { + for (args, message) in [ + ("global-state", r#"{"type":"GlobalState"}"#), + ("session-float-rules", r#"{"type":"SessionFloatRules"}"#), + ] { + let runtime = Runtime::new(); + let daemon = runtime.serve("[]"); + + let output = runtime.komorebic(&[args]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!(daemon.join().unwrap(), message); + assert_eq!(stdout(&output), "[]\n"); + } +} + #[test] fn the_subcommands_about_the_focused_window_and_pausing_send_their_message() { sends(&["minimize"], r#"{"type":"Minimize"}"#); @@ -429,6 +467,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "adjust-workspace-padding.md", "cancel-preselect.md", "change-layout.md", + "clear-session-float-rules.md", "close.md", "completions.md", "container-padding.md", @@ -440,10 +479,13 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "focus.md", "focused-workspace-container-padding.md", "focused-workspace-padding.md", + "global-state.md", "global-work-area-offset.md", + "ignore-rule.md", "layout-ratios.md", "load-resize.md", "log.md", + "manage-rule.md", "manage.md", "minimize.md", "monitor-information.md", @@ -464,6 +506,8 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "retile.md", "save-resize.md", "scrolling-layout-columns.md", + "session-float-rule.md", + "session-float-rules.md", "start.md", "state.md", "stop.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index e2d6b5f3..b5f06ba5 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -219,6 +219,12 @@ mouse-follows-focus enable mouse-follows-focus disable toggle-mouse-follows-focus toggle-mouse-follows-focus +session-float-rule +session-float-rules +clear-session-float-rules +toggle-float +ignore-rule exe nonexistent +manage-rule exe nonexistent manage close retile @@ -269,8 +275,50 @@ checks.check( kde.wait_for(lambda: kde.managed() == before and healthy() == 0, timeout=10), ) +print("== 3c. a rule that matches a title decides when the window has its title") +kde.komorebic("ignore-rule", "title", "pending-rule") +before_all = kde.managed_all() + + +def ignored(title: str) -> bool: + """True once the daemon has logged that it leaves the window titled `title` alone.""" + return any( + "should not be managed" in line and f"title: {title}," in line + for line in kde.komorebi_log().splitlines() + ) + + +# foot is titled pending-rule when it opens, and gives itself another title after 4 seconds +rename = 'sleep 4; printf "\\033]0;renamed-rule\\007"; sleep 3000' +kde.spawn(f"foot -T pending-rule sh -c {shlex.quote(rename)}") +checks.check( + "a window the ignore rule matches by its title is left alone", + kde.wait_for(lambda: ignored("pending-rule"), timeout=20) and kde.managed_all() == before_all, +) +checks.check( + "once it has a title the rule does not match, it is tiled", + kde.wait_for( + lambda: kde.wid("renamed-rule") != "" and kde.managed_all() == before_all + 1, + timeout=20, + ) + and healthy() == 0, +) +# the daemon's log names a window by the title it had when it was focused, which for this one is +# the first: close it, so that the last check finds every window it looks for in the log +kde.close(kde.wid("renamed-rule")) +checks.check( + "closed, it leaves komorebi", + kde.wait_for(lambda: kde.wid("renamed-rule") == "" and healthy() == 0, timeout=10), +) + print("== 4. what komorebic only prints") -for args in ["state", "monitor-information", "data-directory"]: +for args in [ + "state", + "global-state", + "monitor-information", + "data-directory", + "session-float-rules", +]: checks.check(f"komorebic {args}", kde.run(f"komorebic {args}")[0] == 0) for query in [ "focused-monitor-index", diff --git a/nix/tests/vm/suites/kwin-events/test.py b/nix/tests/vm/suites/kwin-events/test.py index c6e082bc..40c4e3c7 100644 --- a/nix/tests/vm/suites/kwin-events/test.py +++ b/nix/tests/vm/suites/kwin-events/test.py @@ -1,8 +1,10 @@ # 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), and that it takes its script -# out of KWin when it stops. +# raised them (KWin activates a new window before it announces it), that a window giving itself +# another title is reported, and that it takes its script out of KWin when it stops. +import shlex + from komorebi_vm import Checks, Kde, daemon from komorebi_vm.daemon import Event @@ -97,6 +99,23 @@ checks.check( in_order == ["Show", "Minimize", "Restore", "Destroy"], ) +print("== a window gives itself another title") +rename = 'sleep 4; printf "\\033]0;beta-renamed\\007"; sleep 3000' +kde.spawn(f"foot -T beta sh -c {shlex.quote(rename)}") +checks.check( + "KWin's focus on it reached the daemon, by title", + kde.wait_for(lambda: "beta" in daemon.window_ids(daemon_log()), timeout=30), +) +b = daemon.window_ids(daemon_log()).get("beta", -1) +checks.check( + "KWin has it under its new title", + kde.wait_for(lambda: kde.wid("beta-renamed") != "", timeout=20), +) +checks.check( + "the title change is a TitleUpdate", + kde.wait_for(lambda: handled(Event("TitleUpdate", b, "CaptionChanged")), timeout=10), +) + print("== stop") kde.stop_komorebi() checks.check("the daemon exited", not kde.komorebi_running()) From 62e37e44cfd8d469753af10af49e1e9e6f3fcf81 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 17:18:12 -0700 Subject: [PATCH 029/255] feat(kwin): workspaces are KWin's own desktops komorebi's workspaces exist on Windows and macOS because neither has a virtual desktop API: switching hides every window of the workspace being left. KWin has virtual desktops, per output since 6.8, so here workspace i is KWin's desktop i on every monitor, and each monitor shows one. KWin shows, hides and focuses the windows of a desktop; komorebi asks for a switch, puts a window on a desktop, and follows what anything else does. The Backend gets the workspace methods (ensure_workspaces, switch_workspace, set_window_workspace, window_workspace, current_workspaces), and the fake its desktops. The bridge reports the desktops, the desktop each output shows and a window's desktops, and carries out output_desktop and desktop commands, typed and tested with the fixtures like the rest. The table turns a switch or a move komorebi did not make into a WorkspaceChange or a WorkspaceMove, and records its own when it sends them, so that KWin's report of those raises nothing. The window manager follows a switch with no command in reply (adopt_workspace_change), puts windows on their desktops before a desktop is shown (focusing a window first would take the monitor back), and loads the windows open at startup onto the workspace of their desktop. Per-output desktops are a kwinrc setting that is off by default, and kwriteconfig6 was not on the PATH of the user service in a live session, so komorebi edits kwinrc itself (kwin::kwinrc) and puts the user's value back when it stops, also after a crash. focus-workspace, move-to-workspace and send-to-workspace come with this commit, since the tests of switching and moving, and vm-workspace-switch, need them; the named and cycling workspace commands follow. vm-workspace-switch runs the daemon against a real KWin; vm-kwin-contract checks what komorebi relies on from KWin's per-output desktops, on a headless KWin with two outputs and no komorebi. --- README.md | 18 +- docs/cli/focus-workspace.md | 14 + docs/cli/move-to-workspace.md | 14 + docs/cli/send-to-workspace.md | 14 + docs/dev/ARCHITECTURE.md | 110 ++++- docs/dev/DESIGN.md | 36 ++ docs/dev/PLATFORM.md | 81 +++- docs/dev/vm-tests.md | 8 + docs/index.md | 2 + docs/usage/workspaces.md | 51 ++ komorebi/src/backend/fake.rs | 192 +++++++- komorebi/src/backend/mod.rs | 62 +++ komorebi/src/core/mod.rs | 3 + komorebi/src/desktop.rs | 32 +- komorebi/src/kwin/bridge.js | 127 ++++- komorebi/src/kwin/bridge.test.js | 114 ++++- komorebi/src/kwin/fixtures/commands.json | 10 + komorebi/src/kwin/fixtures/events.json | 23 +- komorebi/src/kwin/kwin-api.d.ts | 17 +- komorebi/src/kwin/kwinrc.rs | 425 ++++++++++++++++ komorebi/src/kwin/mod.rs | 229 ++++++++- komorebi/src/kwin/state.rs | 459 +++++++++++++++++- komorebi/src/monitor.rs | 305 ++++++++++++ komorebi/src/process_command.rs | 76 +++ komorebi/src/process_event.rs | 61 +++ komorebi/src/window_manager.rs | 145 +++++- komorebi/src/window_manager_event.rs | 44 +- komorebi/src/workspace.rs | 30 ++ komorebi/tests/workspaces.rs | 361 ++++++++++++++ komorebic/src/main.rs | 40 ++ komorebic/tests/cli.rs | 19 + nix/tests/vm/lib/komorebi_vm/kde.py | 77 +++ nix/tests/vm/lib/tests/test_kde.py | 72 +++ nix/tests/vm/suites/commands/test.py | 6 + nix/tests/vm/suites/kwin-contract/default.nix | 5 + nix/tests/vm/suites/kwin-contract/test.py | 172 +++++++ .../vm/suites/workspace-switch/default.nix | 5 + nix/tests/vm/suites/workspace-switch/test.py | 140 ++++++ 38 files changed, 3522 insertions(+), 77 deletions(-) create mode 100644 docs/cli/focus-workspace.md create mode 100644 docs/cli/move-to-workspace.md create mode 100644 docs/cli/send-to-workspace.md create mode 100644 docs/usage/workspaces.md create mode 100644 komorebi/src/kwin/kwinrc.rs create mode 100644 komorebi/tests/workspaces.rs create mode 100644 nix/tests/vm/suites/kwin-contract/default.nix create mode 100644 nix/tests/vm/suites/kwin-contract/test.py create mode 100644 nix/tests/vm/suites/workspace-switch/default.nix create mode 100644 nix/tests/vm/suites/workspace-switch/test.py diff --git a/README.md b/README.md index 5a6a1b70..a746eaf8 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,8 @@ 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 backend that reaches KWin through a script it runs (`kwin`), + (`backend`), the backend that reaches KWin through a script it runs and edits + the one setting of KWin's it needs in the user's `kwinrc` (`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 @@ -119,6 +120,15 @@ 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. If KWin restarts, the daemon loads the bridge into the new one. +komorebi's workspaces are KWin's own virtual desktops: workspace `i` is desktop +`i`, and each monitor shows a desktop of its own, which the daemon has KWin do by +turning on its per-output virtual desktops (the setting is put back when the +daemon stops). Showing a workspace is a request to KWin, which shows the +windows of that desktop, hides the others, and gives the focus to one of them. +When something else switches a monitor to another desktop (a pager, a shortcut, +an application raising a window of another desktop), or puts a window on +another desktop, the window manager follows. + 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 @@ -126,7 +136,8 @@ area, and every window of a container is moved onto its tile. At startup the window manager loads the monitors and the windows that are open from the backend and tiles them; after that it changes the model when the compositor reports that a window was shown, closed, focused, minimized or restored, and -tiles the workspace in front again. +tiles the workspace in front again. A window open at startup goes to the +workspace whose desktop it is on. Everything else reaches the daemon as a message on its socket: one JSON `SocketMessage` per line, handled one at a time with the window manager @@ -151,6 +162,9 @@ the work area offsets keep parts of a monitor free of tiles. Rules decide which windows are managed at all: `ignore-rule` keeps an application out of the layout, `manage-rule` tiles it whatever the ignore rules say, and `session-float-rule` floats the focused window and the windows like it. +`focus-workspace` shows another workspace, and `move-to-workspace` and +`send-to-workspace` put the focused window on another workspace, with and +without showing it. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/focus-workspace.md b/docs/cli/focus-workspace.md new file mode 100644 index 00000000..b303caf9 --- /dev/null +++ b/docs/cli/focus-workspace.md @@ -0,0 +1,14 @@ +```text +Focus the specified workspace on the focused monitor + +Usage: focus-workspace + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-to-workspace.md b/docs/cli/move-to-workspace.md new file mode 100644 index 00000000..b63835d5 --- /dev/null +++ b/docs/cli/move-to-workspace.md @@ -0,0 +1,14 @@ +```text +Move the focused window to the specified workspace + +Usage: move-to-workspace + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/send-to-workspace.md b/docs/cli/send-to-workspace.md new file mode 100644 index 00000000..7eae8db7 --- /dev/null +++ b/docs/cli/send-to-workspace.md @@ -0,0 +1,14 @@ +```text +Send the focused window to the specified workspace + +Usage: send-to-workspace + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 22c68945..d4c86da3 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -7,10 +7,10 @@ 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, the backend that reaches KWin, -how an event about a window becomes a tile, how a message on the daemon's socket is -answered, how subscribers are notified of both, what the orders a message gives do, and how the -NixOS module runs the daemon. It grows with the code: each part of the daemon that is added has -its place here. +how an event about a window becomes a tile, how workspaces are the compositor's desktops, how +a message on the daemon's socket is answered, how subscribers are notified of both, what the +orders a message gives do, and how the NixOS module runs the daemon. It grows with the code: +each part of the daemon that is added has its place here. ## Vocabulary @@ -19,16 +19,22 @@ its place here. - **Monitor**: a connected output, with its bounds and its work area (its bounds minus the panels). - **Workspace**: the containers a monitor shows, in order, and the layout that tiles - them. A monitor has a ring of workspaces and shows one of them. + them. A monitor has a ring of workspaces and shows one of them. Workspace `i` is the + compositor's desktop `i` on that monitor. +- **Desktop**: one of KWin's virtual desktops. KWin shows the windows of one desktop on each + output and hides the others; with its per-output virtual desktops on, each output shows a + desktop of its own. - **Container**: what a layout places. It gets one tile, and every window in it is put on that tile. - **Layout**: the arrangement (BSP, columns, rows, ...) that turns a work area and a number of containers into one rectangle, a **tile**, for each container. - **Event**: what the compositor reports about a window: it was shown, destroyed, given - the focus, minimized or restored ([`WindowManagerEvent`]). Two events come from komorebi - itself: a command asks it to manage the focused window, or to stop managing it. + the focus, minimized or restored, or put on another workspace's desktop; and that a monitor + shows another workspace ([`WindowManagerEvent`]). Two events come from komorebi itself: a + command asks it to manage the focused window, or to stop managing it. - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order - (focus a window, move it, change the layout, resize it, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). + (focus a window, move it, change the layout, resize it, show a workspace, retile, stop) or a + question (the state, the monitors, one [`StateQuery`]). - **Rule**: a condition on a window's title, executable, class or path ([`MatchingRule`]), in one of the process-wide lists that decide whether a window is managed (the ignore and the manage rules) and whether it floats when it opens (the float rules). @@ -81,7 +87,9 @@ The desktop, as the window manager sees it, is two lists and a pointer: of the window that has it. A command is one of: move and resize a window, focus it, raise it, minimize it or bring it -back, close it, and put the pointer in the middle of a rectangle. +back, close it, put the pointer in the middle of a rectangle, make desktops for the +workspaces, show a workspace on a monitor, and put a window on a workspace. The workspace a +window is on, and the one each monitor shows, are queries. The window manager tiles a tree of four levels, each level a [`Ring`]: a list with one element focused, so that "the focused workspace" or "the focused container" means @@ -111,9 +119,10 @@ tile is clamped to the work area, so it cannot reach onto a neighboring monitor. The [`WindowManager`] keeps the monitors, the windows the user minimized (they are in no workspace until they are restored), and an index from each window it manages to the monitor and workspace that have it. It is loaded from the backend at startup: every -monitor, and every open window that is normal, alive, not minimized and not ignored by a -rule, on the focused 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. +monitor, focused on the workspace the compositor shows on it, and every open window that is +normal, alive, not minimized and not ignored by a rule, on the workspace whose desktop it is +on, 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 @@ -179,6 +188,41 @@ and returns once the snapshot has arrived, so that the window manager reads a fu 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. +## Workspaces + +komorebi's workspaces are the compositor's virtual desktops: workspace `i` is desktop `i` on +every monitor, and each monitor shows one at a time. The compositor shows the windows of the +desktop in front, hides the others, and keeps which window of each desktop had the focus; the +window manager hides no window to leave a workspace. The reasons are in +[DESIGN.md](DESIGN.md#why-are-komorebis-workspaces-kwins-virtual-desktops). + +Showing a workspace ([`Monitor::load_focused_workspace`]) is three steps. Every window of every +workspace of the monitor is put on the desktop of its workspace, unless it is already there. +The compositor is asked to show the workspace on the monitor ([`Backend::switch_workspace`]), +which leaves the other monitors as they are. The workspace's focused window is given the focus. +The order matters: a window that is focused while it is on another desktop takes the monitor +back to that desktop. + +Desktops are global in KWin: every monitor has as many as the monitor with the most +workspaces, and each has one name. At startup, and when a workspace is asked for that has no +desktop, the backend creates the missing ones over KWin's `org.kde.KWin.VirtualDesktopManager` +interface, named "Workspace 1", "Workspace 2" and so on ([`WindowManager::sync_workspace_desktops`]). +Without KWin's per-output virtual desktops every output would show the same desktop, so +[`connect`] turns them on in the user's `kwinrc`, and [`Kwinrc`] keeps the user's value and +puts it back when komorebi stops, also after a crash. + +Something else can switch a monitor to another desktop: a pager, a KWin shortcut, an +application that raises a window of another desktop, which KWin answers by showing that +desktop. KWin has one signal for it, which does not say which output, so the bridge sends the +desktop of every output after it, and once a second. The table compares it with what it had, +and a monitor that shows another desktop is a `WorkspaceChange` event: the window manager +focuses that workspace and tiles it ([`WindowManager::adopt_workspace_change`]), and asks the +compositor for nothing, since KWin has already shown the windows and chosen which to focus. A +window put on another desktop by something else (the window menu's "Move to Desktop") is a +`WorkspaceMove`: the window manager moves the window to that workspace. komorebi's own switch +and move come back from KWin as the same reports; the table records them when the command is +sent ([`Table::switch_commands`], [`Table::window_workspace_commands`]), so they raise nothing. + ## The command socket The daemon takes messages on a Unix socket, `komorebi.sock` in [`DATA_DIR`] @@ -370,6 +414,13 @@ would be smaller than a tenth of the work area, or than it is already. The adjus until a `Retile`, which drops them; `RetileWithResizeDimensions` tiles with them, and `Save`, `Load`, `QuickSave` and `QuickLoad` write them to a file as JSON and read them back. +`FocusWorkspaceNumber` shows another workspace of the focused monitor +([`WindowManager::focus_workspace`]). `MoveContainerToWorkspaceNumber` takes the focused +container (or the focused window, when it is a floating one) to the back of another workspace +of the monitor and shows that workspace, and `SendContainerToWorkspaceNumber` does the same +and leaves the workspace in front showing ([`WindowManager::move_container_to_workspace`]). A +workspace that does not exist yet is created, with the ones before it, and gets a desktop. + `PreselectDirection` reserves the index on one side of the focused container for the next window ([`WindowManager::preselect_container_in_direction`]). The workspace inserts an empty container there ([`Container::preselect`]), which [`Workspace::update`] keeps and the layout @@ -429,7 +480,8 @@ module's unit. operations on it (tile the workspace in front, tile every monitor, take a minimized window out, move the focus, move the focused container, change the layout, resize or promote the focused container, float a window, lock a container, set the padding of a - workspace, manage and unmanage a window). + workspace, manage and unmanage a window, show a workspace, move a container to another + workspace, follow a workspace switch made by something else). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -439,7 +491,9 @@ module's unit. 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 + call; [`kwin::state`](../../komorebi/src/kwin/state.rs), the table; + [`kwin::kwinrc`](../../komorebi/src/kwin/kwinrc.rs), the editor of the user's `kwinrc`, which + keeps the values it changes and puts them back; and [`bridge.js`](../../komorebi/src/kwin/bridge.js), the bridge. - [`process_command`](../../komorebi/src/process_command.rs): the thread that listens on the socket, and what the window manager does with each message. @@ -480,6 +534,11 @@ the fake. The window manager is its only caller, through [`backend`]. The contra - A command about a window that does not exist, or is no longer alive, is an error. It never panics. The KWin backend knows a closed window for a minute after it closed, and sends its commands to the bridge, which reports that it could not carry them out. +- Workspace `i` is the compositor's desktop `i`, and each monitor shows one + (`switch_workspace`, `set_window_workspace`, `window_workspace`, `current_workspaces`). A + backend asked for a workspace that has no desktop makes the desktops up to it + (`ensure_workspaces`). The compositor shows and hides the windows of the desktops, and a + backend reports a switch or a move it did not make as an event. - `shutdown`, `is_window`, `window_rect` and `monitor_from_point` have defaults, written in terms of the queries. An implementor should not need to override them, except `shutdown` when it created something in the compositor that has to be given up. @@ -518,6 +577,12 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A resize leaves no tile smaller than a tenth of the work area, or than it was | framework path: [`WindowManager::resize_window`] calculates the tiles for the adjustment, and cuts the adjustment down until they all fit | `a_resize_leaves_every_tile_about_a_tenth_of_the_work_area_wide_at_least` | the paddings are taken off afterwards, so a tile can end up a little smaller | | The offset of a workspace wins over its monitor's, which wins over the window manager's | framework path: [`Monitor::update_workspace_globals`] gives the workspace the monitor's offset or else the window manager's, and [`Workspace::update`] takes its own before that | `the_workspaces_offset_wins_over_the_monitors_which_wins_over_the_global_one` | none | | A workspace whose tiling is off moves no window | framework path: [`Workspace::update`] returns before the layout when [`Workspace::tile`] is false | `with_tiling_off_no_window_is_moved_until_it_is_back_on` | none | +| komorebi hides no window to leave a workspace | framework path: showing a workspace is one request to the compositor ([`Backend::switch_workspace`]), which shows and hides the windows of its desktops | `switching_workspace_asks_the_compositor_to_show_the_other_desktop`, `vm-workspace-switch` ("KWin shows the desktop, komorebi hides nothing") | none | +| Showing a workspace on one monitor leaves the other monitors as they are | KWin's per-output virtual desktops, which [`connect`] turns on | `showing_a_workspace_switches_that_output_only`, `vm-kwin-contract` ("the other keeps its own") | a `kwinrc` komorebi cannot write: every monitor switches | +| A window is on its new workspace's desktop before the desktop is shown or the window focused | framework path: [`Monitor::load_focused_workspace`] puts every window on its desktop first | `moving_a_window_to_another_workspace_puts_it_on_the_desktop_before_showing_it` | none | +| A workspace switch or a window move made by something else is followed, and answered with no command | framework path: the table reports what it did not send as a `WorkspaceChange` or a `WorkspaceMove`, and [`WindowManager::adopt_workspace_change`] asks the compositor for nothing | `a_workspace_switch_by_someone_else_is_followed_not_undone`, `a_window_moved_to_another_desktop_by_someone_else_changes_workspace`, `another_party_switching_a_monitor_is_a_workspace_change`, `vm-workspace-switch` ("nothing is flip-flopping") | none | +| komorebi's own switch or move, reported back by KWin, changes nothing | framework path: the table records a switch and a move when it makes their commands | `the_compositor_reporting_komorebis_own_switch_changes_nothing`, `komorebis_own_move_coming_back_as_an_event_moves_nothing`, `komorebi_switching_a_monitor_comes_back_as_a_change_to_what_it_already_knows` | none | +| The user's `kwinrc` gets back the value komorebi changed, also after a crash | framework path: [`Kwinrc`] records the first value of a key in a backup file, and the backend's `shutdown` puts it back | `what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed`, `a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run`, `vm-workspace-switch` ("back as they were") | `SIGKILL`: the next run puts it back when it stops | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | 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 | @@ -648,6 +713,14 @@ A window is shown, and ends up on a tile: strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, and every `komorebic` command, against a real KWin with two outputs. +- [`komorebi/tests/workspaces.rs`](../../komorebi/tests/workspaces.rs): workspaces as the + fake's desktops; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the + `kwinrc` editor and its tests. +- [`nix/tests/vm/suites/workspace-switch`](../../nix/tests/vm/suites/workspace-switch/test.py): + workspaces as a real KWin's desktops, switched by `komorebic` and by KWin; + [`nix/tests/vm/suites/kwin-contract`](../../nix/tests/vm/suites/kwin-contract/test.py), the + behavior of KWin's per-output virtual desktops komorebi relies on, with two outputs and no + komorebi. - [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; [`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix), its scenarios, evaluated in real NixOS systems; and [`nix/tests/vm/suites/module`](../../nix/tests/vm/suites/module/test.py), @@ -727,6 +800,15 @@ A window is shown, and ends up on a tile: [`Table`]: ../../komorebi/src/kwin/state.rs [`Table::handle`]: ../../komorebi/src/kwin/state.rs [`Table::compositor_lost`]: ../../komorebi/src/kwin/state.rs +[`Table::switch_commands`]: ../../komorebi/src/kwin/state.rs +[`Table::window_workspace_commands`]: ../../komorebi/src/kwin/state.rs +[`Kwinrc`]: ../../komorebi/src/kwin/kwinrc.rs +[`Backend::switch_workspace`]: ../../komorebi/src/backend/mod.rs +[`Monitor::load_focused_workspace`]: ../../komorebi/src/monitor.rs +[`WindowManager::sync_workspace_desktops`]: ../../komorebi/src/window_manager.rs +[`WindowManager::adopt_workspace_change`]: ../../komorebi/src/window_manager.rs +[`WindowManager::focus_workspace`]: ../../komorebi/src/window_manager.rs +[`WindowManager::move_container_to_workspace`]: ../../komorebi/src/window_manager.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 diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index cc625c47..34f6536d 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -223,3 +223,39 @@ to put a window for a second, and sets the position again when the window's fram another one in that time ([PLATFORM.md](PLATFORM.md#how-clients-answer-a-frame)). Three tries at most keep it from chasing a window that cannot go where it was asked, such as a fullscreen one. + +## Why are komorebi's workspaces KWin's virtual desktops? + +Because KWin has virtual desktops, per output since KWin 6.8, and Windows and macOS have no API +for them. komorebi's own workspaces exist there for that reason: switching workspace hides +every window of the workspace being left and restores the windows of the one being entered. On +KDE that is what KWin does with its desktops, and native behavior is preferred over a +workaround (see [What is komorebi for KDE the port of?](#what-is-komorebi-for-kde-the-port-of)): +workspace `i` is desktop `i` on every monitor, and each monitor shows one at a time. + +The spikes measured what KWin does with per-output desktops on a headless KWin with two +outputs: showing a desktop on one output left the other output's alone; KWin gave the focus to +a window of the desktop it switched to, by itself; and activating a window on another desktop +of its output (an application raising itself) made KWin switch that output to the window's +desktop and focus the window, by itself. So komorebi asks for a switch and follows the ones it +did not ask for, with no command in reply. A first attempt in which komorebi hid the windows +itself switched between two workspaces about 280 times a second after an application raised a +window of another workspace: KWin delivered focus events it had generated before it carried +out komorebi's commands, and komorebi took each for a new request. With KWin's desktops there +is nothing to debounce, since komorebi answers a switch with nothing. + +The costs: desktops are global, so every monitor has as many as the monitor with the most +workspaces, with one name each, and they show in the pager and the overview. A window komorebi +does not manage (a dialog, say) belongs to the desktop it opened on and goes out of view with +it. The desktops komorebi created stay when it stops: by then they are the user's desktops. + +## Why does komorebi edit `kwinrc` itself? + +Because per-output virtual desktops are off by default, they are a setting in the user's +`kwinrc`, and the program that would set it cannot be counted on. KDE's `kwriteconfig6` was not +on the PATH of komorebi's user service in the first live run in a Plasma session, and +per-output desktops stayed off; `kreadconfig6` is not always installed either. The file is +plain ini, which komorebi changes line by line, and asks KWin to reload its configuration. +It is the user's setting, so the value komorebi found is kept in a backup file and put back +when komorebi stops; a backup a crash left behind keeps the value from before the first run, +and the next run puts it back. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 2948f47a..efa56ec5 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -19,6 +19,8 @@ was measured with KWin 6.8.1, Plasma 6.8.1 and Qt 6.12.0 from nixpkgs `d3b13ad` - **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. +- **Desktop**: one of KWin's virtual desktops. Each output shows one; komorebi's workspace `i` + is desktop `i`. - **Headless KWin**: `kwin_wayland --virtual`, a KWin with virtual outputs and no display, which the VM tests run ([vm-tests.md](vm-tests.md)). @@ -26,10 +28,35 @@ was measured with KWin 6.8.1, Plasma 6.8.1 and Qt 6.12.0 from nixpkgs `d3b13ad` ### 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. +KWin 6.8 is the oldest KWin komorebi supports. komorebi's workspaces are KWin's virtual +desktops, one shown on each output, which needs the per-output virtual desktops KWin 6.8 +introduced (`workspace.currentDesktopForScreen`, `workspace.setCurrentDesktopForScreen`, and +the setting `[Windows] PerOutputVirtualDesktops` in `kwinrc`). 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. + +### Per-output virtual desktops + +What komorebi relies on KWin to do with them, on KWin 6.8.1 at time of writing (2026-10-27), +measured in the spikes and checked by the VM test `vm-kwin-contract` on a headless KWin with two +outputs: + +- With `PerOutputVirtualDesktops=true` in the `[Windows]` group of `kwinrc`, a script that + shows a desktop on one output (`workspace.setCurrentDesktopForScreen`) leaves the other + output's desktop as it was. komorebi turns the setting on when it starts, has KWin reload its + configuration (`org.kde.KWin.reconfigure`), and puts the user's value back when it stops. +- KWin raises `workspace.currentDesktopChanged` when an output shows another desktop. The signal + does not say which output, so the bridge reads the desktop of every output after it. +- KWin gives the focus to a window of the desktop it switched an output to, by itself. +- Activating a window that is on another desktop of its output switches that output to the + window's desktop and gives the window the focus. +- A window that a script moves so that its middle is on another output keeps its desktops; + `window.output` follows the middle. KWin puts a window on the new output's desktop only during + an interactive move. +- Putting a window on another desktop from outside the script raises the window's + `desktopsChanged`. +- Desktops are global: every output has the same desktops, with the same names, and each output + shows one of them. The ids of the desktops are UUIDs; the bridge names them by id. ### Wayland @@ -74,9 +101,16 @@ the windows and outputs it finds, and from then on every window that opens, clos 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. +Before it loads the script, it turns on KWin's per-output virtual desktops in the user's +`kwinrc` (`[Windows] PerOutputVirtualDesktops=true`), unless they are on, and asks KWin to +reload its configuration. If a workspace has no desktop, it creates the missing desktops over +`org.kde.KWin.VirtualDesktopManager`, named "Workspace 1", "Workspace 2" and so on. A desktop +that is already there keeps its name. + Every command of the window manager (move and resize, focus, raise, minimize, bring back or -close a window) is queued for the bridge, which gets the queue as the answer to its held call -and carries the commands out in KWin, in order. The script API cannot move the pointer, so +close a window, show a workspace on an output, put a window on a workspace) is queued for the +bridge, which gets the queue as the answer to its held call and carries the commands out in +KWin, in order. The script API cannot move the pointer, so when the pointer follows the focus komorebi invokes KWin's own "Move Mouse to Focus" shortcut, which puts the pointer in the middle of the window KWin has focused. @@ -94,11 +128,15 @@ an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a runnin #### What komorebi leaves behind -When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it asks KWin -to unload the script, closes an empty connection to each subscriber, and removes the socket. -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, and the socket file in -the runtime directory, until the next start replaces both or the session ends. +When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it puts back +the value `PerOutputVirtualDesktops` had in `kwinrc` (or removes the key, when the user had +none) and asks KWin to reload its configuration, asks KWin to unload the script, closes an +empty connection to each subscriber, and removes the socket. The desktops it created stay: +they are the user's desktops from then on. 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, the socket file in the runtime directory, and per-output desktops +on, until the next start replaces the script and the socket, and its stop puts the setting +back (the backup in the runtime directory keeps the user's value), or the session ends. ### A headless KWin @@ -143,11 +181,19 @@ What komorebi calls: | `org.kde.KWin` | `/Scripting/Script` | `org.kde.kwin.Script` | `run()` | after `loadScript` | | `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `AddMatch(s)`, for the signal `NameOwnerChanged` | at start, to see KWin leave the bus and come back | | `org.kde.kglobalaccel` | `/component/kwin` | `org.kde.kglobalaccel.Component` | `invokeShortcut(s)`, with `MoveMouseToFocus` | when the pointer follows the focus | +| `org.kde.KWin` | `/KWin` | `org.kde.KWin` | `reconfigure()` | after komorebi changed `kwinrc`, at start and at exit | +| `org.kde.KWin` | `/VirtualDesktopManager` | `org.kde.KWin.VirtualDesktopManager` | the property `desktops`, `createDesktop(us)`, `setDesktopName(ss)` | when a workspace has no desktop, and at start | + +The property `desktops` is introspected as `a(iss)`, a position, an id and a name for each +desktop, and the value on the wire is `a(uss)`: komorebi reads it as that. It is read uncached, +since a read right after `createDesktop` has to see the new desktop. ## Files and directories | Path | What | Lifetime | |---|---|---| +| `$XDG_CONFIG_HOME/kwinrc` (`~/.config/kwinrc`) | KWin's configuration: komorebi sets `PerOutputVirtualDesktops=true` in `[Windows]`, changing that line or adding it and nothing else, and writes the file beside it first and renames it over it | put back as it was when the daemon stops | +| `$XDG_RUNTIME_DIR/komorebi/kwinrc-backup.json` | the value each key of `kwinrc` had before komorebi first changed it | removed when the values are put back; one a crash left behind is used by the next run | | `$XDG_RUNTIME_DIR/komorebi/bridge.js` | the script KWin loads, with its configuration (the D-Bus names and the hold time of `Poll`) on its first line | written at every start; the directory is removed at logout | | `$XDG_RUNTIME_DIR/komorebi/komorebi.sock` | the command socket | bound once the daemon is connected to KWin, after a file left there is removed; removed when the daemon stops | | `$XDG_RUNTIME_DIR/komorebi/NAME` | the socket of a subscriber, which the subscriber binds and names in its subscription | removed by the daemon, with the subscriber, when it cannot connect to it | @@ -170,6 +216,19 @@ either. An address with no bus behind it is the first error under [No KWin](#no- The runtime directory of the user, normally `/run/user/`: komorebi writes the bridge to the `komorebi` directory in it, and binds its command socket there. +### `XDG_CONFIG_HOME` + +Where the user's `kwinrc` is: `$XDG_CONFIG_HOME/kwinrc`, or `~/.config/kwinrc` when it is not +set. Without either, komorebi leaves per-output virtual desktops as they are and logs that it +found no configuration directory. + +### `XDG_CONFIG_DIRS` + +Where KConfig looks for the system's `kwinrc` when the user's has no value: komorebi reads +`PerOutputVirtualDesktops` the same way, from the user's file and then from the first of these +directories that has it (`/etc/xdg` when the variable is not set), and changes nothing when the +setting is on already. + ### `XDG_DATA_HOME` The logs are written to `$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index b45e243b..28e1a8a3 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -134,6 +134,14 @@ the run. in order, `daemon.window_ids(log)` maps a window's title to the daemon's id for it, and `daemon.requests(log)` returns the frame the daemon last asked KWin for, for each window. +- `desk(wid)` is the number of the desktop a window is on and `shown()` the one + KWin shows, both counted from 1 as `kdotool` counts, `desktops()` how many + desktops KWin has, and `kwinrc(group, key)` a value of the user's `kwinrc`. +- `kwin_script(name, source, keep=)` runs a KWin script and returns the lines it + reported: the script calls `report(...)`, which `print`s a line marked with + `name` to KWin's log, and ends with `report("done")`. A script that is kept + goes on reporting what its signal handlers see, and `kwin_reports(name)` + reads every line it has reported so far from the journal. - `monitor_bridge(path)` records the bridge's traffic on the session bus with `dbus-monitor`, and `latency.rounds` times each batch of commands in it, from the daemon's answer to the last frame KWin reports for the windows it moved. diff --git a/docs/index.md b/docs/index.md index 77f40c0d..8ee8224b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -43,6 +43,8 @@ window and pause the daemon, and and keep parts of a monitor free of them. [Rules](usage/rules.md) explains how to keep an application out of the layout, always tile it, or float its windows. +[Workspaces](usage/workspaces.md) explains how each monitor shows one of its workspaces, which +are KWin's virtual desktops, and how to show another or move a window to one. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/workspaces.md b/docs/usage/workspaces.md new file mode 100644 index 00000000..c3713c31 --- /dev/null +++ b/docs/usage/workspaces.md @@ -0,0 +1,51 @@ +# Workspaces + +Each monitor has workspaces, and shows one of them at a time. A workspace has its own windows +and its own layout. komorebi's workspaces are KWin's virtual desktops: workspace 0 is the first +desktop, workspace 1 the second, and so on, which is why the pager, the overview and KWin's +shortcuts show and switch them too. + +komorebi turns on KWin's per-output virtual desktops when it starts, so that each monitor shows +a desktop of its own: switching the workspace of one monitor leaves the others as they are. It +puts the setting back as it was when it stops. + +## Showing another workspace + +[`komorebic focus-workspace`](../cli/focus-workspace.md) shows a workspace of the focused +monitor, by its number, counted from 0. KWin shows the windows of that workspace and hides the +others, and the window of that workspace that had the focus has it again. + +```sh +komorebic focus-workspace 1 +komorebic focus-workspace 0 +``` + +A workspace that does not exist yet is created, with the ones before it, and KWin gets a +desktop for each, named "Workspace 2" and so on. A desktop that is there already keeps its +name. The desktops komorebi creates stay when it stops. + +## Moving a window to another workspace + +[`komorebic move-to-workspace`](../cli/move-to-workspace.md) takes the focused window to another +workspace, puts it after the windows there, and shows that workspace. +[`komorebic send-to-workspace`](../cli/send-to-workspace.md) does the same and stays on the +workspace in front, which is tiled again without the window. + +```sh +komorebic move-to-workspace 1 +komorebic send-to-workspace 2 +``` + +## Switching with KWin + +Anything that switches KWin's desktop switches komorebi's workspace: the pager, KWin's own +shortcuts, the overview, or an application that raises a window of another desktop (KWin then +shows that desktop and focuses the window). komorebi follows, tiles the workspace that came +into view, and asks KWin for nothing in reply. A window moved to another desktop with the +window menu's "Move to Desktop" moves to that workspace. + +## The windows that were open before + +When komorebi starts, each window that is open goes to the workspace whose desktop it is on, +and each monitor starts on the workspace KWin shows there. A window that is on every desktop +goes to the workspace in front. diff --git a/komorebi/src/backend/fake.rs b/komorebi/src/backend/fake.rs index 8e2ee60f..2c2c52c6 100644 --- a/komorebi/src/backend/fake.rs +++ b/komorebi/src/backend/fake.rs @@ -52,6 +52,12 @@ pub enum Command { Close(u32), /// [`Backend::center_cursor_in`]. CenterCursor(Rect), + /// [`Backend::ensure_workspaces`]: how many workspaces were asked for. + EnsureWorkspaces(usize), + /// [`Backend::switch_workspace`]: the monitor, and the workspace it was asked to show. + SwitchWorkspace(u32, usize), + /// [`Backend::set_window_workspace`]: the window, and the workspace it was put on. + SetWindowWorkspace(u32, usize), } #[derive(Default)] @@ -65,6 +71,42 @@ struct State { foreground: Option, cursor: Option<(i32, i32)>, commands: Vec, + /// how many virtual desktops there are + desktops: usize, + /// the desktop every window is on + window_ws: HashMap, + /// the desktop each monitor (by id) shows + shown: HashMap, +} + +impl State { + /// The monitor a window is on: the one that holds the middle of it, else the first + fn monitor_of(&self, id: u32) -> Option { + let w = self.windows.get(&id)?; + let (x, y) = ( + w.rect.left + w.rect.right / 2, + w.rect.top + w.rect.bottom / 2, + ); + self.monitors + .iter() + .find(|m| { + x >= m.size.left + && x < m.size.left + m.size.right + && y >= m.size.top + && y < m.size.top + m.size.bottom + }) + .or_else(|| self.monitors.first()) + .map(|m| m.id) + } + + /// What a window opened now would be on, as in KWin: the desktop its monitor is showing + fn desktop_for_new_window(&self) -> usize { + self.monitors + .first() + .and_then(|m| self.shown.get(&m.id)) + .copied() + .unwrap_or(0) + } } /// An in-memory [`Backend`]. @@ -127,9 +169,12 @@ impl FakeBackend { } /// Opens a window of an application. It starts at 800x600 at (100, 100), a normal window with - /// no focus. + /// no focus, on the workspace the first monitor shows. pub fn open_window(&self, id: u32, exe: &str, class: &str, title: &str) { - self.state.lock().windows.insert( + let mut state = self.state.lock(); + let desktop = state.desktop_for_new_window(); + state.window_ws.insert(id, desktop); + state.windows.insert( id, WindowInfo { id, @@ -207,6 +252,45 @@ impl FakeBackend { self.state.lock().windows.get(&id).map(|w| w.rect) } + /// Returns true if and only if the window can be seen: it is alive, not minimized, and on the + /// workspace its monitor shows. This is what the compositor does with desktops. + pub fn on_screen(&self, id: u32) -> bool { + let state = self.state.lock(); + let Some(window) = state.windows.get(&id) else { + return false; + }; + let monitor = state.monitor_of(id); + let shown = monitor + .and_then(|m| state.shown.get(&m)) + .copied() + .unwrap_or(0); + window.alive && !window.minimized && state.window_ws.get(&id).copied().unwrap_or(0) == shown + } + + /// Returns the workspace a window is on, if it was ever opened. + pub fn workspace_of(&self, id: u32) -> Option { + self.state.lock().window_ws.get(&id).copied() + } + + /// Returns the workspace a monitor shows. + pub fn shown_workspace(&self, monitor_id: u32) -> usize { + self.state + .lock() + .shown + .get(&monitor_id) + .copied() + .unwrap_or(0) + } + + /// Shows workspace `idx` on a monitor the way something other than komorebi does (a pager, a + /// shortcut, a click on a window of another desktop): no command is recorded, and the + /// compositor's event about it is the test's to send. + pub fn show_workspace_by_user(&self, monitor_id: u32, idx: usize) { + let mut state = self.state.lock(); + state.desktops = state.desktops.max(idx + 1); + state.shown.insert(monitor_id, idx); + } + /// Returns every command received so far, oldest first. pub fn commands(&self) -> Vec { self.state.lock().commands.clone() @@ -344,6 +428,47 @@ impl Backend for FakeBackend { state.cursor = Some((rect.left + rect.right / 2, rect.top + rect.bottom / 2)); Ok(()) } + + fn ensure_workspaces(&self, names: &[String]) -> eyre::Result<()> { + let mut state = self.state.lock(); + state.commands.push(Command::EnsureWorkspaces(names.len())); + state.desktops = state.desktops.max(names.len()); + Ok(()) + } + + fn switch_workspace(&self, monitor_id: u32, idx: usize) -> eyre::Result<()> { + let mut state = self.state.lock(); + state + .commands + .push(Command::SwitchWorkspace(monitor_id, idx)); + state.desktops = state.desktops.max(idx + 1); + state.shown.insert(monitor_id, idx); + Ok(()) + } + + fn set_window_workspace(&self, id: u32, idx: usize) -> eyre::Result<()> { + self.record(id, Command::SetWindowWorkspace(id, idx), |state| { + state.desktops = state.desktops.max(idx + 1); + state.window_ws.insert(id, idx); + }) + } + + fn window_workspace(&self, id: u32) -> Option { + let mut state = self.state.lock(); + if state.permissive && !state.windows.contains_key(&id) { + state.windows.insert(id, permissive_window(id)); + } + state.window_ws.get(&id).copied() + } + + fn current_workspaces(&self) -> Vec<(u32, usize)> { + let state = self.state.lock(); + state + .monitors + .iter() + .map(|m| (m.id, state.shown.get(&m.id).copied().unwrap_or(0))) + .collect() + } } #[cfg(test)] @@ -500,6 +625,69 @@ mod tests { assert_eq!(ids, [1, 3]); } + #[test] + fn a_window_opens_on_the_workspace_the_first_monitor_shows() { + let fake = FakeBackend::with_one_monitor(); + fake.show_workspace_by_user(1, 2); + + fake.open_window(1, "foot", "foot", "window 1"); + + assert_eq!(fake.workspace_of(1), Some(2)); + assert_eq!(fake.window_workspace(1), Some(2)); + assert!(fake.on_screen(1)); + } + + #[test] + fn a_monitor_shows_the_windows_of_its_workspace_and_no_others() -> eyre::Result<()> { + let fake = fake_with(&[1, 2]); + fake.set_window_workspace(2, 1)?; + + assert!(fake.on_screen(1) && !fake.on_screen(2)); + + fake.switch_workspace(1, 1)?; + + assert!(!fake.on_screen(1) && fake.on_screen(2)); + assert_eq!(fake.shown_workspace(1), 1); + assert_eq!(fake.current_workspaces(), [(1, 1)]); + assert_eq!( + fake.commands(), + [ + Command::SetWindowWorkspace(2, 1), + Command::SwitchWorkspace(1, 1) + ] + ); + Ok(()) + } + + #[test] + fn a_workspace_shown_by_the_user_is_not_a_command() { + let fake = fake_with(&[1]); + + fake.show_workspace_by_user(1, 3); + + assert_eq!(fake.current_workspaces(), [(1, 3)]); + assert!(fake.commands().is_empty()); + } + + #[test] + fn a_minimized_window_or_one_that_closed_is_not_on_screen() -> eyre::Result<()> { + let fake = fake_with(&[1, 2]); + + fake.minimize(1)?; + fake.close_window_now(2); + + assert!(!fake.on_screen(1) && !fake.on_screen(2)); + Ok(()) + } + + #[test] + fn putting_a_window_nobody_opened_on_a_workspace_is_an_error() { + let fake = fake_with(&[1]); + + assert!(fake.set_window_workspace(9, 1).is_err()); + assert_eq!(fake.workspace_of(9), None); + } + #[test] fn the_cursor_can_be_centered_in_a_rectangle() -> eyre::Result<()> { let fake = FakeBackend::new(); diff --git a/komorebi/src/backend/mod.rs b/komorebi/src/backend/mod.rs index 15de867f..7050c43b 100644 --- a/komorebi/src/backend/mod.rs +++ b/komorebi/src/backend/mod.rs @@ -20,6 +20,14 @@ //! short time, with [`WindowInfo::alive`] false, so that the event that mentions it can still be //! logged. Commands return once the compositor has accepted them, not once the client has acted on //! them, and an implementation may batch them. +//! +//! # Workspaces +//! +//! komorebi's workspaces are the compositor's virtual desktops, per monitor: the window manager +//! asks for workspace `i` to be shown on a monitor ([`Backend::switch_workspace`]) and for a window +//! to be put on workspace `i` ([`Backend::set_window_workspace`]), and the compositor does the +//! showing, the hiding and the focusing. When something else changes what a monitor shows, the +//! backend raises an event and the window manager follows it. #![deny(missing_docs)] @@ -89,6 +97,12 @@ pub struct MonitorInfo { /// - A command about a window that does not exist, or is no longer alive, returns an error. It does /// not panic. /// - A backend is `Send + Sync`: the window manager calls it from several threads. +/// - Workspace `i` is the compositor's virtual desktop `i` on every monitor, and each monitor shows +/// one of them at a time ([`Backend::switch_workspace`]). The compositor shows the windows of the +/// workspace in front and hides the others; the window manager never hides a window to leave a +/// workspace. +/// - A backend asked to show a workspace, or to put a window on one, that has no desktop yet makes +/// the desktops up to it first. /// /// The compiler enforces the first and last parts of the contract that it can see. A backend that /// leaves out a method does not compile: @@ -123,6 +137,11 @@ pub struct MonitorInfo { /// # fn unminimize(&self, _: u32) -> eyre::Result<()> { Ok(()) } /// # fn close(&self, _: u32) -> eyre::Result<()> { Ok(()) } /// # fn center_cursor_in(&self, _: &Rect) -> eyre::Result<()> { Ok(()) } +/// # fn ensure_workspaces(&self, _: &[String]) -> eyre::Result<()> { Ok(()) } +/// # fn switch_workspace(&self, _: u32, _: usize) -> eyre::Result<()> { Ok(()) } +/// # fn set_window_workspace(&self, _: u32, _: usize) -> eyre::Result<()> { Ok(()) } +/// # fn window_workspace(&self, _: u32) -> Option { None } +/// # fn current_workspaces(&self) -> Vec<(u32, usize)> { vec![] } /// # } /// ``` pub trait Backend: Send + Sync + 'static { @@ -201,6 +220,49 @@ pub trait Backend: Send + Sync + 'static { /// When the compositor refuses to move the pointer. fn center_cursor_in(&self, rect: &Rect) -> eyre::Result<()>; + // ---- workspaces ---------------------------------------------------------------------------- + // + // komorebi's workspaces are the compositor's own virtual desktops: workspace `i` is desktop `i` + // on every monitor, and each monitor shows one at a time. Showing, hiding and focusing the + // windows of a workspace is then the compositor's business; komorebi tiles what is in front and + // follows the compositor when something else (a pager, a shortcut, an app raising a window) + // changes what a monitor shows. + + /// Makes sure there are at least as many desktops as `names`, creating the missing ones with + /// those names. + /// + /// A desktop that is already there keeps its name, unless nobody chose it (the compositor's + /// own "Desktop 2"), in which case it may take the name it is given. + /// + /// # Errors + /// + /// When the compositor refuses to create or rename a desktop. + fn ensure_workspaces(&self, names: &[String]) -> eyre::Result<()>; + + /// Shows workspace `idx` on the monitor `monitor_id`, leaving the other monitors as they are. + /// + /// The compositor shows the windows on that workspace, hides the rest, and gives the focus to a + /// window of that workspace by itself. + /// + /// # Errors + /// + /// When there is no desktop for `idx` and one cannot be made. + fn switch_workspace(&self, monitor_id: u32, idx: usize) -> eyre::Result<()>; + + /// Puts a window on workspace `idx`. It is visible at once to [`Backend::window_workspace`]. + /// + /// # Errors + /// + /// When the window does not exist, or there is no desktop for `idx` and one cannot be made. + fn set_window_workspace(&self, id: u32, idx: usize) -> eyre::Result<()>; + + /// Returns the workspace a window is on, or `None` for a window the compositor does not know or + /// that is on every workspace. + fn window_workspace(&self, id: u32) -> Option; + + /// Returns the workspace each monitor shows, as `(monitor id, workspace index)`. + fn current_workspaces(&self) -> Vec<(u32, usize)>; + // ---- provided ------------------------------------------------------------------------------ /// Called once as komorebi exits, after the window manager has put back what it moved, so that diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index dfcddc89..e51b7894 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -348,6 +348,8 @@ pub enum SocketMessage { CycleMoveWindow(CycleDirection), ResizeWindowEdge(OperationDirection, Sizing), ResizeWindowAxis(Axis, Sizing), + MoveContainerToWorkspaceNumber(usize), + SendContainerToWorkspaceNumber(usize), // ForceFocus, Close, Minimize, @@ -382,6 +384,7 @@ pub enum SocketMessage { QuickLoad, Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf), Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + FocusWorkspaceNumber(usize), ContainerPadding(usize, usize, i32), FocusedWorkspaceContainerPadding(i32), WorkspacePadding(usize, usize, i32), diff --git a/komorebi/src/desktop.rs b/komorebi/src/desktop.rs index 20444314..cf579a49 100644 --- a/komorebi/src/desktop.rs +++ b/komorebi/src/desktop.rs @@ -141,13 +141,19 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { Ok(()) } -/// Puts the windows that are already open into containers on the focused workspace of the -/// monitor they are on, so that starting komorebi tiles what is on screen. +/// Puts the windows that are already open into containers on the workspace of the monitor they +/// are on, so that starting komorebi tiles what is on screen. /// -/// A window is on the monitor whose bounds contain its middle. A window that is minimized, that -/// komorebi does not manage ([`Window::should_manage`]: not a normal window, or one the rules -/// ignore), or that is on no monitor is left alone. -/// Nothing is moved: tiling is [`WindowManager::retile_all`]'s job. +/// Each monitor is first focused on the workspace the compositor shows on it +/// ([`Backend::current_workspaces`]). A window is on the monitor whose bounds contain its middle, +/// and on the workspace whose desktop it is on ([`Backend::window_workspace`]), which need not be +/// the one in front; a window on every desktop goes to the one in front. The monitor gets as many +/// workspaces as that takes. A window that is minimized, that komorebi does not manage +/// ([`Window::should_manage`]: not a normal window, or one the rules ignore), or that is on no +/// monitor is left alone. Nothing is moved: tiling is [`WindowManager::retile_all`]'s job. +/// +/// [`Backend::current_workspaces`]: crate::backend::Backend::current_workspaces +/// [`Backend::window_workspace`]: crate::backend::Backend::window_workspace /// /// # Errors /// @@ -181,6 +187,7 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { /// let workspace = wm.focused_workspace()?; /// assert!(workspace.contains_window(1)); /// assert!(!workspace.contains_window(2)); +/// assert_eq!(wm.focused_workspace_idx()?, 0); /// # std::fs::remove_file(socket)?; /// # Ok::<(), color_eyre::eyre::Report>(()) /// ``` @@ -188,6 +195,13 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { pub fn load_workspace_information(wm: &mut WindowManager) -> eyre::Result<()> { let mut valid_window_count = 0; + // each monitor starts out showing the workspace the compositor is showing on it + for (monitor_id, idx) in backend().current_workspaces() { + if let Some(monitor) = wm.monitors_mut().iter_mut().find(|m| m.id == monitor_id) { + monitor.focus_workspace(idx)?; + } + } + for info in backend().windows() { if info.minimized { continue; @@ -212,10 +226,14 @@ pub fn load_workspace_information(wm: &mut WindowManager) -> eyre::Result<()> { continue; }; + // a window is on the workspace whose desktop it is on, not necessarily the one in front let Some(monitor) = wm.monitors_mut().get_mut(monitor_idx) else { continue; }; - let workspace_idx = monitor.focused_workspace_idx(); + let workspace_idx = backend() + .window_workspace(info.id) + .unwrap_or_else(|| monitor.focused_workspace_idx()); + monitor.ensure_workspace_count(workspace_idx + 1); if let Some(workspace) = monitor.workspaces_mut().get_mut(workspace_idx) { let mut container = Container::default(); diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index 3c7121d3..5751add3 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -41,16 +41,25 @@ * }} Screen */ +/** + * A virtual desktop, by KWin's id for it and its name; and the desktop an output shows. + * + * @typedef {{ id: string, name: string }} Desktop + * @typedef {{ output: string, id: string }} CurrentDesktop + */ + /** * 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; `caption` is a window's new title; + * `desktops` says which desktops a window is on now, `desktop_list` which desktops there are, and + * `current_desktops` which desktop each output shows, each sent when it is not what was last sent; * `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 + * type: "snapshot", windows: WindowInfo[], screens: Screen[], desktops: Desktop[], + * current_desktops: CurrentDesktop[], active: string | null, cursor: Point * }} Snapshot * @typedef {WindowInfo & { type: "added" }} Added * @typedef {{ type: "removed", id: string }} Removed @@ -58,25 +67,32 @@ * @typedef {{ type: "minimized", id: string, v: boolean }} Minimized * @typedef {{ type: "geometry", id: string, geo: Rect }} Geometry * @typedef {{ type: "caption", id: string, caption: string }} Caption + * @typedef {{ type: "desktops", id: string, desktops: string[] }} Desktops + * @typedef {{ type: "desktop_list", desktops: Desktop[] }} DesktopList + * @typedef {{ type: "current_desktops", current: CurrentDesktop[] }} CurrentDesktops * @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 | Caption | CursorAnswer | Failed} BridgeEvent + * @typedef {Snapshot | Added | Removed | Activated | Minimized | Geometry | Caption | Desktops + * | DesktopList | CurrentDesktops | CursorAnswer | Failed} BridgeEvent */ /** * What the daemon sends: the answer to `Poll` is a list of batches, each a list of commands. A * window command names the window by its `id`: `geo` sets its frame, `min` minimizes it (`v`) or - * brings it back, and `activate`, `raise` and `close` do what they say. A cursor query is - * numbered by `token` so that its answer can be matched. + * brings it back, `desktop` puts it on the desktop `v` (and on no other), and `activate`, `raise` + * and `close` do what they say. `output_desktop` shows the desktop `v` on one output, leaving the + * others as they are. A cursor query is numbered by `token` so that its answer can be matched. * * @typedef {{ op: "cursor", token: number }} CursorQuery + * @typedef {{ op: "output_desktop", output: string, v: string }} OutputDesktop * @typedef {{ op: "geo", id: string, x: number, y: number, w: number, h: number }} SetFrame * @typedef {{ op: "min", id: string, v: boolean }} SetMinimized * @typedef {{ op: "activate", id: string }} Activate * @typedef {{ op: "raise", id: string }} Raise * @typedef {{ op: "close", id: string }} Close - * @typedef {SetFrame | SetMinimized | Activate | Raise | Close} WindowCommand - * @typedef {CursorQuery | WindowCommand} Command + * @typedef {{ op: "desktop", id: string, v: string }} SetDesktop + * @typedef {SetFrame | SetMinimized | Activate | Raise | Close | SetDesktop} WindowCommand + * @typedef {CursorQuery | OutputDesktop | WindowCommand} Command * @typedef {{ batch: number, cmds: Command[] }} Batch */ @@ -207,6 +223,59 @@ function cursor() { return { x: Math.round(p.x), y: Math.round(p.y) }; } +/** @returns {Desktop[]} */ +function desktops() { + var ds = []; + for (var i = 0; i < workspace.desktops.length; i++) { + ds.push({ id: String(workspace.desktops[i].id), name: String(workspace.desktops[i].name) }); + } + return ds; +} + +// The desktop each output shows. With per-output virtual desktops (which komorebi turns on) the +// outputs are independent: that is what lets each monitor have its own workspace in front. +/** @returns {CurrentDesktop[]} */ +function currentDesktops() { + var out = []; + for (var i = 0; i < workspace.screens.length; i++) { + var s = workspace.screens[i]; + out.push({ output: String(s.name), id: String(workspace.currentDesktopForScreen(s).id) }); + } + return out; +} + +/** + * @param {string} name + * @returns {Output | null} + */ +function screenByName(name) { + for (var i = 0; i < workspace.screens.length; i++) { + if (String(workspace.screens[i].name) === name) { + return workspace.screens[i]; + } + } + return null; +} + +// KWin has one signal for "an output changed desktop" and it does not say which, so the whole set is +// compared with what was last announced, here and once a second. +var lastCurrent = ""; +var lastDesktopList = ""; + +function announceDesktops() { + var list = JSON.stringify(desktops()); + if (list !== lastDesktopList) { + lastDesktopList = list; + emit("desktop_list", { desktops: JSON.parse(list) }); + } + + var now = JSON.stringify(currentDesktops()); + if (now !== lastCurrent) { + lastCurrent = now; + emit("current_desktops", { current: JSON.parse(now) }); + } +} + /** * @param {string} id * @returns {KWinWindow | null} @@ -224,6 +293,19 @@ function findWindow(id) { return null; } +/** + * @param {string} id + * @returns {VirtualDesktop | null} + */ +function findDesktop(id) { + for (var i = 0; i < workspace.desktops.length; i++) { + if (String(workspace.desktops[i].id) === id) { + return workspace.desktops[i]; + } + } + return null; +} + // A window has moved or been resized; if it is not where komorebi asked, ask again for the // position alone (see `want`). A few tries at most, so a window that cannot go where it was asked // (a fullscreen one, say) is left alone rather than chased. @@ -272,6 +354,9 @@ function track(w, announce) { w.captionChanged.connect(function () { emit("caption", { id: id, caption: String(w.caption) }); }); + w.desktopsChanged.connect(function () { + emit("desktops", { id: id, desktops: desktopIds(w) }); + }); } workspace.windowAdded.connect(function (w) { @@ -298,6 +383,12 @@ function announceActive(w) { } workspace.windowActivated.connect(announceActive); +workspace.currentDesktopChanged.connect(function () { + announceDesktops(); +}); +workspace.desktopsChanged.connect(function () { + announceDesktops(); +}); var existing = workspace.windowList(); for (var i = 0; i < existing.length; i++) { @@ -305,10 +396,14 @@ for (var i = 0; i < existing.length; i++) { } lastActive = workspace.activeWindow ? wid(workspace.activeWindow) : null; +lastCurrent = JSON.stringify(currentDesktops()); +lastDesktopList = JSON.stringify(desktops()); emit("snapshot", { windows: workspace.windowList().map(describe), screens: screens(), + desktops: desktops(), + current_desktops: currentDesktops(), active: workspace.activeWindow ? wid(workspace.activeWindow) : null, cursor: cursor() }); @@ -326,6 +421,15 @@ function applyOne(c) { emit("cursor", { token: c.token, x: p.x, y: p.y }); return true; } + if (c.op === "output_desktop") { + // show a desktop on one output, leaving the others as they are + var target = findDesktop(c.v); + var screen = screenByName(c.output); + if (target && screen) { + workspace.setCurrentDesktopForScreen(target, screen); + } + return !!(target && screen); + } var w = findWindow(c.id); if (!w) { @@ -349,6 +453,14 @@ function applyOne(c) { case "close": w.closeWindow(); break; + case "desktop": { + var d = findDesktop(c.v); + if (!d) { + return false; + } + w.desktops = [d]; + break; + } default: return false; } @@ -408,5 +520,6 @@ watchdog.timeout.connect(function () { if (Date.now() - lastIssue > CFG.hold_ms + 3000) { pull(); } + announceDesktops(); }); watchdog.start(); diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index d8abd4b0..6e06b419 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -57,13 +57,14 @@ function geometry(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, and `closeWindow` closes it -// once it is in a KWin. `place` is where KWin puts the window when it is asked for a frame: where -// it was asked, unless a test says otherwise. +// Setting `minimized`, `frameGeometry` or `desktops` raises the signal KWin raises, and +// `closeWindow` closes it once it is in a KWin. `place` is where KWin puts the window when it is +// asked for a frame: where it was asked, unless a test says otherwise. function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100), + desktops = [], place = (g) => g, ...rest }) { @@ -83,15 +84,22 @@ function window({ minSize: { width: 0, height: 0 }, move: false, resize: false, - desktops: [], frameGeometryChanged: new Signal(), minimizedChanged: new Signal(), captionChanged: new Signal(), + desktopsChanged: new Signal(), closeWindow: () => assert.fail("a window that is in no KWin was closed"), ...rest, }; - let state = { minimized, frameGeometry }; + let state = { minimized, frameGeometry, desktops }; Object.defineProperties(w, { + desktops: { + get: () => state.desktops, + set: (ds) => { + state.desktops = ds; + w.desktopsChanged.emit(); + }, + }, minimized: { get: () => state.minimized, set: (v) => { @@ -123,8 +131,23 @@ const DP1 = { placementArea: geometry(0, 0, 1920, 1050), }; +// the virtual desktops of a KWin that nobody has given any others +function twoDesktops() { + return [ + { id: "desktop-1", name: "Desktop 1" }, + { id: "desktop-2", name: "Desktop 2" }, + ]; +} + // 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 } } = {}) { +// Every output shows the first of `desktops`. +function kwin({ + windows = [], + screens = [DP1], + desktops = twoDesktops(), + active = null, + cursor = { x: 0, y: 0 }, +} = {}) { const calls = []; const printed = []; const raised = []; @@ -132,21 +155,30 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y const clock = { now: 1000 }; const open = []; let activeWindow = active; + const current = Object.fromEntries(screens.map((s) => [s.name, desktops[0]])); const workspace = { screens, + desktops, cursorPos: cursor, windowList: () => open.slice(), clientArea: (option, output, desktop) => { assert.equal(option, 7, "the placement area"); - assert.equal(desktop.id, `desktop of ${output.name}`); + assert.equal(desktop, current[output.name], "the desktop the output shows"); return output.placementArea; }, - currentDesktopForScreen: (output) => ({ id: `desktop of ${output.name}` }), + currentDesktopForScreen: (output) => current[output.name], + // per-output virtual desktops: the other outputs keep theirs + setCurrentDesktopForScreen: (desktop, output) => { + current[output.name] = desktop; + workspace.currentDesktopChanged.emit(); + }, raiseWindow: (w) => raised.push(w), windowAdded: new Signal(), windowRemoved: new Signal(), windowActivated: new Signal(), + currentDesktopChanged: new Signal(), + desktopsChanged: new Signal(), }; Object.defineProperty(workspace, "activeWindow", { get: () => activeWindow, @@ -219,6 +251,11 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y }, // the daemon answers the bridge's last `Poll` with these batches answer: (batches) => k.reply(JSON.stringify(batches)), + // somebody makes another desktop (System Settings, the pager) + createDesktop: (desktop) => { + desktops.push(desktop); + workspace.desktopsChanged.emit(); + }, }; return k; } @@ -267,7 +304,7 @@ test("what the bridge sends for a session is what the daemon's tests read", () = // the client took the frame it was given to whole cells of its font terminal.frameGeometry = geometry(480.4, 270, 956, 532); - const [cursorQuery, windowCommands] = commands; + const [cursorQuery, windowCommands, workspaceCommands] = commands; assert.equal(k.events().at(-1).seq, cursorQuery.after_seq); k.workspace.cursorPos = { x: 1200, y: 700.5 }; k.answer([cursorQuery.batch]); @@ -279,6 +316,19 @@ test("what the bridge sends for a session is what the daemon's tests read", () = assert.equal(k.events().at(-1).seq, windowCommands.after_seq); k.answer([windowCommands.batch]); + // the editor is sent to the second workspace, and the output is switched to it + assert.equal(k.events().at(-1).seq, workspaceCommands.after_seq); + k.answer([workspaceCommands.batch]); + const [first, second] = k.workspace.desktops; + // (an array the script made, whose prototype is not this file's) + assert.deepStrictEqual([...editor.desktops], [second]); + assert.equal(k.workspace.currentDesktopForScreen(DP1), second); + + // then somebody else makes a desktop, moves the editor back to the first, and shows that + k.createDesktop({ id: "desktop-3", name: "mail" }); + editor.desktops = [first]; + k.workspace.setCurrentDesktopForScreen(first, DP1); + assert.deepStrictEqual(k.events(), events); assert.deepStrictEqual(editor.frameGeometry, geometry(0, 0, 960, 1050)); assert.equal(k.workspace.activeWindow, editor); @@ -287,6 +337,52 @@ test("what the bridge sends for a session is what the daemon's tests read", () = assert.deepStrictEqual(k.workspace.windowList(), [editor]); }); +test("the desktop each output shows is sent when it changes, and once", () => { + const k = kwin(); + const [first, second] = k.workspace.desktops; + + k.workspace.setCurrentDesktopForScreen(second, DP1); + k.timers[0].timeout.emit(); + k.workspace.setCurrentDesktopForScreen(first, DP1); + + assert.deepStrictEqual(k.events().slice(1), [ + { type: "current_desktops", current: [{ output: "DP-1", id: "desktop-2" }], seq: 2 }, + { type: "current_desktops", current: [{ output: "DP-1", id: "desktop-1" }], seq: 3 }, + ]); +}); + +test("a desktop made while the bridge runs is sent as the new list of desktops", () => { + const k = kwin(); + + k.createDesktop({ id: "desktop-3", name: "mail" }); + + assert.deepStrictEqual(k.events().at(-1), { + type: "desktop_list", + desktops: [ + { id: "desktop-1", name: "Desktop 1" }, + { id: "desktop-2", name: "Desktop 2" }, + { id: "desktop-3", name: "mail" }, + ], + seq: 2, + }); +}); + +test("a desktop a command names that KWin does not have is given back as failed", () => { + const w = window({ id: "{w}", desktops: [{ id: "desktop-1" }] }); + const k = kwin({ windows: [w] }); + const commands = [ + { op: "desktop", id: "{w}", v: "gone" }, + { op: "output_desktop", output: "DP-1", v: "gone" }, + { op: "output_desktop", output: "HDMI-9", v: "desktop-2" }, + ]; + + k.answer([{ batch: 6, cmds: commands }]); + + assert.deepStrictEqual(w.desktops, [{ id: "desktop-1" }]); + assert.equal(k.workspace.currentDesktopForScreen(DP1).id, "desktop-1"); + assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 6, cmds: commands, seq: 2 }); +}); + test("a window KWin activates before announcing it is announced first, and once", () => { const k = kwin(); const w = window({ id: "{w}" }); diff --git a/komorebi/src/kwin/fixtures/commands.json b/komorebi/src/kwin/fixtures/commands.json index 62bafbd0..6351f964 100644 --- a/komorebi/src/kwin/fixtures/commands.json +++ b/komorebi/src/kwin/fixtures/commands.json @@ -20,5 +20,15 @@ } ] } + }, + { + "after_seq": 15, + "batch": { + "batch": 3, + "cmds": [ + {"op": "desktop", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": "desktop-2"}, + {"op": "output_desktop", "output": "DP-1", "v": "desktop-2"} + ] + } } ] diff --git a/komorebi/src/kwin/fixtures/events.json b/komorebi/src/kwin/fixtures/events.json index 994abb5b..6ec8d199 100644 --- a/komorebi/src/kwin/fixtures/events.json +++ b/komorebi/src/kwin/fixtures/events.json @@ -18,6 +18,10 @@ "area": {"x": 0, "y": 0, "w": 1920, "h": 1050} } ], + "desktops": [ + {"id": "desktop-1", "name": "Desktop 1"}, {"id": "desktop-2", "name": "Desktop 2"} + ], + "current_desktops": [{"output": "DP-1", "id": "desktop-1"}], "active": "{0e5a1c3b-0000-4000-8000-00000000000a}", "cursor": {"x": 481, "y": 525} }, { @@ -59,5 +63,22 @@ "w": 960, "h": 1050 } ] - } + }, + { + "type": "desktops", "seq": 16, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "desktops": ["desktop-2"] + }, + {"type": "current_desktops", "seq": 17, "current": [{"output": "DP-1", "id": "desktop-2"}]}, + { + "type": "desktop_list", "seq": 18, + "desktops": [ + {"id": "desktop-1", "name": "Desktop 1"}, {"id": "desktop-2", "name": "Desktop 2"}, + {"id": "desktop-3", "name": "mail"} + ] + }, + { + "type": "desktops", "seq": 19, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "desktops": ["desktop-1"] + }, + {"type": "current_desktops", "seq": 20, "current": [{"output": "DP-1", "id": "desktop-1"}]} ] diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts index 18e4e6c9..e9dffe99 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -45,8 +45,10 @@ interface QUuid { readonly __quuid: never; } +/** A virtual desktop (`KWin::VirtualDesktop`). `id` is a UUID, as a string. */ interface VirtualDesktop { readonly id: string; + readonly name: string; } /** An output (`KWin::Output`). */ @@ -82,10 +84,13 @@ interface KWinWindow { readonly move: boolean; /** True while the user resizes the window with the pointer. */ readonly resize: boolean; - readonly desktops: VirtualDesktop[]; + /** The desktops the window is on; empty when it is on all of them. Setting it moves the + * window. */ + desktops: VirtualDesktop[]; readonly frameGeometryChanged: Signal<[oldGeometry: QRectF]>; readonly minimizedChanged: Signal; readonly captionChanged: Signal; + readonly desktopsChanged: Signal; closeWindow(): void; } @@ -95,14 +100,24 @@ interface Workspace { /** Setting it activates the window. */ activeWindow: KWinWindow | null; readonly cursorPos: QPointF; + /** Every virtual desktop, in order. */ + readonly desktops: VirtualDesktop[]; windowList(): KWinWindow[]; clientArea(option: number, output: Output, desktop: VirtualDesktop): QRectF; + /** The desktop an output shows. With per-output virtual desktops each output has its own. */ currentDesktopForScreen(output: Output): VirtualDesktop; + /** Shows a desktop on one output; with per-output virtual desktops the others keep theirs. */ + setCurrentDesktopForScreen(desktop: VirtualDesktop, output: Output): void; raiseWindow(window: KWinWindow): void; readonly windowAdded: Signal<[window: KWinWindow]>; readonly windowRemoved: Signal<[window: KWinWindow]>; /** `null` when no window has the focus. */ readonly windowActivated: Signal<[window: KWinWindow | null]>; + /** Some output shows another desktop. It does not say which, and the bridge does not need + * what KWin passes with it: it reads the desktop of every output. */ + readonly currentDesktopChanged: Signal; + /** A desktop was created or removed. */ + readonly desktopsChanged: Signal; } declare const workspace: Workspace; diff --git a/komorebi/src/kwin/kwinrc.rs b/komorebi/src/kwin/kwinrc.rs new file mode 100644 index 00000000..52ab76c7 --- /dev/null +++ b/komorebi/src/kwin/kwinrc.rs @@ -0,0 +1,425 @@ +//! KWin's configuration file, `kwinrc`, for the setting komorebi changes: per-output virtual +//! desktops. +//! +//! These are the user's settings, changed on their behalf, so [`Kwinrc::set`] records the value of +//! every key the first time komorebi changes it, in a backup file, and [`Kwinrc::restore`] puts the +//! values back when komorebi exits. The backup outlives a crash: the next run finds it, keeps the +//! values it recorded (not the ones the crashed run wrote), and restores them at the end of that +//! run. The KWin backend keeps the backup in [`DATA_DIR`](struct@crate::DATA_DIR), which is under +//! `$XDG_RUNTIME_DIR` when there is one: such a directory is emptied at logout, so a backup a crash +//! left behind lasts until the session ends. +//! +//! KDE's tools (`kreadconfig6`, `kwriteconfig6`) are not used. The daemon runs as a user service +//! whose PATH need not have them: in a live Plasma 6.8.1 session, at time of writing (2026-10-27), +//! `kwriteconfig6` was not on that PATH, and per-output desktops stayed off. The file is plain ini, +//! which KConfig reads back, and a setting that silently was not changed is worse than one changed +//! by editing a file. +//! +//! # What is guaranteed, and by what +//! +//! | Rule | Enforced by | Proof | +//! |---|---|---| +//! | A key komorebi changed gets back the value it had before komorebi first changed it, and a key komorebi added is removed | [`Kwinrc::set`] records only the first value of a key; [`Kwinrc::restore`] | `kwin::kwinrc::tests::what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed` | +//! | A crash loses none of the recorded values | the backup file, read by the next run | `kwin::kwinrc::tests::a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run` | +//! | Only the line of the key changes; the rest of the file is left as it was | [`ini_set`], [`ini_unset`] | `kwin::kwinrc::tests::a_key_is_set_in_place_added_to_its_group_or_given_a_group`, `kwin::kwinrc::tests::a_key_is_removed_from_its_own_group_only` | +//! | KWin never reads a half-written file | [`Kwinrc`] writes a file beside `kwinrc` and renames it over it | no test | + +#![deny(missing_docs)] + +use serde::Deserialize; +use serde::Serialize; +use std::collections::BTreeMap; +use std::io; +use std::path::PathBuf; + +/// The value of each key before komorebi changed it, by group and key: `None` for a key that was +/// not in the user's file. +type Originals = BTreeMap>>; + +/// A `kwinrc` file that komorebi changes, and the backup of the values it changed. +pub struct Kwinrc { + /// The `kwinrc` that is read and written. + path: PathBuf, + /// The JSON file the original values are kept in. + backup: PathBuf, +} + +/// The contents of the backup file. +#[derive(Serialize, Deserialize, Default)] +struct Backup { + /// The value of every key komorebi changed, before it first changed it. + originals: Originals, +} + +impl Kwinrc { + /// Returns a `kwinrc` at `path`, with its backup at `backup`. Neither file has to exist. + pub fn new(path: PathBuf, backup: PathBuf) -> Self { + Self { path, backup } + } + + /// Returns the user's `kwinrc`, with the backup as `kwinrc-backup.json` in `data_dir`. + /// + /// The user's `kwinrc` is in `$XDG_CONFIG_HOME`, or in `~/.config` when that is not set. + /// Returns `None` when neither can be found. + pub fn user(data_dir: &std::path::Path) -> Option { + let config = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .or_else(|| dirs::home_dir().map(|home| home.join(".config")))?; + + Some(Self::new( + config.join("kwinrc"), + data_dir.join("kwinrc-backup.json"), + )) + } + + /// Returns the value of `key` in `[group]`, read the way KConfig cascades: from the user's file + /// if it has the key, else from the first `kwinrc` in `$XDG_CONFIG_DIRS` (`/etc/xdg` when that + /// is not set) that has it. + pub fn get(&self, group: &str, key: &str) -> Option { + let system = std::env::var("XDG_CONFIG_DIRS").unwrap_or_else(|_| "/etc/xdg".to_string()); + + std::iter::once(self.path.clone()) + .chain( + system + .split(':') + .map(|dir| PathBuf::from(dir).join("kwinrc")), + ) + .filter_map(|file| std::fs::read_to_string(file).ok()) + .find_map(|text| ini_value(&text, group, key)) + } + + /// Returns true if and only if the setting is `true`, as [`Kwinrc::get`] reads it. + pub fn is_on(&self, group: &str, key: &str) -> bool { + self.get(group, key).as_deref() == Some("true") + } + + /// Sets keys in a group, recording the value of each in the backup the first time komorebi + /// changes it. + /// + /// A key set a second time keeps the value recorded the first time, in this run or in one that + /// crashed, so [`Kwinrc::restore`] puts back what the user had. + /// + /// # Errors + /// + /// Returns an error if the backup or `kwinrc` cannot be written. The backup is written first: + /// when it cannot be, `kwinrc` is left as it was. + pub fn set(&self, group: &str, pairs: &[(&str, String)]) -> io::Result<()> { + let text = std::fs::read_to_string(&self.path).unwrap_or_default(); + + let mut backup = self.read_backup(); + let mut changed = false; + for (key, _) in pairs { + let originals = backup.originals.entry(group.to_string()).or_default(); + if !originals.contains_key(*key) { + originals.insert((*key).to_string(), ini_value(&text, group, key)); + changed = true; + } + } + if changed { + self.write_backup(&backup)?; + } + + let mut updated = text; + for (key, value) in pairs { + updated = ini_set(&updated, group, key, value); + } + self.write_file(&updated) + } + + /// Puts back everything [`Kwinrc::set`] changed, removes the backup, and returns true if and + /// only if there was anything to put back. + /// + /// # Errors + /// + /// Returns an error if `kwinrc` cannot be written, or if the backup cannot be removed after + /// `kwinrc` was written. + pub fn restore(&self) -> io::Result { + let backup = self.read_backup(); + if backup.originals.is_empty() { + let _ = std::fs::remove_file(&self.backup); + return Ok(false); + } + + let mut text = std::fs::read_to_string(&self.path).unwrap_or_default(); + for (group, keys) in &backup.originals { + for (key, original) in keys { + text = match original { + Some(value) => ini_set(&text, group, key, value), + None => ini_unset(&text, group, key), + }; + } + } + + self.write_file(&text)?; + std::fs::remove_file(&self.backup)?; + Ok(true) + } + + /// Returns the backup, or an empty one when there is no backup file or it cannot be read. + fn read_backup(&self) -> Backup { + std::fs::read_to_string(&self.backup) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() + } + + /// Writes the backup, creating its directory if needed. + fn write_backup(&self, backup: &Backup) -> io::Result<()> { + if let Some(dir) = self.backup.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::write( + &self.backup, + serde_json::to_string_pretty(backup).map_err(io::Error::other)?, + ) + } + + /// Writes `kwinrc`: the text goes into a file beside it, which is then renamed over it, so that + /// KWin never reads half of it. + fn write_file(&self, text: &str) -> io::Result<()> { + let dir = self.path.parent().map(PathBuf::from).unwrap_or_default(); + std::fs::create_dir_all(&dir)?; + let temporary = dir.join(".kwinrc.komorebi"); + std::fs::write(&temporary, text)?; + std::fs::rename(&temporary, &self.path) + } +} + +/// Returns the value of `key` in `[group]` of the ini text, trimmed, or `None` when the group does +/// not have the key. +/// +/// Covered by `kwin::kwinrc::tests::a_key_is_read_from_its_own_group_only`. +pub fn ini_value(text: &str, group: &str, key: &str) -> Option { + let mut in_group = false; + for line in text.lines().map(str::trim) { + if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + in_group = name == group; + } else if in_group + && let Some((k, v)) = line.split_once('=') + && k.trim() == key + { + return Some(v.trim().to_string()); + } + } + None +} + +/// Returns the ini text with `key=value` in `[group]`: the line of the key is replaced if there is +/// one, otherwise the line is added at the end of the group, and the group is added at the end of +/// the text when there is none. +/// +/// Every other line is left as it was, and the text returned ends with a newline. Covered by +/// `kwin::kwinrc::tests::a_key_is_set_in_place_added_to_its_group_or_given_a_group`. +pub fn ini_set(text: &str, group: &str, key: &str, value: &str) -> String { + let mut out: Vec = Vec::new(); + let mut in_group = false; + let mut done = false; + + let flush = |out: &mut Vec, done: &mut bool, in_group: bool| { + // leaving the group without having found the key: it goes at the end of the group + if in_group && !*done { + let mut at = out.len(); + while at > 0 && out[at - 1].trim().is_empty() { + at -= 1; + } + out.insert(at, format!("{key}={value}")); + *done = true; + } + }; + + for line in text.lines() { + let trimmed = line.trim(); + if let Some(name) = trimmed.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + flush(&mut out, &mut done, in_group); + in_group = name == group; + out.push(line.to_string()); + } else if in_group + && !done + && let Some((k, _)) = trimmed.split_once('=') + && k.trim() == key + { + out.push(format!("{key}={value}")); + done = true; + } else { + out.push(line.to_string()); + } + } + flush(&mut out, &mut done, in_group); + + if !done { + if out.last().is_some_and(|l| !l.trim().is_empty()) { + out.push(String::new()); + } + out.push(format!("[{group}]")); + out.push(format!("{key}={value}")); + } + + let mut joined = out.join("\n"); + joined.push('\n'); + joined +} + +/// Returns the ini text without `key` in `[group]`. +/// +/// A group left empty stays in place, which KConfig accepts. Every other line is left as it was. +/// Covered by `kwin::kwinrc::tests::a_key_is_removed_from_its_own_group_only`. +pub fn ini_unset(text: &str, group: &str, key: &str) -> String { + let mut in_group = false; + let mut out: Vec<&str> = Vec::new(); + + for line in text.lines() { + let trimmed = line.trim(); + if let Some(name) = trimmed.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + in_group = name == group; + } else if in_group + && let Some((k, _)) = trimmed.split_once('=') + && k.trim() == key + { + continue; + } + out.push(line); + } + + let mut joined = out.join("\n"); + if text.ends_with('\n') || !joined.is_empty() { + joined.push('\n'); + } + joined +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dir(name: &str) -> PathBuf { + let dir = PathBuf::from(format!( + "/tmp/komorebi-kwinrc-{}-{name}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn a_key_is_read_from_its_own_group_only() { + let rc = "[General]\nK=true\n\n[Windows]\nFocusPolicy=1\nK = false \n\n[Other]\nK=true\n"; + assert_eq!(ini_value(rc, "Windows", "K").as_deref(), Some("false")); + assert_eq!(ini_value(rc, "Windows", "Missing"), None); + assert_eq!(ini_value(rc, "Nowhere", "FocusPolicy"), None); + } + + #[test] + fn a_key_is_set_in_place_added_to_its_group_or_given_a_group() { + assert_eq!( + ini_set( + "[A]\nx=1\n\n[Windows]\nFocusPolicy=1\nK=old\n\n[B]\ny=2\n", + "Windows", + "K", + "new" + ), + "[A]\nx=1\n\n[Windows]\nFocusPolicy=1\nK=new\n\n[B]\ny=2\n" + ); + assert_eq!( + ini_set( + "[Windows]\nFocusPolicy=1\n\n[B]\ny=2\n", + "Windows", + "K", + "v" + ), + "[Windows]\nFocusPolicy=1\nK=v\n\n[B]\ny=2\n" + ); + assert_eq!( + ini_set("[A]\nx=1\n\n[Windows]\nFocusPolicy=1", "Windows", "K", "v"), + "[A]\nx=1\n\n[Windows]\nFocusPolicy=1\nK=v\n" + ); + assert_eq!( + ini_set("[A]\nx=1\n", "Windows", "K", "v"), + "[A]\nx=1\n\n[Windows]\nK=v\n" + ); + assert_eq!(ini_set("", "Windows", "K", "v"), "[Windows]\nK=v\n"); + assert_eq!( + ini_set("[Other]\nK=1\n", "Windows", "K", "v"), + "[Other]\nK=1\n\n[Windows]\nK=v\n" + ); + } + + #[test] + fn a_key_is_removed_from_its_own_group_only() { + assert_eq!( + ini_unset("[A]\nK=1\n[Windows]\nK=2\nJ=3\n", "Windows", "K"), + "[A]\nK=1\n[Windows]\nJ=3\n" + ); + } + + #[test] + fn what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed() { + let d = dir("backup"); + let rc = Kwinrc::new(d.join("kwinrc"), d.join("backup.json")); + let original = "[Windows]\nFocusPolicy=1\nShade=true\n\n[Round-Corners]\nSize=8\n"; + std::fs::write(d.join("kwinrc"), original).unwrap(); + + rc.set( + "Round-Corners", + &[ + ("Size", "20".into()), + ("OuterOutlineThickness", "10".into()), + ], + ) + .unwrap(); + rc.set("Windows", &[("PerOutputVirtualDesktops", "true".into())]) + .unwrap(); + // a second change to a key already changed must not overwrite what it was before komorebi + rc.set("Round-Corners", &[("Size", "30".into())]).unwrap(); + + let changed = std::fs::read_to_string(d.join("kwinrc")).unwrap(); + assert_eq!( + ini_value(&changed, "Round-Corners", "Size").as_deref(), + Some("30") + ); + assert!(rc.is_on("Windows", "PerOutputVirtualDesktops")); + + assert!(rc.restore().unwrap()); + let back = std::fs::read_to_string(d.join("kwinrc")).unwrap(); + assert_eq!( + ini_value(&back, "Round-Corners", "Size").as_deref(), + Some("8") + ); + assert_eq!( + ini_value(&back, "Round-Corners", "OuterOutlineThickness"), + None + ); + assert_eq!( + ini_value(&back, "Windows", "PerOutputVirtualDesktops"), + None + ); + assert_eq!( + ini_value(&back, "Windows", "FocusPolicy").as_deref(), + Some("1") + ); + assert!(!d.join("backup.json").exists()); + + // nothing left to restore + assert!(!rc.restore().unwrap()); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run() { + let d = dir("crash"); + let first = Kwinrc::new(d.join("kwinrc"), d.join("backup.json")); + std::fs::write(d.join("kwinrc"), "[Windows]\nK=orig\n").unwrap(); + first.set("Windows", &[("K", "komorebi".into())]).unwrap(); + + // the daemon dies; the next one starts with the changed file and the backup + let second = Kwinrc::new(d.join("kwinrc"), d.join("backup.json")); + second + .set("Windows", &[("K", "komorebi again".into())]) + .unwrap(); + second.restore().unwrap(); + + let back = std::fs::read_to_string(d.join("kwinrc")).unwrap(); + assert_eq!(ini_value(&back, "Windows", "K").as_deref(), Some("orig")); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index f8e04377..3825d6d7 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -34,11 +34,23 @@ //! owner again, the daemon loads the script into the new KWin, which reports its desktop as it //! does at start. //! +//! Workspaces are KWin's own virtual desktops, per output: workspace `i` is desktop `i`, and each +//! output shows a desktop of its own, which KWin does once its per-output virtual desktops are +//! turned on. [`connect`] turns them on in the user's `kwinrc` (the exit puts the user's setting +//! back), desktops are created over KWin's `org.kde.KWin.VirtualDesktopManager` interface when a +//! workspace has none, and the script switches an output's desktop and puts a window on a desktop. +//! When something other than komorebi does either, the script reports it, and the table turns it +//! into a [`WorkspaceChange`] or a [`WorkspaceMove`] for the window manager to follow. +//! +//! [`WorkspaceChange`]: crate::window_manager_event::WindowManagerEvent::WorkspaceChange +//! [`WorkspaceMove`]: crate::window_manager_event::WindowManagerEvent::WorkspaceMove +//! //! `docs/dev/PLATFORM.md` has the D-Bus names, the files and the environment variables involved, //! and `docs/dev/DESIGN.md` the reasons for this design. #![deny(missing_docs)] +mod kwinrc; pub mod state; use crate::DATA_DIR; @@ -54,6 +66,7 @@ use parking_lot::Condvar; use parking_lot::Mutex; use serde_json::Value; use serde_json::json; +use state::NeedsDesktops; use state::Output; use state::Table; use std::collections::HashMap; @@ -68,6 +81,7 @@ use tokio::runtime::Handle; use tokio::sync::Notify; use zbus::Connection; use zbus::interface; +use zbus::proxy::CacheProperties; use zbus::proxy::Proxy; const SERVICE: &str = "org.komorebi.Bridge"; @@ -104,6 +118,8 @@ struct Shared { /// runtime is then being shut down, and blocking on it panics alive: AtomicBool, connection: Mutex>, + /// the user's `kwinrc`, for the settings komorebi changes and puts back + kwinrc: Option, } impl Shared { @@ -252,6 +268,12 @@ pub struct KWinBackend { /// daemon exits or the session bus goes away. The same thread watches KWin on the bus, and loads /// the script again into a KWin that has restarted. /// +/// Before it loads the script, it turns on KWin's per-output virtual desktops in the user's +/// `kwinrc` (`[Windows] PerOutputVirtualDesktops`), unless they are on, and has KWin reload its +/// configuration. [`Backend::shutdown`] puts the user's setting back. A `kwinrc` that cannot be +/// written is logged, and komorebi runs on: with more than one monitor, a workspace switch then +/// switches every monitor. +/// /// # Errors /// /// - The session bus cannot be reached (`DBUS_SESSION_BUS_ADDRESS` is not set, or names a bus @@ -295,6 +317,7 @@ pub fn connect() -> eyre::Result> { handle: runtime.handle().clone(), alive: AtomicBool::new(true), connection: Mutex::new(None), + kwinrc: kwinrc::Kwinrc::user(&DATA_DIR), }); let (started_tx, started_rx) = std::sync::mpsc::channel::>(); @@ -366,9 +389,52 @@ async fn start(shared: Arc) -> eyre::Result<()> { })?; *shared.connection.lock() = Some(connection.clone()); + enable_per_output_desktops(&shared, &connection).await; load_script(&connection).await } +async fn kwin_reconfigure(connection: &Connection) { + let result = async { + let kwin = Proxy::new(connection, "org.kde.KWin", "/KWin", "org.kde.KWin").await?; + kwin.call_method("reconfigure", &()).await?; + eyre::Ok(()) + } + .await; + if let Err(error) = result { + tracing::warn!("could not ask KWin to reload its configuration: {error}"); + } +} + +/// Turn on KWin's per-output virtual desktops, which is how every monitor gets a workspace of its +/// own: without them, switching the desktop switches it on every output. The user's setting is put +/// back when komorebi exits (see [`kwinrc::Kwinrc`]). +async fn enable_per_output_desktops(shared: &Shared, connection: &Connection) { + let Some(kwinrc) = &shared.kwinrc else { + tracing::warn!("there is no configuration directory to find kwinrc in"); + return; + }; + + if kwinrc.is_on("Windows", "PerOutputVirtualDesktops") { + return; + } + + if let Err(error) = kwinrc.set( + "Windows", + &[("PerOutputVirtualDesktops", "true".to_string())], + ) { + tracing::warn!( + "could not turn on per-output virtual desktops ({error}): with more than one monitor, \ + switching workspace will switch them all" + ); + return; + } + + kwin_reconfigure(connection).await; + // the setting is applied as KWin reloads; the script reads the desktops right after + tokio::time::sleep(Duration::from_millis(300)).await; + tracing::info!("turned on KWin's per-output virtual desktops"); +} + /// 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!({ @@ -460,6 +526,62 @@ async fn supervise(shared: Arc) { } } +async fn desktop_manager(shared: &Shared) -> eyre::Result> { + let connection = shared.connection().await?; + // uncached: a property read right after createDesktop must not return the list from before it + Ok(zbus::proxy::Builder::new(&connection) + .destination("org.kde.KWin")? + .path("/VirtualDesktopManager")? + .interface("org.kde.KWin.VirtualDesktopManager")? + .cache_properties(CacheProperties::No) + .build() + .await?) +} + +/// `(position, id, name)`; kwin's introspection says `a(iss)` but the value on the wire is `a(uss)` +async fn desktops(manager: &Proxy<'static>) -> eyre::Result> { + Ok(manager.get_property("desktops").await?) +} + +/// "Desktop 2" is what KWin calls a desktop nobody named, and "Workspace 2" what komorebi calls one +/// it made for a workspace that has no name: neither is anyone's choice. +fn is_placeholder(name: &str) -> bool { + ["Desktop ", "Workspace "].iter().any(|prefix| { + name.strip_prefix(prefix) + .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) + }) +} + +/// Make sure there are desktops for these workspaces, naming the ones that are created. Existing +/// desktops keep their names, if they are somebody's: they may be the user's. +async fn create_workspace_desktops(shared: &Shared, names: &[String]) -> eyre::Result<()> { + let manager = desktop_manager(shared).await?; + let existing = desktops(&manager).await?; + let have = existing.len(); + + for (position, name) in names.iter().enumerate().skip(have) { + manager + .call_method("createDesktop", &(position as u32, name.as_str())) + .await?; + } + + // the ones nobody named take the workspaces' names; the ones somebody did keep theirs + for ((_, id, name), wanted) in existing.iter().zip(names) { + if is_placeholder(name) && !is_placeholder(wanted) { + manager + .call_method("setDesktopName", &(id.as_str(), wanted.as_str())) + .await?; + } + } + + let after = desktops(&manager).await?; + shared + .table + .lock() + .set_desktops(after.into_iter().map(|(_, id, name)| (id, name)).collect()); + Ok(()) +} + /// KWin's own "Move Mouse to Focus" action: the scripting API cannot move the pointer async fn move_mouse_to_focus(shared: &Shared) -> eyre::Result<()> { let connection = shared.connection().await?; @@ -481,6 +603,12 @@ fn command_rect(uuid: &str, rect: &Rect) -> Value { } impl KWinBackend { + /// A workspace was asked for that has no desktop: make desktops up to it + fn make_desktops(&self, count: usize) -> eyre::Result<()> { + let names: Vec = (1..=count).map(|n| format!("Workspace {n}")).collect(); + self.ensure_workspaces(&names) + } + fn command(&self, id: u32, build: impl FnOnce(&str) -> Value) -> eyre::Result<()> { let uuid = self .shared @@ -562,6 +690,51 @@ impl Backend for KWinBackend { self.command(id, |uuid| json!({ "op": "raise", "id": uuid })) } + fn ensure_workspaces(&self, names: &[String]) -> eyre::Result<()> { + let shared = self.shared.clone(); + let names = names.to_vec(); + self.shared + .block_on(async move { create_workspace_desktops(&shared, &names).await })? + } + + fn switch_workspace(&self, monitor_id: u32, idx: usize) -> eyre::Result<()> { + let commands = loop { + let attempt = self.shared.table.lock().switch_commands(monitor_id, idx); + match attempt { + Ok(commands) => break commands, + Err(NeedsDesktops(count)) => self.make_desktops(count)?, + } + }; + + for command in commands { + self.shared.push(command); + } + Ok(()) + } + + fn set_window_workspace(&self, id: u32, idx: usize) -> eyre::Result<()> { + let commands = loop { + let attempt = self.shared.table.lock().window_workspace_commands(id, idx); + match attempt { + Ok(commands) => break commands, + Err(NeedsDesktops(count)) => self.make_desktops(count)?, + } + }; + + for command in commands { + self.shared.push(command); + } + Ok(()) + } + + fn window_workspace(&self, id: u32) -> Option { + self.shared.table.lock().window_workspace(id) + } + + fn current_workspaces(&self) -> Vec<(u32, usize)> { + self.shared.table.lock().current_workspaces() + } + fn minimize(&self, id: u32) -> eyre::Result<()> { self.command(id, |uuid| json!({ "op": "min", "id": uuid, "v": true })) } @@ -590,7 +763,18 @@ impl Backend for KWinBackend { // 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 { + let told_kwin = self.shared.block_on(async move { + // every setting of KWin's that komorebi changed + if let Ok(connection) = shared.connection().await + && let Some(kwinrc) = &shared.kwinrc + { + match kwinrc.restore() { + Ok(true) => kwin_reconfigure(&connection).await, + Ok(false) => {} + Err(error) => tracing::warn!("could not put kwinrc back as it was: {error}"), + } + } + if let Ok(connection) = shared.connection().await && let Ok(scripting) = Proxy::new( &connection, @@ -603,6 +787,16 @@ impl Backend for KWinBackend { let _: Result = scripting.call("unloadScript", &(SCRIPT_NAME,)).await; } }); + + // KWin is gone (the session is being torn down, so this is not the way it usually ends): + // there is nobody to tell, but what komorebi changed in `kwinrc` is the user's, and a file + // can be put back without KWin + if told_kwin.is_err() + && let Some(kwinrc) = &self.shared.kwinrc + && let Err(error) = kwinrc.restore() + { + tracing::warn!("could not put kwinrc back as it was: {error}"); + } } } @@ -630,6 +824,7 @@ mod tests { handle: runtime.handle().clone(), alive: AtomicBool::new(true), connection: Mutex::new(None), + kwinrc: None, }); (runtime, KWinBackend { shared }) @@ -655,7 +850,7 @@ mod tests { 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); 2] = [ + let asks: [fn(&KWinBackend); 3] = [ |backend| { // nothing answers the query here, so the pointer is where the snapshot had it assert_eq!(backend.cursor_pos(), Some((481, 525))); @@ -677,6 +872,14 @@ mod tests { // the terminal has closed, and the table still knows it: the bridge gives it back backend.set_rect(2, &left(960)).unwrap(); }, + |backend| { + // the editor goes to the second workspace before the monitor is switched to it + let monitor = backend.monitors().unwrap()[0].id; + backend.set_window_workspace(1, 1).unwrap(); + backend.switch_workspace(monitor, 1).unwrap(); + assert_eq!(backend.window_workspace(1), Some(1)); + assert_eq!(backend.current_workspaces(), [(monitor, 1)]); + }, ]; assert_eq!(asks.len(), commands.len()); @@ -738,4 +941,26 @@ mod tests { assert_eq!(next_poll(&runtime, &backend), json!([])); } + + #[test] + fn a_desktop_nobody_named_is_a_placeholder() { + assert!(is_placeholder("Desktop 1")); + assert!(is_placeholder("Desktop 12")); + assert!(is_placeholder("Workspace 3")); + } + + #[test] + fn a_name_somebody_chose_is_not() { + for name in [ + "", + "Desktop", + "Desktop ", + "Desktop 1b", + "Mail", + "My Desktop 1", + "terminal", + ] { + assert!(!is_placeholder(name), "{name:?}"); + } + } } diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index 8324d6d1..cf8c05c0 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -1,11 +1,18 @@ -//! 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. +//! The daemon's model of the compositor: the windows, monitors and virtual desktops 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`]. //! +//! Every virtual desktop is a workspace: workspace `i` is KWin's desktop `i`, and each output +//! shows one desktop of its own, because komorebi turns on KWin's per-output virtual desktops. The +//! commands that show a workspace and put a window on one are made here too +//! ([`Table::switch_commands`], [`Table::window_workspace_commands`]), so that the table knows what +//! komorebi asked for and does not report it back as somebody else's doing. +//! //! # Example //! //! The script's first report is a snapshot of the desktop. A window that opens after it is an @@ -73,6 +80,7 @@ struct Entry { info: WindowInfo, /// What KWin says: a normal window, as opposed to a dialog, splash, panel, popup... kwin_normal: bool, + desktops: Vec, closed_at: Option, } @@ -107,6 +115,12 @@ pub struct Table { monitors: Vec, foreground: Option, cursor: Option<(i32, i32)>, + /// `(id, name)` of every virtual desktop, in KWin's order + desktops: Vec<(String, String)>, + /// The desktop each output shows, by output name. They are independent (komorebi turns on + /// KWin's per-output virtual desktops), which is what lets every monitor have a workspace of + /// its own in front. + current: HashMap, } fn rect(v: &Value) -> Rect { @@ -119,6 +133,16 @@ fn rect(v: &Value) -> Rect { } } +fn strings(v: &Value) -> Vec { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|s| s.as_str().map(String::from)) + .collect() + }) + .unwrap_or_default() +} + /// 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; @@ -209,11 +233,110 @@ impl Table { } /// Whether komorebi should have anything to do with this window: a normal window, as opposed - /// to a dialog, a panel, a popup. + /// to a dialog, a panel, a popup. Every desktop is a workspace of komorebi's. fn manageable(&self, entry: &Entry) -> bool { entry.kwin_normal } + // ---- workspaces ------------------------------------------------------------------------ + + /// The ids of the desktops that are workspaces, in order: all of them + fn workspace_desktops(&self) -> Vec<&str> { + self.desktops.iter().map(|(id, _)| id.as_str()).collect() + } + + /// Which workspace a desktop is + fn workspace_index(&self, desktop: &str) -> Option { + self.workspace_desktops().iter().position(|d| *d == desktop) + } + + /// Returns the workspace a window is on: the first of its desktops. A window on every desktop + /// (KWin gives it no desktop) is on none. + pub fn window_workspace(&self, id: u32) -> Option { + let entry = self.windows.get(&id)?; + let desktop = entry.desktops.first()?; + self.workspace_index(desktop) + } + + /// Returns the workspace each monitor shows, as `(monitor id, workspace index)` + pub fn current_workspaces(&self) -> Vec<(u32, usize)> { + self.monitors + .iter() + .filter_map(|m| { + let desktop = self.current.get(&m.name)?; + Some((m.id, self.workspace_index(desktop)?)) + }) + .collect() + } + + /// Returns how many workspace desktops there are + pub fn workspace_count(&self) -> usize { + self.workspace_desktops().len() + } + + /// Replaces the list of desktops with what KWin says it is now, for after komorebi created + /// some. The list is `(id, name)` pairs, in KWin's order. + pub fn set_desktops(&mut self, desktops: Vec<(String, String)>) { + self.desktops = desktops; + } + + /// Returns the commands that show workspace `idx` on a monitor, and records that the monitor + /// shows it, so that KWin's report of the switch is not taken for somebody else's. A monitor + /// the table does not know gets no command. + /// + /// # Errors + /// + /// [`NeedsDesktops`] when there are not that many desktops yet: make them, then ask again. + pub fn switch_commands( + &mut self, + monitor_id: u32, + idx: usize, + ) -> Result, NeedsDesktops> { + let desktop = self + .workspace_desktops() + .get(idx) + .map(|d| d.to_string()) + .ok_or(NeedsDesktops(idx + 1))?; + + let Some(monitor) = self.monitors.iter().find(|m| m.id == monitor_id) else { + return Ok(vec![]); + }; + + let output = monitor.name.clone(); + self.current.insert(output.clone(), desktop.clone()); + Ok(vec![ + json!({ "op": "output_desktop", "output": output, "v": desktop }), + ]) + } + + /// Returns the commands that put a window on workspace `idx`, and records the window there, + /// so that the next query sees it at once and KWin's report of the move raises nothing. A + /// window the table does not know gets no command. + /// + /// # Errors + /// + /// [`NeedsDesktops`] when there are not that many desktops yet: make them, then ask again. + pub fn window_workspace_commands( + &mut self, + id: u32, + idx: usize, + ) -> Result, NeedsDesktops> { + let desktop = self + .workspace_desktops() + .get(idx) + .map(|d| d.to_string()) + .ok_or(NeedsDesktops(idx + 1))?; + + let Some(entry) = self.windows.get_mut(&id) else { + return Ok(vec![]); + }; + + entry.desktops = vec![desktop.clone()]; + Ok(vec![ + json!({ "op": "desktop", "id": entry.uuid, "v": desktop }), + ]) + } + /// KWin went away. Its windows go with it, and nothing will report them closing. /// /// Returns a [`WindowManagerEvent::Destroy`] for every window the window manager may manage, @@ -282,6 +405,7 @@ impl Table { uuid, info, kwin_normal: w["normal"].as_bool().unwrap_or(false), + desktops: strings(&w["desktops"]), closed_at: None, }; @@ -321,9 +445,10 @@ impl Table { /// /// 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. + /// - `snapshot`: everything on the desktop (`windows`, `screens`, `desktops`, + /// `current_desktops`, `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, @@ -332,6 +457,13 @@ impl Table { /// [`WindowManagerEvent::Restore`]). /// - `caption`: a window's title changed ([`WindowManagerEvent::TitleUpdate`]). /// - `geometry`: a window's frame changed. It raises no event. + /// - `desktops`: a window is on other desktops. When it is now on another workspace than the + /// table had it on, this is a [`WindowManagerEvent::WorkspaceMove`]; komorebi's own move + /// ([`Table::window_workspace_commands`]) is on it already, and raises nothing. + /// - `current_desktops`: the desktop each output shows. An output that shows another desktop + /// than the table had it showing is a [`WindowManagerEvent::WorkspaceChange`]; komorebi's own + /// switch ([`Table::switch_commands`]) raises nothing. + /// - `desktop_list`: the virtual desktops, in order. It raises no event. /// - `cursor`: the answer to a cursor query ([`Output::Cursor`]). /// - `failed`: commands the script could not carry out. They are logged. /// @@ -353,6 +485,12 @@ impl Table { } vec![] } + Some("desktops") => self.on_desktops(event), + Some("current_desktops") => self.on_current_desktops(event), + Some("desktop_list") => { + self.desktops = desktop_list(&event["desktops"]); + vec![] + } Some("cursor") => { let (x, y) = ( event["x"].as_i64().unwrap_or(0) as i32, @@ -387,6 +525,10 @@ impl Table { } fn on_snapshot(&mut self, event: &Value) -> Vec { + // desktops first: which workspace a window is on depends on them + self.desktops = desktop_list(&event["desktops"]); + self.current = current_map(&event["current_desktops"]); + // 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() { @@ -536,8 +678,112 @@ impl Table { vec![] } } + + fn on_desktops(&mut self, event: &Value) -> Vec { + let Some(id) = self.id_of(event) else { + return vec![]; + }; + + let before = self.window_workspace(id); + let desktops = strings(&event["desktops"]); + + if let Some(entry) = self.windows.get_mut(&id) { + entry.desktops = desktops; + } + + // A window that is on another workspace's desktop than it was: komorebi's own doing coming + // back (the window manager already has it there) or somebody else's, which it will adopt. + let after = self + .windows + .get(&id) + .filter(|e| e.info.normal && e.info.alive) + .and_then(|e| e.desktops.first()) + .and_then(|d| self.workspace_index(d)); + + match after { + Some(idx) if before != Some(idx) => { + vec![Output::Event(WindowManagerEvent::WorkspaceMove( + kwin(KWinNotification::WindowMovedToDesktop), + Window::from(id), + idx, + ))] + } + _ => vec![], + } + } + + /// Some output now shows another desktop: komorebi's request, or a pager, a shortcut, an app + /// raising a window (KWin switches that output to the window's desktop) + fn on_current_desktops(&mut self, event: &Value) -> Vec { + let now = current_map(&event["current"]); + let mut out = vec![]; + + let mut changes: Vec<(String, String)> = now + .iter() + .filter(|(output, desktop)| self.current.get(*output) != Some(*desktop)) + .map(|(o, d)| (o.clone(), d.clone())) + .collect(); + changes.sort(); + + for (output, desktop) in changes { + self.current.insert(output.clone(), desktop.clone()); + + let (Some(idx), Some(monitor)) = ( + self.workspace_index(&desktop), + self.monitors.iter().find(|m| m.name == output), + ) else { + continue; + }; + + out.push(Output::Event(WindowManagerEvent::WorkspaceChange( + kwin(KWinNotification::WorkspaceChanged), + monitor.id, + idx, + ))); + } + + out + } } +fn desktop_list(v: &Value) -> Vec<(String, String)> { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|d| { + Some(( + d["id"].as_str()?.to_string(), + d["name"].as_str()?.to_string(), + )) + }) + .collect() + }) + .unwrap_or_default() +} + +fn current_map(v: &Value) -> HashMap { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|d| { + Some(( + d["output"].as_str()?.to_string(), + d["id"].as_str()?.to_string(), + )) + }) + .collect() + }) + .unwrap_or_default() +} + +/// The error of a request for a workspace that has no desktop yet: at least this many desktops +/// are needed. +/// +/// [`Table::switch_commands`] and [`Table::window_workspace_commands`] return it; the KWin backend +/// makes the desktops and asks again. +#[derive(Debug)] +pub struct NeedsDesktops(pub usize); + /// 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. @@ -582,6 +828,8 @@ mod tests { "geo": { "x": 0, "y": 0, "w": 1920, "h": 1080 }, "area": { "x": 0, "y": 0, "w": 1920, "h": 1050 }, }], + "desktops": [{ "id": "d1", "name": "Desktop 1" }, { "id": "d2", "name": "Desktop 2" }], + "current_desktops": [{ "output": "DP-1", "id": "d1" }], "active": null, "cursor": { "x": 5, "y": 6 }, }) @@ -614,18 +862,33 @@ mod tests { 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}")); - } - } + let said: Vec = out + .iter() + .map(|output| match output { + Output::Event(WindowManagerEvent::WorkspaceMove(_, window, idx)) => { + format!("WorkspaceMove {} to {idx}", window.id) + } + Output::Event(WindowManagerEvent::WorkspaceChange(_, _, idx)) => { + format!("WorkspaceChange to {idx}") + } + Output::Event(e) => format!("{e} {}", e.window_id().unwrap_or(0)), + Output::Cursor { token, x, y } => format!("Cursor {token} at {x},{y}"), + }) + .collect(); trace.push(format!( "{} -> {}", event["type"].as_str().unwrap(), said.join(", ") )); + // what komorebi asks for next (fixtures/commands.json, batch 3): the editor on the + // second workspace, and the output showing it + if event["seq"] == 15 { + let monitor = t.monitors()[0].id; + t.window_workspace_commands(1, 1).unwrap(); + t.switch_commands(monitor, 1).unwrap(); + } + if event["type"] == "added" && event["caption"] == "a terminal" { let w = t.window(2).unwrap(); assert_eq!( @@ -664,6 +927,13 @@ mod tests { "minimized -> Restore 1", "removed -> ", "failed -> ", + // komorebi's own move and switch, coming back + "desktops -> ", + "current_desktops -> ", + // somebody else's: a new desktop, the editor moved back, the first one shown + "desktop_list -> ", + "desktops -> WorkspaceMove 1 to 0", + "current_desktops -> WorkspaceChange to 0", ] ); @@ -676,6 +946,9 @@ mod tests { assert_eq!(t.window(2).unwrap().rect.bottom, 532, "the geometry event"); assert_eq!(t.foreground(), Some(1)); assert_eq!(t.cursor(), Some((1200, 701))); + assert_eq!(t.workspace_count(), 3); + assert_eq!(t.window_workspace(1), Some(0)); + assert_eq!(t.current_workspaces(), [(t.monitors()[0].id, 0)]); let monitor = &t.monitors()[0]; assert_eq!( @@ -714,6 +987,7 @@ mod tests { } ); assert_eq!(t.cursor(), Some((5, 6))); + assert_eq!(t.current_workspaces(), vec![(t.monitors()[0].id, 0)]); } #[test] @@ -892,6 +1166,167 @@ mod tests { assert_eq!(t.window(1).unwrap().title, "renamed"); } + #[test] + fn every_desktop_is_a_workspace_and_a_window_is_on_the_one_it_is_on() { + let t = table(vec![ + win("first", &["d1"]), + win("second", &["d2"]), + win("everywhere", &[]), + ]); + + assert_eq!( + t.windows().len(), + 3, + "windows on any desktop are komorebi's" + ); + assert_eq!(t.window_workspace(1), Some(0)); + assert_eq!(t.window_workspace(2), Some(1)); + assert_eq!( + t.window_workspace(3), + None, + "a window on every desktop is on none" + ); + assert_eq!(t.workspace_count(), 2); + } + + #[test] + fn moving_a_window_to_another_desktop_is_reported_once_as_a_workspace_move() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + + let out = t.handle( + &json!({ "type": "desktops", "id": "a", "desktops": ["d2"] }), + now, + ); + assert!( + matches!( + &out[..], + [Output::Event(WindowManagerEvent::WorkspaceMove(_, _, 1))] + ), + "{out:?}" + ); + assert_eq!(t.window_workspace(1), Some(1)); + assert!(t.window(1).unwrap().normal); + + // the same again is nothing new + let out = t.handle( + &json!({ "type": "desktops", "id": "a", "desktops": ["d2"] }), + now, + ); + assert!(out.is_empty()); + } + + #[test] + fn komorebis_own_move_coming_back_from_kwin_raises_nothing() { + let mut t = table(vec![win("a", &["d1"])]); + + // komorebi put it on workspace 1; kwin says so + t.window_workspace_commands(1, 1).unwrap(); + let out = t.handle( + &json!({ "type": "desktops", "id": "a", "desktops": ["d2"] }), + Instant::now(), + ); + + assert!(out.is_empty(), "{out:?}"); + } + + #[test] + fn a_window_is_put_on_a_workspace_by_putting_it_on_its_desktop() { + let mut t = table(vec![win("a", &["d1"])]); + + assert_eq!( + t.window_workspace_commands(1, 1).unwrap(), + vec![json!({ "op": "desktop", "id": "a", "v": "d2" })] + ); + assert_eq!( + t.window_workspace(1), + Some(1), + "visible to the next query at once" + ); + } + + #[test] + fn showing_a_workspace_switches_that_output_only() { + let mut t = table(vec![]); + let monitor = t.monitors()[0].id; + + assert_eq!( + t.switch_commands(monitor, 1).unwrap(), + vec![json!({ "op": "output_desktop", "output": "DP-1", "v": "d2" })] + ); + assert_eq!(t.current_workspaces(), vec![(monitor, 1)]); + } + + #[test] + fn a_workspace_without_a_desktop_asks_for_one() { + let mut t = table(vec![win("a", &["d1"])]); + let monitor = t.monitors()[0].id; + + assert!(matches!( + t.switch_commands(monitor, 4), + Err(NeedsDesktops(5)) + )); + assert!(matches!( + t.window_workspace_commands(1, 2), + Err(NeedsDesktops(3)) + )); + } + + #[test] + fn another_party_switching_a_monitor_is_a_workspace_change() { + let mut t = table(vec![]); + let monitor = t.monitors()[0].id; + + let out = t.handle( + &json!({ "type": "current_desktops", "current": [{ "output": "DP-1", "id": "d2" }] }), + Instant::now(), + ); + assert!( + matches!(&out[..], [Output::Event(WindowManagerEvent::WorkspaceChange(_, m, 1))] if *m == monitor), + "{out:?}" + ); + + // the same again says nothing + let out = t.handle( + &json!({ "type": "current_desktops", "current": [{ "output": "DP-1", "id": "d2" }] }), + Instant::now(), + ); + assert!(out.is_empty()); + } + + #[test] + fn komorebi_switching_a_monitor_comes_back_as_a_change_to_what_it_already_knows() { + let mut t = table(vec![]); + let monitor = t.monitors()[0].id; + t.switch_commands(monitor, 1).unwrap(); + + // the table already believes it, so KWin's report of it raises nothing a second time + let out = t.handle( + &json!({ "type": "current_desktops", "current": [{ "output": "DP-1", "id": "d2" }] }), + Instant::now(), + ); + assert!(out.is_empty(), "{out:?}"); + } + + #[test] + fn a_new_list_of_desktops_is_read_and_raises_nothing() { + let mut t = table(vec![win("a", &["d3"])]); + assert_eq!(t.window_workspace(1), None, "d3 is not a desktop yet"); + + let out = t.handle( + &json!({ "type": "desktop_list", "desktops": [ + { "id": "d1", "name": "Desktop 1" }, + { "id": "d2", "name": "Desktop 2" }, + { "id": "d3", "name": "mail" }, + ] }), + Instant::now(), + ); + + assert!(out.is_empty(), "{out:?}"); + assert_eq!(t.workspace_count(), 3); + assert_eq!(t.window_workspace(1), Some(2)); + } + #[test] fn a_cursor_query_answer_is_passed_on_and_remembered() { let mut t = table(vec![]); diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 7be95cea..18160570 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -5,11 +5,19 @@ //! one. Before the focused workspace is tiled it is given the monitor's work area, the monitor's //! padding (or [`DEFAULT_CONTAINER_PADDING`] and [`DEFAULT_WORKSPACE_PADDING`]) and the work area //! offset ([`WorkspaceGlobals`]). +//! +//! Workspace `i` of a monitor is the compositor's virtual desktop `i` on that monitor. Showing +//! another workspace ([`Monitor::load_focused_workspace`]) puts every window on the desktop of the +//! workspace it is in, asks the compositor to show the focused workspace's desktop, which shows its +//! windows and hides the others, and gives the focus to the workspace's focused window. use crate::DEFAULT_CONTAINER_PADDING; use crate::DEFAULT_WORKSPACE_PADDING; +use crate::backend::backend; use crate::container::Container; +use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::OperationDirection; use crate::core::Rect; use crate::ring::Ring; use crate::workspace::Workspace; @@ -174,10 +182,207 @@ impl Monitor { Ok(()) } + /// Make this monitor show its focused workspace. + /// + /// The workspaces are the compositor's virtual desktops, so this is a request to switch the + /// desktop this monitor shows, and the compositor shows the windows on it and hides the rest. + /// What is left for komorebi is to tile the windows that came into view. + pub fn load_focused_workspace(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> { + let focused_idx = self.focused_workspace_idx(); + let monitor_id = self.id; + + // a window moved to this workspace has to be on its desktop before the desktop is shown + // and a window of it focused, or focusing it would take the monitor back to the desktop it + // was on + self.assign_windows_to_workspaces(); + + if let Err(error) = backend().switch_workspace(monitor_id, focused_idx) { + tracing::warn!("could not show workspace {focused_idx}: {error}"); + } + + if let Some(workspace) = self.workspaces_mut().get_mut(focused_idx) { + workspace.restore(mouse_follows_focus)?; + } + + Ok(()) + } + + /// Put every window of every workspace of this monitor on that workspace's desktop, unless it + /// already is. komorebi decides which workspace a window belongs to (a window sent to another + /// workspace, a new window, a rule); this is how the compositor learns of it. + pub fn assign_windows_to_workspaces(&self) { + for (idx, workspace) in self.workspaces().iter().enumerate() { + let windows = workspace + .containers() + .iter() + .flat_map(|c| c.windows().iter()) + .chain(workspace.floating_windows().iter()); + + for window in windows { + if backend().window_workspace(window.id) != Some(idx) + && let Err(error) = backend().set_window_workspace(window.id, idx) + { + tracing::debug!( + "could not put window {} on workspace {idx}: {error}", + window.id + ); + } + } + } + } + pub fn new_workspace_idx(&self) -> usize { self.workspaces().len() } + /// Moves the focused container of the focused workspace, or the focused window when it is a + /// floating one, to the back of workspace `target_workspace_idx`, creating the workspace (and + /// the ones before it) if it does not exist, and focuses that workspace when `follow` is set. + /// + /// With a `direction`, the container goes where a container moved across a boundary in that + /// direction goes ([`Monitor::add_container_with_direction`]). + #[tracing::instrument(skip(self))] + pub fn move_container_to_workspace( + &mut self, + target_workspace_idx: usize, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + let workspace = self + .focused_workspace_mut() + .ok_or_eyre("there is no workspace")?; + + let foreground_hwnd = if !cfg!(test) { + backend() + .foreground_window() + .ok_or_eyre("no foreground window")? + } else { + 0 + }; + + let floating_window_index = workspace + .floating_windows() + .iter() + .position(|w| w.id == foreground_hwnd); + + if let Some(idx) = floating_window_index { + if let Some(window) = workspace.floating_windows_mut().remove(idx) { + let workspaces = self.workspaces_mut(); + #[allow(clippy::option_if_let_else)] + let target_workspace = match workspaces.get_mut(target_workspace_idx) { + None => { + workspaces.resize(target_workspace_idx + 1, Workspace::default()); + workspaces.get_mut(target_workspace_idx).unwrap() + } + Some(workspace) => workspace, + }; + + target_workspace.floating_windows_mut().push_back(window); + } + } else { + let container = workspace + .remove_focused_container() + .ok_or_eyre("there is no container")?; + + let workspaces = self.workspaces_mut(); + + #[allow(clippy::option_if_let_else)] + let target_workspace = match workspaces.get_mut(target_workspace_idx) { + None => { + workspaces.resize(target_workspace_idx + 1, Workspace::default()); + workspaces.get_mut(target_workspace_idx).unwrap() + } + Some(workspace) => workspace, + }; + + if let Some(direction) = direction { + self.add_container_with_direction( + container, + Some(target_workspace_idx), + direction, + )?; + } else { + target_workspace.add_container_to_back(container); + } + } + + if follow { + self.focus_workspace(target_workspace_idx)?; + } + + Ok(()) + } + + /// Adds a container to this `Monitor` using the move direction to calculate if the container + /// should be added in front of all containers, in the back or in place of the focused + /// container, moving the rest along. The move direction should be from the origin monitor + /// towards the target monitor or from the origin workspace towards the target workspace. + pub fn add_container_with_direction( + &mut self, + container: Container, + workspace_idx: Option, + direction: OperationDirection, + ) -> eyre::Result<()> { + let workspace = if let Some(idx) = workspace_idx { + self.workspaces_mut() + .get_mut(idx) + .ok_or_eyre(format!("there is no workspace at index {}", idx))? + } else { + self.focused_workspace_mut() + .ok_or_eyre("there is no workspace")? + }; + + match direction { + OperationDirection::Left => { + // insert the container into the workspace on the monitor at the back (or rightmost position) + // if we are moving across a boundary to the left (back = right side of the target) + match workspace.layout { + Layout::Default(layout) => match layout { + DefaultLayout::RightMainVerticalStack => { + workspace.add_container_to_front(container); + } + DefaultLayout::UltrawideVerticalStack + if workspace.containers().len() == 1 => + { + workspace.insert_container_at_idx(0, container); + } + _ => { + workspace.add_container_to_back(container); + } + }, + } + } + OperationDirection::Right => { + // insert the container into the workspace on the monitor at the front (or leftmost position) + // if we are moving across a boundary to the right (front = left side of the target) + match workspace.layout { + Layout::Default(layout) => { + let target_index = layout.leftmost_index(workspace.containers().len()); + + match layout { + DefaultLayout::RightMainVerticalStack + | DefaultLayout::UltrawideVerticalStack + if workspace.containers().len() == 1 => + { + workspace.add_container_to_back(container); + } + _ => { + workspace.insert_container_at_idx(target_index, container); + } + } + } + } + } + OperationDirection::Up | OperationDirection::Down => { + // insert the container into the workspace on the monitor at the position + // where the currently focused container on that workspace is + workspace.insert_container_at_idx(workspace.focused_container_idx(), container); + } + }; + + Ok(()) + } + pub fn remove_workspace_by_idx(&mut self, idx: usize) -> Option { if idx < self.workspaces().len() { return self.workspaces_mut().remove(idx); @@ -380,6 +585,106 @@ mod tests { assert_eq!(new_workspace_index, 1); } + #[test] + fn test_move_container_to_workspace() { + let mut m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + let new_workspace_index = m.new_workspace_idx(); + assert_eq!(new_workspace_index, 1); + + { + // Create workspace 1 and add 3 containers + let workspace = m.focused_workspace_mut().unwrap(); + for _ in 0..3 { + let container = Container::default(); + workspace.add_container_to_back(container); + } + + // Should have 3 containers in workspace 1 + assert_eq!(m.focused_workspace().unwrap().containers().len(), 3); + } + + // Create and focus workspace 2 + m.focus_workspace(new_workspace_index).unwrap(); + + // Focus workspace 1 + m.focus_workspace(0).unwrap(); + + // Move container to workspace 2 + m.move_container_to_workspace(1, true, None).unwrap(); + + // Should be focused on workspace 2 + assert_eq!(m.focused_workspace_idx(), 1); + + // Workspace 2 should have 1 container now + assert_eq!(m.focused_workspace().unwrap().containers().len(), 1); + + // Move to workspace 1 + m.focus_workspace(0).unwrap(); + + // Workspace 1 should have 2 containers + assert_eq!(m.focused_workspace().unwrap().containers().len(), 2); + + // Move a another container from workspace 1 to workspace 2 without following + m.move_container_to_workspace(1, false, None).unwrap(); + + // Should have 1 container + assert_eq!(m.focused_workspace().unwrap().containers().len(), 1); + + // Should still be focused on workspace 1 + assert_eq!(m.focused_workspace_idx(), 0); + + // Switch to workspace 2 + m.focus_workspace(1).unwrap(); + + // Workspace 2 should now have 2 containers + assert_eq!(m.focused_workspace().unwrap().containers().len(), 2); + } + + #[test] + fn test_move_container_to_nonexistent_workspace() { + let mut m = Monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestDevice", + "TestDeviceId", + ); + + { + // Create workspace 1 and add 3 containers + let workspace = m.focused_workspace_mut().unwrap(); + for _ in 0..3 { + let container = Container::default(); + workspace.add_container_to_back(container); + } + + // Should have 3 containers in workspace 1 + assert_eq!(m.focused_workspace().unwrap().containers().len(), 3); + } + + // Should only have 1 workspace + assert_eq!(m.workspaces().len(), 1); + + // Try to move a container to a workspace that doesn't exist + m.move_container_to_workspace(8, true, None).unwrap(); + + // Should have 9 workspaces now + assert_eq!(m.workspaces().len(), 9); + + // Should be focused on workspace 8 + assert_eq!(m.focused_workspace_idx(), 8); + + // Should have 1 container in workspace 8 + assert_eq!(m.focused_workspace().unwrap().containers().len(), 1); + } + #[test] fn test_ensure_workspace_count_workspace_contains_two_workspaces() { let mut m = Monitor::new( diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 2485ed96..da0b26c0 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -81,6 +81,12 @@ //! [`WindowManager::resize_delta`] that **ResizeDelta** sets ([`WindowManager::resize_window`]), //! and **QuickSave**, **QuickLoad**, **Save** and **Load** write the resize adjustments of the //! focused workspace's containers to a file and read them back. +//! - **FocusWorkspaceNumber** shows a workspace of the focused monitor, by its index +//! ([`WindowManager::focus_workspace`]): the compositor is asked to show its desktop on that +//! monitor. **MoveContainerToWorkspaceNumber** moves the focused container to a workspace and +//! shows it, and **SendContainerToWorkspaceNumber** moves it there and stays +//! ([`WindowManager::move_container_to_workspace`]). A workspace that does not exist yet is +//! made, with the ones before it. //! - **Retile** tiles the focused workspace of every monitor again, without the resize //! adjustments, and **RetileWithResizeDimensions** with them. //! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name @@ -202,6 +208,10 @@ impl WindowManager { /// `UnlockMonitorWorkspaceContainer` is not there (a container that is not there is ignored). /// - The focused window cannot be floated or put back, for one of the reasons /// [`WindowManager::toggle_float`] gives. + /// - The focused monitor has no workspace or no container to move to another workspace, or + /// the compositor reports no window with the focus (`MoveContainerToWorkspaceNumber`, + /// `SendContainerToWorkspaceNumber`), or the focused window of the workspace that is shown + /// cannot be focused. /// - The monitor or the workspace of `WorkspacePadding` or `ContainerPadding` is not there, or /// the focused workspace has no padding of its own for `AdjustWorkspacePadding` or /// `AdjustContainerPadding` to change. @@ -272,6 +282,18 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::FocusWorkspaceNumber(workspace_idx) => { + if self.focused_workspace_idx().unwrap_or_default() != workspace_idx { + self.focus_workspace(workspace_idx)?; + } + } + + SocketMessage::MoveContainerToWorkspaceNumber(workspace_idx) => { + self.move_container_to_workspace(workspace_idx, true, None)?; + } + SocketMessage::SendContainerToWorkspaceNumber(workspace_idx) => { + self.move_container_to_workspace(workspace_idx, false, None)?; + } SocketMessage::ToggleFloat => self.toggle_float(false)?, SocketMessage::ResizeWindowEdge(direction, sizing) => { self.resize_window(direction, sizing, self.resize_delta, true)?; @@ -904,6 +926,11 @@ mod tests { use crate::backend::fake::FakeBackend; use crate::backend::with_backend; use crate::core::Rect; + use crate::monitor; + use crate::window_manager_event::WindowManagerEvent; + use crossbeam_channel::Receiver; + use crossbeam_channel::Sender; + use crossbeam_channel::bounded; use std::io::Read; use std::io::Write; use std::net::Shutdown; @@ -1121,4 +1148,53 @@ mod tests { assert!(reply.is_err()); } + + fn send_socket_message(socket: &PathBuf, message: SocketMessage) { + let mut stream = UnixStream::connect(socket).unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(1))) + .unwrap(); + stream + .write_all(serde_json::to_string(&message).unwrap().as_bytes()) + .unwrap(); + } + + #[test] + fn test_receive_socket_message() { + let (_sender, receiver): (Sender, Receiver) = + bounded(1); + // /tmp: short enough for a unix socket path on macOS, and writable wherever the tests run + let socket_name = format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4()); + let socket_path = PathBuf::from(&socket_name); + let mut wm = WindowManager::new(receiver, Some(socket_path.clone())).unwrap(); + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + wm.monitors_mut().push_back(m); + + // send a message + send_socket_message(&socket_path, SocketMessage::FocusWorkspaceNumber(5)); + + let (stream, _) = wm.command_listener.accept().unwrap(); + let reader = BufReader::new(stream.try_clone().unwrap()); + let next = reader.lines().next(); + + // read and deserialize the message + let message_string = next.unwrap().unwrap(); + let message = SocketMessage::from_str(&message_string).unwrap(); + assert!(matches!(message, SocketMessage::FocusWorkspaceNumber(5))); + + // process the message + wm.process_command(message, stream).unwrap(); + + // check the updated window manager state + assert_eq!(wm.focused_workspace_idx().unwrap(), 5); + + std::fs::remove_file(socket_path).unwrap(); + } } diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index fc017144..ca4e4385 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -20,6 +20,17 @@ //! again; **Restore** brings it back in a container of its own. //! - **TitleUpdate**: a window komorebi does not have, and that was not minimized, is announced //! again as a Show, so that a rule that matches on the title it has now decides. +//! - **WorkspaceChange**: a monitor shows another workspace, because something other than komorebi +//! switched it (a pager, a shortcut, an app raising a window of another desktop). The window +//! manager follows ([`WindowManager::adopt_workspace_change`]) and asks the compositor for +//! nothing: it has already shown the windows and chosen which to focus. komorebi's own switch +//! comes back as one too, and changes nothing. +//! - **WorkspaceMove**: a window was put on the desktop of another workspace by something other +//! than komorebi. It moves to that workspace, and whichever of the two is in front is tiled +//! again. +//! +//! A window that is shown or managed is put on the desktop of the workspace it was managed into +//! ([`Monitor::assign_windows_to_workspaces`]). //! //! 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. @@ -28,6 +39,7 @@ //! of it ([`notify_subscribers`]). //! //! [`Window::should_manage`]: crate::window::Window::should_manage +//! [`Monitor::assign_windows_to_workspaces`]: crate::monitor::Monitor::assign_windows_to_workspaces use crate::FLOATING_APPLICATIONS; use crate::Notification; @@ -107,6 +119,11 @@ impl WindowManager { return Ok(()); } + // a monitor changed which workspace it shows; nothing to do with any window + if let WindowManagerEvent::WorkspaceChange(_, monitor_id, idx) = event { + return self.adopt_workspace_change(monitor_id, idx); + } + let Some(window) = event.window() else { return Ok(()); }; @@ -144,6 +161,7 @@ impl WindowManager { match event { WindowManagerEvent::FocusChange(_, _) => { + let is_known = self.known_window_ids.get(&window_id).cloned(); let mut is_on_current_workspace = false; // don't want to trigger the full workspace updates when there are no managed @@ -172,6 +190,38 @@ impl WindowManager { { self.update_focused_workspace(self.mouse_follows_focus, false)?; } + + // A window of another workspace being activated (an app raising itself) makes + // KWin switch that monitor to the window's desktop, and tells us in a + // `WorkspaceChange`: there is nothing to do about the window until that arrives + let _ = (is_known, is_on_current_workspace); + } + // handled before the window is looked up + WindowManagerEvent::WorkspaceChange(..) => {} + WindowManagerEvent::WorkspaceMove(_, _, idx) => { + // somebody put the window on another workspace's desktop: it belongs there now. + // (komorebi's own moves come back here too, and find the window already there.) + if let Some((m_idx, w_idx)) = self.known_window_ids.get(&window_id).cloned() + && w_idx != idx + { + tracing::info!("window {window_id} was moved to workspace {idx}"); + let offset = self.work_area_offset; + + if let Some(monitor) = self.monitors_mut().get_mut(m_idx) { + monitor.ensure_workspace_count(idx + 1); + + if let Some(from) = monitor.workspaces_mut().get_mut(w_idx) { + from.remove_window(window_id)?; + } + + if let Some(to) = monitor.workspaces_mut().get_mut(idx) { + to.new_container_for_window(&window)?; + } + + // whichever of the two is showing needs its tiles redone + monitor.update_focused_workspace(offset)?; + } + } } WindowManagerEvent::Show(_, _) | WindowManagerEvent::Manage(_) => { let mut create = true; @@ -335,6 +385,17 @@ impl WindowManager { } } + // a window that was just managed is on the desktop the compositor opened it on, which is the + // one in front where it opened; make sure that is the workspace it was managed into + if matches!( + event, + WindowManagerEvent::Show(_, _) | WindowManagerEvent::Manage(_) + ) { + for monitor in self.monitors() { + monitor.assign_windows_to_workspaces(); + } + } + self.update_known_window_ids(); notify_subscribers( diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 9ab5f355..cb549330 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -14,6 +14,12 @@ //! [`WindowManager::move_container_in_cycle_direction`]), and stops the daemon when it is asked //! to ([`WindowManager::stop`]). //! +//! A monitor's workspaces are the compositor's virtual desktops. The window manager shows one +//! ([`WindowManager::focus_workspace`]), moves a container to one +//! ([`WindowManager::move_container_to_workspace`]), makes sure the compositor has a desktop for +//! each ([`WindowManager::sync_workspace_desktops`]), and follows a workspace switch that +//! something else made ([`WindowManager::adopt_workspace_change`]). +//! //! [`listen_for_commands`]: crate::process_command::listen_for_commands use crate::DATA_DIR; @@ -136,11 +142,13 @@ impl WindowManager { } /// Loads the monitors and the windows that are already open from the backend - /// ([`desktop`]) + /// ([`desktop`]), and makes sure the compositor has a desktop for every workspace + /// ([`WindowManager::sync_workspace_desktops`]) #[tracing::instrument(skip(self))] pub fn init(&mut self) -> Result<(), LibraryError> { tracing::info!("initializing"); desktop::load_monitor_information(self)?; + self.sync_workspace_desktops(); desktop::load_workspace_information(self)?; // the windows that were open already are in containers now; an event about one of them // (the first thing to happen may be that it closes) has to find it @@ -422,6 +430,55 @@ impl WindowManager { std::process::exit(0) } + /// Shows workspace `idx` on the focused monitor, creating it (and the ones before it) if it + /// does not exist yet. + /// + /// The compositor is asked to show the workspace's desktop on that monitor + /// ([`Monitor::load_focused_workspace`]): it shows the windows on it and hides the others, and + /// komorebi focuses the workspace's focused window and tiles it. + #[tracing::instrument(skip(self))] + pub fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("focusing workspace"); + + let mouse_follows_focus = self.mouse_follows_focus; + let monitor = self + .focused_monitor_mut() + .ok_or_eyre("there is no workspace")?; + + monitor.focus_workspace(idx)?; + monitor.load_focused_workspace(mouse_follows_focus)?; + + self.update_focused_workspace(false, true) + } + + /// Moves the focused container of the focused monitor to workspace `idx`, creating it if it + /// does not exist yet, and shows that workspace when `follow` is set. + /// + /// The container's windows are put on the workspace's desktop before the desktop is shown or + /// one of them is focused ([`Monitor::load_focused_workspace`]): a window that is focused while + /// it is still on the desktop it came from takes the monitor back to that desktop. + #[tracing::instrument(skip(self))] + pub fn move_container_to_workspace( + &mut self, + idx: usize, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + tracing::info!("moving container"); + + let mouse_follows_focus = self.mouse_follows_focus; + let monitor = self + .focused_monitor_mut() + .ok_or_eyre("there is no monitor")?; + + monitor.move_container_to_workspace(idx, follow, direction)?; + monitor.load_focused_workspace(mouse_follows_focus)?; + + self.update_focused_workspace(mouse_follows_focus, true)?; + + Ok(()) + } + /// Takes the window that has the focus in the compositor out of the layout of the focused /// workspace, or puts it back when it is one of its floating windows and `force_float` is not /// set, and tiles the workspace again @@ -990,6 +1047,48 @@ impl WindowManager { Ok(()) } + /// Make sure the compositor has a virtual desktop for every workspace any monitor has, named + /// "Workspace 1", "Workspace 2" and so on where it has to create them + pub fn sync_workspace_desktops(&self) { + let count = self + .monitors() + .iter() + .map(|m| m.workspaces().len()) + .max() + .unwrap_or(1) + .max(1); + + let names: Vec = (0..count).map(|i| format!("Workspace {}", i + 1)).collect(); + + if let Err(error) = backend().ensure_workspaces(&names) { + tracing::warn!("could not make sure there are desktops for the workspaces: {error}"); + } + } + + /// A monitor now shows workspace `idx`, which komorebi did not ask for: a pager, a shortcut, an + /// app raising a window of another desktop. The compositor has already shown the windows and + /// chosen what to focus; komorebi follows, and tiles what came into view. + pub fn adopt_workspace_change(&mut self, monitor_id: u32, idx: usize) -> eyre::Result<()> { + let offset = self.work_area_offset; + + let Some(monitor) = self.monitors_mut().iter_mut().find(|m| m.id == monitor_id) else { + return Ok(()); + }; + + if monitor.focused_workspace_idx() == idx { + // komorebi's own switch, coming back + return Ok(()); + } + + tracing::info!("the compositor now shows workspace {idx} on monitor {monitor_id}"); + monitor.focus_workspace(idx)?; + monitor.update_focused_workspace(offset)?; + + self.update_known_window_ids(); + + Ok(()) + } + pub fn update_known_window_ids(&mut self) { tracing::trace!("updating list of known window_ids"); let mut known_window_ids = HashMap::new(); @@ -1223,6 +1322,50 @@ mod tests { let (_wm, _test_context) = setup_window_manager(); } + #[test] + fn test_focus_workspace() { + let (mut wm, _test_context) = setup_window_manager(); + + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // a new monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // the next index on the monitor should be the not-yet-created second workspace + let new_workspace_index = m.new_workspace_idx(); + assert_eq!(new_workspace_index, 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + + { + // focusing a workspace which doesn't yet exist should create it + let monitor = wm.focused_monitor_mut().unwrap(); + monitor.focus_workspace(new_workspace_index).unwrap(); + assert_eq!(monitor.workspaces().len(), 2); + } + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + + { + // focusing a workspace many indices ahead should create all workspaces + // required along the way + let monitor = wm.focused_monitor_mut().unwrap(); + monitor.focus_workspace(new_workspace_index + 2).unwrap(); + assert_eq!(monitor.workspaces().len(), 4); + } + assert_eq!(wm.focused_workspace_idx().unwrap(), 3); + + // we should be able to successfully focus an existing workspace too + wm.focus_workspace(0).unwrap(); + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + } + #[test] fn test_focus_container_in_cycle_direction() { let (mut wm, _test_context) = setup_window_manager(); diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index 314462a5..71470ce0 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -2,11 +2,12 @@ //! window manager handles it //! ([`WindowManager::process_event`](crate::window_manager::WindowManager::process_event)). //! -//! An event is about one window and carries it, and the compositor signal it came from -//! ([`SystemNotification`]), which is only for logging. Two events come from komorebi itself -//! rather than from the compositor: [`WindowManagerEvent::Manage`] and -//! [`WindowManagerEvent::Unmanage`], which the commands that manage and unmanage the focused window -//! raise. +//! An event carries the compositor signal it came from ([`SystemNotification`]), which is only for +//! logging. Every event but one is about a window, and carries it: a +//! [`WindowManagerEvent::WorkspaceChange`] is about a monitor that shows another workspace. Two +//! events come from komorebi itself rather than from the compositor: +//! [`WindowManagerEvent::Manage`] and [`WindowManagerEvent::Unmanage`], which the commands that +//! manage and unmanage the focused window raise. use crate::window::Window; use serde::Deserialize; @@ -32,6 +33,10 @@ pub enum KWinNotification { WindowRemoved, /// `workspace.windowActivated` WindowActivated, + /// `workspace.currentDesktopChanged`: a monitor now shows another desktop + WorkspaceChanged, + /// `window.desktopsChanged`: a window is on another desktop + WindowMovedToDesktop, /// `window.minimizedChanged` to true WindowMinimized, /// `window.minimizedChanged` to false @@ -48,7 +53,7 @@ pub enum ManualNotification { Unmanage, } -/// Window events: each carries the window it is about. +/// Window events: each carries the window it is about, but for a workspace change. #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(tag = "type", content = "content")] @@ -64,6 +69,12 @@ pub enum WindowManagerEvent { Manage(Window), /// The user asked komorebi to stop managing the window (`UnmanageFocusedWindow`) Unmanage(Window), + /// A monitor (by id) now shows another workspace: komorebi did that itself, or a pager, a + /// shortcut or an app raising a window did. Not about any one window. + WorkspaceChange(SystemNotification, u32, usize), + /// A window was put on another workspace's desktop by something other than komorebi (the + /// window menu's "Move to Desktop", a drag in the pager) + WorkspaceMove(SystemNotification, Window, usize), } impl WindowManagerEvent { @@ -77,7 +88,9 @@ impl WindowManagerEvent { | WindowManagerEvent::Restore(_, window) | WindowManagerEvent::TitleUpdate(_, window) | WindowManagerEvent::Manage(window) - | WindowManagerEvent::Unmanage(window) => *window, + | WindowManagerEvent::Unmanage(window) + | WindowManagerEvent::WorkspaceMove(_, window, _) => *window, + WindowManagerEvent::WorkspaceChange(..) => return None, }) } @@ -97,7 +110,9 @@ impl WindowManagerEvent { | WindowManagerEvent::Destroy(n, _) | WindowManagerEvent::Minimize(n, _) | WindowManagerEvent::Restore(n, _) - | WindowManagerEvent::TitleUpdate(n, _) => match n { + | WindowManagerEvent::TitleUpdate(n, _) + | WindowManagerEvent::WorkspaceChange(n, _, _) + | WindowManagerEvent::WorkspaceMove(n, _, _) => match n { SystemNotification::KWin(k) => k.to_string(), SystemNotification::Manual(m) => m.to_string(), }, @@ -125,4 +140,17 @@ mod tests { assert_eq!(event.notification(), "WindowMinimized"); assert_eq!(event.to_string(), "Minimize"); } + + #[test] + fn a_workspace_change_is_about_a_monitor_and_no_window() { + let event = WindowManagerEvent::WorkspaceChange( + SystemNotification::KWin(KWinNotification::WorkspaceChanged), + 7, + 2, + ); + + assert_eq!(event.window(), None); + assert_eq!(event.window_id(), None); + assert_eq!(event.notification(), "WorkspaceChanged"); + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index edc3e7bc..4233e559 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -388,6 +388,36 @@ impl Workspace { false } + /// Gives the focus to the window of this workspace that had it: the focused window of the + /// focused container, or the focused floating window when there is no container. + /// + /// The compositor shows a workspace's windows by itself when the workspace's desktop is shown; + /// this is what komorebi does after it has asked for that. + pub fn restore(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> { + let idx = self.focused_container_idx(); + let mut to_focus = None; + + for (i, container) in self.containers().iter().enumerate() { + if let Some(window) = container.focused_window() + && idx == i + { + to_focus = Option::from(*window); + } + } + + if let Some(container) = self.focused_container_mut() { + container.focus_window(container.focused_window_idx()); + } + + if let Some(window) = to_focus { + window.focus(mouse_follows_focus)?; + } else if let Some(floating_window) = self.focused_floating_window() { + floating_window.focus(mouse_follows_focus)?; + } + + Ok(()) + } + pub fn remove_focused_container(&mut self) -> Option { let focused_idx = self.focused_container_idx(); let container = self.remove_container_by_idx(focused_idx); diff --git a/komorebi/tests/workspaces.rs b/komorebi/tests/workspaces.rs new file mode 100644 index 00000000..98298c39 --- /dev/null +++ b/komorebi/tests/workspaces.rs @@ -0,0 +1,361 @@ +//! Workspaces as the compositor's virtual desktops, against an in-memory desktop. +//! +//! Workspace `i` is the compositor's desktop `i` on each monitor. komorebi asks the compositor to +//! show a workspace and to put a window on one. It follows a switch or a move that something else +//! made without undoing it, and does nothing when the compositor reports what komorebi did itself. +//! +//! Window ids are in the 10_000s and unique per test. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn removed(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Destroy( + SystemNotification::KWin(KWinNotification::WindowRemoved), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel) +fn desktop() -> (Arc, WindowManager) { + desktop_on(FakeBackend::with_one_monitor()) +} + +fn desktop_on(fake: FakeBackend) -> (Arc, WindowManager) { + let fake = Arc::new(fake); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmb-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +fn open(fake: &FakeBackend, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); +} + +#[test] +fn a_destroyed_window_is_removed_from_a_workspace_that_is_not_in_front() { + let (fake, mut wm) = desktop(); + open(&fake, 10_031); + open(&fake, 10_032); + + with_backend(fake.clone(), || { + wm.process_event(added(10_031))?; + wm.process_event(added(10_032))?; + // send the focused window (10_032) to workspace 1 and stay on workspace 0 + wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new())?; + assert!(wm.known_window_ids.contains_key(&10_032)); + + fake.close_window_now(10_032); + wm.process_event(removed(10_032)) + }) + .unwrap(); + + assert!(!wm.known_window_ids.contains_key(&10_032)); + assert!(wm.known_window_ids.contains_key(&10_031)); +} + +fn activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +fn workspace_changed(monitor_id: u32, idx: usize) -> WindowManagerEvent { + WindowManagerEvent::WorkspaceChange( + SystemNotification::KWin(KWinNotification::WorkspaceChanged), + monitor_id, + idx, + ) +} + +const MONITOR: u32 = 1; + +#[test] +fn switching_workspace_asks_the_compositor_to_show_the_other_desktop() { + let (fake, mut wm) = desktop(); + open(&fake, 10_061); + open(&fake, 10_062); + + with_backend(fake.clone(), || { + wm.process_event(added(10_061))?; + wm.process_event(added(10_062))?; + wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new())?; + fake.clear_commands(); + wm.process_command(SocketMessage::FocusWorkspaceNumber(1), Vec::new()) + }) + .unwrap(); + + assert_eq!(fake.shown_workspace(MONITOR), 1); + assert!( + fake.commands() + .iter() + .any(|c| matches!(c, Command::SwitchWorkspace(MONITOR, 1))), + "{:?}", + fake.commands() + ); + // the compositor shows the windows of the workspace in front and not the others; komorebi + // hides nothing + assert!( + fake.on_screen(10_062), + "the window on workspace 1 is not shown" + ); + assert!( + !fake.on_screen(10_061), + "the window on workspace 0 is still shown" + ); +} + +#[test] +fn a_window_sent_to_another_workspace_is_put_on_that_desktop() { + let (fake, mut wm) = desktop(); + open(&fake, 10_071); + open(&fake, 10_072); + + with_backend(fake.clone(), || { + wm.process_event(added(10_071))?; + wm.process_event(added(10_072))?; + wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new()) + }) + .unwrap(); + + assert_eq!(fake.workspace_of(10_071), Some(0)); + assert_eq!(fake.workspace_of(10_072), Some(1)); + assert_eq!( + wm.focused_workspace_idx().unwrap(), + 0, + "send does not follow" + ); + assert!(!fake.on_screen(10_072)); +} + +#[test] +fn moving_a_window_to_another_workspace_puts_it_on_the_desktop_before_showing_it() { + // focusing a window that is not yet on the desktop being shown would take the monitor back + let (fake, mut wm) = desktop(); + open(&fake, 10_081); + open(&fake, 10_082); + + with_backend(fake.clone(), || { + wm.process_event(added(10_081))?; + wm.process_event(added(10_082))?; + fake.clear_commands(); + wm.process_command(SocketMessage::MoveContainerToWorkspaceNumber(1), Vec::new()) + }) + .unwrap(); + + let commands = fake.commands(); + let assigned = commands + .iter() + .position(|c| matches!(c, Command::SetWindowWorkspace(10_082, 1))) + .expect("the window was never put on workspace 1's desktop"); + let switched = commands + .iter() + .position(|c| matches!(c, Command::SwitchWorkspace(MONITOR, 1))) + .expect("the monitor was never switched"); + let focused = commands + .iter() + .position(|c| matches!(c, Command::Focus(10_082, _))) + .expect("the moved window was never focused"); + + assert!(assigned < switched, "{commands:?}"); + assert!(assigned < focused, "{commands:?}"); + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert!(fake.on_screen(10_082)); +} + +#[test] +fn a_workspace_switch_by_someone_else_is_followed_not_undone() { + let (fake, mut wm) = desktop(); + open(&fake, 10_091); + open(&fake, 10_092); + + with_backend(fake.clone(), || { + wm.process_event(added(10_091))?; + wm.process_event(added(10_092))?; + wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new()) + }) + .unwrap(); + + // a pager, a shortcut, or an app raising a window of workspace 1: the compositor shows it + fake.show_workspace_by_user(MONITOR, 1); + fake.clear_commands(); + with_backend(fake.clone(), || { + wm.process_event(workspace_changed(MONITOR, 1)) + }) + .unwrap(); + + assert_eq!( + wm.focused_workspace_idx().unwrap(), + 1, + "komorebi did not follow" + ); + assert!( + !fake + .commands() + .iter() + .any(|c| matches!(c, Command::SwitchWorkspace(..))), + "komorebi asked for a switch in reply to one: {:?}", + fake.commands() + ); + assert_eq!(fake.shown_workspace(MONITOR), 1); +} + +#[test] +fn the_compositor_reporting_komorebis_own_switch_changes_nothing() { + let (fake, mut wm) = desktop(); + open(&fake, 10_101); + + with_backend(fake.clone(), || { + wm.process_event(added(10_101))?; + wm.process_command(SocketMessage::FocusWorkspaceNumber(1), Vec::new())?; + fake.clear_commands(); + wm.process_event(workspace_changed(MONITOR, 1)) + }) + .unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); +} + +#[test] +fn a_window_open_on_a_desktop_at_startup_starts_on_that_workspace() { + let fake = FakeBackend::with_one_monitor(); + fake.open_window(10_111, "foot", "foot", "terminal 10111"); + fake.open_window(10_112, "foot", "foot", "terminal 10112"); + // the user had put one on the second desktop, and was looking at the first + fake.show_workspace_by_user(MONITOR, 0); + { + use komorebi::backend::Backend; + fake.set_window_workspace(10_112, 1).unwrap(); + fake.clear_commands(); + } + let (_fake, wm) = desktop_on(fake); + + let workspaces = wm.focused_monitor().unwrap().workspaces(); + let ids = |idx: usize| -> Vec { + workspaces + .get(idx) + .map(|w| { + w.containers() + .iter() + .flat_map(|c| c.windows().iter().map(|w| w.id)) + .collect() + }) + .unwrap_or_default() + }; + assert_eq!(ids(0), [10_111]); + assert_eq!(ids(1), [10_112]); +} + +#[test] +fn focus_going_to_a_window_on_the_workspace_in_front_changes_nothing() { + let (fake, mut wm) = desktop(); + open(&fake, 10_411); + open(&fake, 10_412); + + with_backend(fake.clone(), || { + wm.process_event(added(10_411))?; + wm.process_event(added(10_412))?; + fake.clear_commands(); + wm.process_event(activated(10_411)) + }) + .unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + assert!(fake.on_screen(10_411) && fake.on_screen(10_412)); +} + +fn moved_to_desktop(id: u32, idx: usize) -> WindowManagerEvent { + WindowManagerEvent::WorkspaceMove( + SystemNotification::KWin(KWinNotification::WindowMovedToDesktop), + Window::from(id), + idx, + ) +} + +#[test] +fn a_window_moved_to_another_desktop_by_someone_else_changes_workspace() { + let (fake, mut wm) = desktop(); + open(&fake, 10_501); + open(&fake, 10_502); + + with_backend(fake.clone(), || { + wm.process_event(added(10_501))?; + wm.process_event(added(10_502))?; + // "Move to Desktop 2" in the window menu + wm.process_event(moved_to_desktop(10_502, 1)) + }) + .unwrap(); + + let ids = |idx: usize| -> Vec { + wm.focused_monitor() + .unwrap() + .workspaces() + .get(idx) + .map(|w| { + w.containers() + .iter() + .flat_map(|c| c.windows().iter().map(|w| w.id)) + .collect() + }) + .unwrap_or_default() + }; + assert_eq!(ids(0), [10_501]); + assert_eq!(ids(1), [10_502]); + + // the tile left behind was given to the other window + let remaining = fake.rect_of(10_501).unwrap(); + assert!(remaining.right > 1500, "{remaining:?}"); +} + +#[test] +fn komorebis_own_move_coming_back_as_an_event_moves_nothing() { + let (fake, mut wm) = desktop(); + open(&fake, 10_511); + open(&fake, 10_512); + + with_backend(fake.clone(), || { + wm.process_event(added(10_511))?; + wm.process_event(added(10_512))?; + wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new())?; + fake.clear_commands(); + wm.process_event(moved_to_desktop(10_512, 1)) + }) + .unwrap(); + + assert!( + fake.commands().is_empty(), + "an event about komorebi's own move caused commands: {:?}", + fake.commands() + ); + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index b4b733b9..e030edbc 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -30,6 +30,9 @@ //! - `resize-edge` and `resize-axis` resize the focused window by the `resize-delta`, and //! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of //! the tiles of the focused workspace and load them back. +//! - `focus-workspace` shows another workspace of the focused monitor, `move-to-workspace` moves +//! the focused window to a workspace and shows it, and `send-to-workspace` moves it there and +//! stays. A workspace is KWin's virtual desktop of the same number, counted from 0. //! //! `ignore-rule` and `manage-rule` add a rule that keeps an application out of the layout or //! always in it, `session-float-rule` floats the focused window and every window like it until the @@ -120,6 +123,25 @@ gen_enum_subcommand_args! { PromoteWindow: OperationDirection, } +macro_rules! gen_target_subcommand_args { + // SubCommand Pattern + ( $( $name:ident ),+ $(,)? ) => { + $( + #[derive(clap::Parser)] + pub struct $name { + /// Target index (zero-indexed) + target: usize, + } + )+ + }; +} + +gen_target_subcommand_args! { + MoveToWorkspace, + SendToWorkspace, + FocusWorkspace, +} + macro_rules! gen_focused_workspace_padding_subcommand_args { // SubCommand Pattern ( $( $name:ident ),+ $(,)? ) => { @@ -426,6 +448,15 @@ enum SubCommand { /// Resize the focused window or primary column along the specified axis #[clap(arg_required_else_help = true)] ResizeAxis(ResizeAxis), + /// Move the focused window to the specified workspace + #[clap(arg_required_else_help = true)] + MoveToWorkspace(MoveToWorkspace), + /// Send the focused window to the specified workspace + #[clap(arg_required_else_help = true)] + SendToWorkspace(SendToWorkspace), + /// Focus the specified workspace on the focused monitor + #[clap(arg_required_else_help = true)] + FocusWorkspace(FocusWorkspace), /// Set the resize delta (used by resize-edge and resize-axis) #[clap(arg_required_else_help = true)] ResizeDelta(ResizeDelta), @@ -669,6 +700,9 @@ fn main() -> eyre::Result<()> { SubCommand::FlipLayout(args) => { send_message(&SocketMessage::FlipLayout(args.axis))?; } + SubCommand::FocusWorkspace(args) => { + send_message(&SocketMessage::FocusWorkspaceNumber(args.target))?; + } SubCommand::ToggleFloat => { send_message(&SocketMessage::ToggleFloat)?; } @@ -678,6 +712,12 @@ fn main() -> eyre::Result<()> { SubCommand::ResizeAxis(args) => { send_message(&SocketMessage::ResizeWindowAxis(args.axis, args.sizing))?; } + SubCommand::MoveToWorkspace(args) => { + send_message(&SocketMessage::MoveContainerToWorkspaceNumber(args.target))?; + } + SubCommand::SendToWorkspace(args) => { + send_message(&SocketMessage::SendContainerToWorkspaceNumber(args.target))?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index bcd145a6..414670d2 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -424,6 +424,22 @@ fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { ); } +#[test] +fn the_workspace_subcommands_send_the_index_they_are_given() { + sends( + &["focus-workspace", "1"], + r#"{"type":"FocusWorkspaceNumber","content":1}"#, + ); + sends( + &["move-to-workspace", "2"], + r#"{"type":"MoveContainerToWorkspaceNumber","content":2}"#, + ); + sends( + &["send-to-workspace", "0"], + r#"{"type":"SendContainerToWorkspaceNumber","content":0}"#, + ); +} + #[test] fn without_a_daemon_a_question_fails() { let runtime = Runtime::new(); @@ -476,6 +492,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "cycle-move.md", "data-directory.md", "flip-layout.md", + "focus-workspace.md", "focus.md", "focused-workspace-container-padding.md", "focused-workspace-padding.md", @@ -491,6 +508,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "monitor-information.md", "monitor-work-area-offset.md", "mouse-follows-focus.md", + "move-to-workspace.md", "move.md", "preselect-direction.md", "promote-focus.md", @@ -506,6 +524,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "retile.md", "save-resize.md", "scrolling-layout-columns.md", + "send-to-workspace.md", "session-float-rule.md", "session-float-rules.md", "start.md", diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index be3a9f55..6ff66d17 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -397,6 +397,83 @@ class Kde: self.machine.screenshot(name) return Image.open(self.machine.out_dir / f"{name}.png").convert("RGB") + def desk(self, wid: str) -> int: + """The number of the virtual desktop the window is on, counted from 1 as kdotool counts. + + 0 when kdotool cannot say (a window on every desktop, a window that is gone). + """ + lines = self.run(f"kdotool get_desktop_for_window {shlex.quote(wid)}")[1].split() + return int(lines[-1]) if lines and lines[-1].isdigit() else 0 + + def shown(self) -> int: + """The number of the virtual desktop KWin shows, counted from 1. + + With per-output virtual desktops, that is the desktop of the output KWin considers + active; a suite with one output has no other. + """ + lines = self.run("kdotool get_desktop")[1].split() + return int(lines[-1]) if lines and lines[-1].isdigit() else 0 + + def desktops(self) -> int: + """The number of virtual desktops KWin has.""" + out = self.run( + "busctl --user get-property org.kde.KWin /VirtualDesktopManager" + " org.kde.KWin.VirtualDesktopManager count" + )[1].split() + return int(out[-1]) if out and out[-1].isdigit() else 0 + + def kwinrc(self, group: str, key: str) -> str | None: + """The value of `key` in `[group]` of the user's `kwinrc`, or None when it is not set.""" + status, text = self.machine.execute(f"cat /home/{self.user}/.config/kwinrc") + if status != 0: + return None + current = None + for line in text.splitlines(): + line = line.strip() + if line.startswith("[") and line.endswith("]"): + current = line[1:-1] + elif current == group and "=" in line: + name, value = line.split("=", 1) + if name.strip() == key: + return value.strip() + return None + + def kwin_script(self, name: str, source: str, *, keep: bool = False) -> list[str]: + """Runs `source` as the KWin script `name` and returns the lines it reported. + + The script reports with `report(...)`, which writes its arguments to KWin's log as one + line marked with `name`, and ends with `report("done")`, which the lines are waited for. + The script is unloaded afterwards, unless `keep` is set: a script that connects to a + signal goes on reporting, and [`Kde.kwin_reports`][] reads what it reported since. + """ + path = f"/tmp/kwin-script-{name}.js" + prelude = ( + "function report() { print(" + + json.dumps(f"KS:{name} ") + + " + Array.prototype.slice.call(arguments).join(' ')); }\n" + ) + self.as_user(f"printf %s {shlex.quote(prelude + source)} > {path}") + reply = self.sh( + "busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting loadScript ss" + f" {path} {shlex.quote(name)}" + ).split() + script = f"/Scripting/Script{reply[-1]}" + self.sh(f"busctl --user call org.kde.KWin {script} org.kde.kwin.Script run") + if not self.wait_for(lambda: "done" in self.kwin_reports(name)): + raise AssertionError(f"the KWin script {name} never reported it was done") + if not keep: + self.sh( + "busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting unloadScript s" + f" {shlex.quote(name)}" + ) + return [line for line in self.kwin_reports(name) if line != "done"] + + def kwin_reports(self, name: str) -> list[str]: + """Every line the KWin script `name` has reported so far ([`Kde.kwin_script`][]).""" + log = self.machine.execute(f"journalctl _UID={self.uid} --no-pager -o cat")[1] + mark = f"KS:{name} " + return [line.split(mark, 1)[1] for line in log.splitlines() if mark in line] + def outputs(self) -> int: """The number of outputs KWin has enabled.""" return int(self.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'")) diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index 22195438..3d99aad8 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -431,3 +431,75 @@ def test_focused_title_is_empty_for_a_workspace_without_containers(machine: Fake machine.reply("komorebic state", output=a_state(workspace())) assert Kde(machine, "main").focused_title() == "" + + +def test_desk_is_the_desktop_number_kdotool_prints_or_zero(machine: FakeMachine) -> None: + machine.reply("{a}", output="2\n") + machine.reply("{b}", status=1, output="no such window") + kde = Kde(machine, "main") + + assert kde.desk("{a}") == 2 + assert kde.desk("{b}") == 0 + + +def test_shown_and_desktops_ask_kwin(machine: FakeMachine) -> None: + machine.reply("kdotool get_desktop", output="3\n") + machine.reply("VirtualDesktopManager count", output="u 4\n") + kde = Kde(machine, "main") + + assert kde.shown() == 3 + assert kde.desktops() == 4 + + +def test_kwinrc_reads_a_key_of_its_own_group(machine: FakeMachine) -> None: + machine.reply( + "cat /home/komorebi/.config/kwinrc", + output=( + "[Desktops]\nPerOutputVirtualDesktops=false\n" + "[Windows]\nPerOutputVirtualDesktops = true\n" + ), + ) + kde = Kde(machine, "main") + + assert kde.kwinrc("Windows", "PerOutputVirtualDesktops") == "true" + assert kde.kwinrc("Windows", "FocusPolicy") is None + + +def test_kwinrc_is_none_without_a_file(machine: FakeMachine) -> None: + machine.reply("cat /home/komorebi/.config/kwinrc", status=1) + + assert Kde(machine, "main").kwinrc("Windows", "PerOutputVirtualDesktops") is None + + +def test_a_kwin_script_is_loaded_run_and_unloaded_and_its_reports_returned( + machine: FakeMachine, +) -> None: + machine.reply("loadScript", output="i 7\n") + machine.reply("journalctl", output="other\nKS:probe 2 outputs\nkwin: KS:probe done\n") + kde = Kde(machine, "main", scale=0.01) + + lines = kde.kwin_script("probe", 'report(workspace.screens.length, "outputs"); report("done");') + + assert lines == ["2 outputs"] + scripts = [inner(command) for command in machine.commands if " sh -c " in command] + assert any("/tmp/kwin-script-probe.js" in s and "function report()" in s for s in scripts) + assert any("/Scripting/Script7 org.kde.kwin.Script run" in s for s in scripts) + assert any("unloadScript s probe" in s for s in scripts) + + +def test_a_kwin_script_that_is_kept_stays_loaded(machine: FakeMachine) -> None: + machine.reply("loadScript", output="i 8\n") + machine.reply("journalctl", output="KS:listen done\n") + kde = Kde(machine, "main", scale=0.01) + + kde.kwin_script("listen", 'report("done");', keep=True) + + assert not any("unloadScript" in command for command in machine.commands) + + +def test_a_kwin_script_that_never_reports_it_is_done_fails_the_test(machine: FakeMachine) -> None: + machine.reply("loadScript", output="i 9\n") + kde = Kde(machine, "main", scale=0.01) + + with pytest.raises(AssertionError, match="never reported"): + kde.kwin_script("silent", "") diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index b5f06ba5..f13df547 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -192,6 +192,12 @@ toggle-tiling toggle-tiling toggle-pause toggle-pause +focus-workspace 1 +focus-workspace 0 +send-to-workspace 1 +focus-workspace 1 +move-to-workspace 0 +focus-workspace 0 global-work-area-offset 10 10 20 20 global-work-area-offset 0 0 0 0 monitor-work-area-offset 0 10 10 20 20 diff --git a/nix/tests/vm/suites/kwin-contract/default.nix b/nix/tests/vm/suites/kwin-contract/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/kwin-contract/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/kwin-contract/test.py b/nix/tests/vm/suites/kwin-contract/test.py new file mode 100644 index 00000000..41dd626e --- /dev/null +++ b/nix/tests/vm/suites/kwin-contract/test.py @@ -0,0 +1,172 @@ +# The contract of KWin's per-output virtual desktops that komorebi's workspaces rely on, checked +# against a headless KWin with two outputs and no komorebi: workspace `i` is desktop `i`, and each +# output shows a desktop of its own. What has to hold, and what breaks if it does not: +# +# - with `[Windows] PerOutputVirtualDesktops=true` in kwinrc, a script can show a desktop on one +# output and the other output keeps its own (otherwise a workspace switch switches every monitor); +# - KWin says so with `workspace.currentDesktopChanged`, which the bridge listens to; +# - KWin focuses a window of the desktop it switched an output to, by itself (komorebi asks for no +# focus after a switch it did not make); +# - activating a window on another desktop of its output (an app raising itself) makes KWin switch +# that output to the window's desktop (which komorebi then follows); +# - a window moved by a script so that its middle is on the other output keeps its desktops: KWin +# moves a window to the new output's desktop only during an interactive move; +# - a window put on another desktop from outside raises `desktopsChanged` on the window, which the +# bridge listens to. +# +# docs/dev/PLATFORM.md records these as the facts of KWin that komorebi depends on. +from itertools import count + +from komorebi_vm import Checks, Kde + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +# per-output desktops are read when KWin starts, as komorebi's users have them after their first run +machine.succeed( + "runuser -u komorebi -- sh -c 'mkdir -p ~/.config" + ' && printf "[Windows]\\nPerOutputVirtualDesktops=true\\n" > ~/.config/kwinrc\'' +) +kde = Kde.headless(machine, "main", size=(1920, 1080), outputs=2, scale=SCALE) + +# what every script is given: the desktop each output shows, and a window by its title +HELPERS = """ +function cur() { + return workspace.screens.map(function (o) { + return workspace.currentDesktopForScreen(o).name; + }).join("/"); +} +function win(title) { + return workspace.windowList().filter(function (w) { return w.caption === title; })[0]; +} +function names(ds) { + return ds.map(function (d) { return d.name; }).join(","); +} +""" + + +def script(name: str, body: str, keep: bool = False) -> list[str]: + return kde.kwin_script(name, HELPERS + body + '\nreport("done");\n', keep=keep) + + +def shows() -> str: + """What each output shows, as `first/second`.""" + lines = script(f"shows-{next(counter)}", "report(cur());") + return lines[0] if lines else "" + + +counter = count(1) + +print("== 1. two outputs, one desktop, and per-output desktops on") +outputs = script( + "outputs", 'report(workspace.screens.map(function (o) { return o.name; }).join(" "));' +) +print(f" outputs: {outputs}") +names_of = outputs[0].split() if outputs else [] +checks.check("KWin has two outputs", len(names_of) == 2) +checks.check("and one desktop", kde.desktops() == 1) +checks.check( + "kwinrc has per-output desktops on", + kde.kwinrc("Windows", "PerOutputVirtualDesktops") == "true", +) + +print("== 2. a desktop created over D-Bus is a desktop of every output") +kde.sh( + "busctl --user call org.kde.KWin /VirtualDesktopManager" + " org.kde.KWin.VirtualDesktopManager createDesktop us 1 two > /dev/null" +) +checks.check("KWin has two desktops", kde.wait_for(lambda: kde.desktops() == 2)) +desktops = script("desktops", "report(names(workspace.desktops));") +checks.check(f"the script sees them in order: {desktops}", desktops[-1:] == ["Desktop 1,two"]) +checks.check("both outputs show the first", shows() == "Desktop 1/Desktop 1") + +print("== 3. one output shows another desktop, and the other keeps its own") +script( + "listen", + 'workspace.currentDesktopChanged.connect(function () { report("changed", cur()); });', + keep=True, +) +script( + "switch", "workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);" +) +checks.check( + "the first output shows the second desktop, and the second output the first", + kde.wait_for(lambda: shows() == "two/Desktop 1"), +) +checks.check( + "KWin said so with currentDesktopChanged", + kde.wait_for(lambda: "changed two/Desktop 1" in kde.kwin_reports("listen")), +) +script("back", "workspace.setCurrentDesktopForScreen(workspace.desktops[0], workspace.screens[0]);") +checks.check("and back", kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1")) + +print("== 4. KWin focuses a window of the desktop it switched an output to") +for title in ["w1", "w2"]: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30) +script( + "place", + """ +var d = workspace.desktops; +var w1 = win("w1"), w2 = win("w2"); +w1.desktops = [d[0]]; +w1.frameGeometry = { x: 100, y: 100, width: 600, height: 400 }; +w2.desktops = [d[1]]; +w2.frameGeometry = { x: 800, y: 100, width: 600, height: 400 }; +workspace.activeWindow = w1; +""", +) +checks.check( + "w1 has the focus, on the first desktop", + kde.wait_for(lambda: kde.title(kde.active()) == "w1"), +) +script( + "to-two", "workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);" +) +checks.check( + "after the first output shows the second desktop, w2, which is on it, has the focus", + kde.wait_for(lambda: kde.active() != "" and kde.title(kde.active()) == "w2"), +) + +print("== 5. activating a window on another desktop of its output switches that output to it") +script("raise", 'workspace.activeWindow = win("w1");') +checks.check( + "the first output shows the first desktop again", + kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1"), +) +checks.check("and w1 has the focus", kde.wait_for(lambda: kde.title(kde.active()) == "w1")) + +print("== 6. a window a script moves onto the other output keeps its desktops") +script("cross", 'win("w1").frameGeometry = { x: 2300, y: 100, width: 600, height: 400 };') + + +def where_w1() -> str: + lines = script( + f"where-{next(counter)}", + 'var w = win("w1"); report(w.output.name + " " + names(w.desktops));', + ) + return lines[0] if lines else "" + + +second = names_of[1] if len(names_of) == 2 else "?" +checks.check( + f"w1 is on {second} now, and still on the first desktop only", + kde.wait_for(lambda: where_w1() == f"{second} Desktop 1"), +) + +print("== 7. a window put on another desktop from outside says so") +script( + "watch", + 'var w = win("w1"); w.desktopsChanged.connect(function () { report("moved", names(w.desktops)); });', + keep=True, +) +kde.sh(f"kdotool set_desktop_for_window {kde.wid('w1')} 2") +checks.check( + "w1's desktopsChanged was raised, with the second desktop", + kde.wait_for(lambda: "moved two" in kde.kwin_reports("watch")), +) + +kde.stop() +checks.finish() diff --git a/nix/tests/vm/suites/workspace-switch/default.nix b/nix/tests/vm/suites/workspace-switch/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/workspace-switch/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/workspace-switch/test.py b/nix/tests/vm/suites/workspace-switch/test.py new file mode 100644 index 00000000..6cdcda31 --- /dev/null +++ b/nix/tests/vm/suites/workspace-switch/test.py @@ -0,0 +1,140 @@ +# komorebi's workspaces are KWin's own virtual desktops, per output. What only a real KWin can +# tell: that komorebi turns on KWin's per-output virtual desktops and puts the user's setting back +# when it stops; that `komorebic send-to-workspace` puts a window on another desktop and leaves the +# one in front showing; that `komorebic focus-workspace` has KWin show the other desktop, and KWin +# focuses the window there, which komorebi agrees with, without komorebi hiding or parking any +# window; that a switch by anything else (a shortcut, an app raising a window of another desktop) +# is followed once, with KWin and komorebi agreeing on the focused window and nothing flip-flopping; +# and that a window moved to another desktop by someone else (the window menu's "Move to Desktop") +# moves to that workspace. `komorebi/tests/workspaces.rs` checks the same against the fake. +import time + +from komorebi_vm import Checks, Kde, daemon + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(1920, 1080), scale=SCALE) + + +def focus_changes() -> int: + return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "FocusChange") + + +def ws() -> int: + """The workspace komorebi has in front on the (only) monitor.""" + return kde.state()["monitors"]["elements"][0]["workspaces"]["focused"] + + +def active_title() -> str: + active = kde.active() + return kde.title(active) if active else "" + + +def per_output() -> bool: + return kde.kwinrc("Windows", "PerOutputVirtualDesktops") == "true" + + +print("== 1. start, and three windows") +checks.check("per-output virtual desktops are off before komorebi starts", not per_output()) +kde.start_komorebi() +checks.check( + "the daemon answers komorebic", + kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=30), +) +for title in ["w1", "w2", "w3"]: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30) +checks.check("komorebi manages the three", kde.wait_for(lambda: kde.managed(0) == 3, timeout=20)) + +print("== 2. workspaces are desktops") +checks.check("komorebi turned on per-output virtual desktops in kwinrc", per_output()) +checks.check( + "all three windows are on desktop 1, which is showing", + all(kde.desk(kde.wid(t)) == 1 for t in ["w1", "w2", "w3"]) and kde.shown() == 1, +) + +print("== 3. one window goes to workspace 1 and stays there") +moved = active_title() +mid = kde.wid(moved) +kde.komorebic("send-to-workspace", "1") +checks.check( + f"{moved} is on desktop 2, and desktop 1 is still showing", + kde.wait_for(lambda: kde.desk(mid) == 2 and kde.shown() == 1 and ws() == 0), +) +checks.check( + "the other two are on workspace 0, and komorebi has the moved one on workspace 1", + kde.wait_for(lambda: kde.managed(0) == 2 and kde.managed(1) == 1), +) +stayed = [t for t in ["w1", "w2", "w3"] if t != moved] + +print("== 4. komorebic switches workspace: KWin shows the desktop, komorebi hides nothing") +kde.komorebic("focus-workspace", "1") +checks.check( + "desktop 2 is showing and komorebi agrees", + kde.wait_for(lambda: kde.shown() == 2 and ws() == 1), +) +checks.check( + "KWin focused the window of that desktop and komorebi knows it", + kde.wait_for(lambda: active_title() == moved and kde.focused_title(1) == moved), +) +checks.check( + "the windows of desktop 1 never left it", all(kde.desk(kde.wid(t)) == 1 for t in stayed) +) +checks.check("komorebi made one desktop, for workspace 1, and no other", kde.desktops() == 2) +kde.komorebic("focus-workspace", "0") +checks.check("back on desktop 1", kde.wait_for(lambda: kde.shown() == 1 and ws() == 0)) + +print("== 5. something else switches: a pager or a shortcut") +kde.sh("busctl --user call org.kde.KWin /KWin org.kde.KWin setCurrentDesktop i 2 > /dev/null") +checks.check("komorebi followed to workspace 1", kde.wait_for(lambda: ws() == 1)) +checks.check( + "and agrees with KWin on the focused window", + kde.wait_for(lambda: active_title() != "" and active_title() == kde.focused_title(1)), +) + +print("== 6. an app raises a window of another desktop") +kde.sh("busctl --user call org.kde.KWin /KWin org.kde.KWin setCurrentDesktop i 1 > /dev/null") +kde.wait_for(lambda: ws() == 0) +time.sleep(1 * SCALE) +before = focus_changes() +kde.activate(mid) +checks.check( + "KWin switched to the window's desktop and komorebi followed", + kde.wait_for(lambda: kde.shown() == 2 and ws() == 1), +) +checks.check( + f"KWin and komorebi agree on the focused window: {moved}", + kde.wait_for(lambda: active_title() == moved and kde.focused_title(1) == moved), +) +time.sleep(3 * SCALE) +after = focus_changes() +print(f" focus changes komorebi handled meanwhile: {after - before}") +checks.check( + f"nothing is flip-flopping (at most 6 focus events, got {after - before})", + after - before <= 6, +) +time.sleep(3 * SCALE) +final = focus_changes() +checks.check(f"and it stays quiet afterwards ({final - after} more)", final - after <= 1) + +print("== 7. somebody moves a window to another desktop (the window menu's Move to Desktop)") +other = kde.wid(stayed[0]) +kde.sh(f"kdotool set_desktop_for_window {other} 2") +checks.check( + "komorebi moved it to workspace 1: one window left on workspace 0, two on workspace 1", + kde.wait_for(lambda: kde.managed(0) == 1 and kde.managed(1) == 2), +) +checks.check("and left it where KWin put it", kde.desk(other) == 2) +checks.check("KWin carried out every command", "the bridge could not do" not in kde.komorebi_log()) + +print("== 8. a clean stop") +kde.komorebic("stop") +checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running())) +checks.check("per-output virtual desktops are back as they were (off)", not per_output()) +checks.check("the desktops komorebi made stay: they are the user's now", kde.desktops() == 2) + +kde.stop() +checks.finish() From 8467b03ac27018a2b4e79b412f8017b34afb7e67 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 17:43:36 -0700 Subject: [PATCH 030/255] feat(wm): named workspaces and the other workspace commands Workspace i is KWin's desktop i, and switching and moving by index came with the workspaces. What a user binds keys to besides is the rest of komorebi's workspace commands: going to the next or the previous workspace (or the next empty one), back to the last one, adding and closing workspaces, showing one index on every monitor, and setting the layout or the tiling of a workspace that need not be in front. They are made of the same two operations, showing a workspace and moving a container to one, so KWin keeps doing the showing and the hiding. A workspace gets a name, which focus-named-workspace, named-workspace-layout and named-workspace-tiling find it by on any monitor; focusing a named workspace focuses its monitor too, so focus_monitor comes with it. The name is komorebi's: naming a workspace does not rename KWin's desktop. The query focused-workspace-name answers with the name, or the index of a workspace that has none. The moves to a named workspace, and everything that addresses a monitor, are moves between monitors in the window manager and come with more than one monitor. --- README.md | 5 +- docs/cli/close-workspace.md | 10 + docs/cli/cycle-empty-workspace.md | 14 + docs/cli/cycle-move-to-workspace.md | 14 + docs/cli/cycle-send-to-workspace.md | 14 + docs/cli/cycle-workspace.md | 14 + docs/cli/ensure-named-workspaces.md | 17 ++ docs/cli/ensure-workspaces.md | 17 ++ docs/cli/focus-last-workspace.md | 10 + docs/cli/focus-named-workspace.md | 14 + docs/cli/focus-workspaces.md | 14 + docs/cli/move-to-last-workspace.md | 10 + docs/cli/named-workspace-layout.md | 26 ++ docs/cli/named-workspace-tiling.md | 17 ++ docs/cli/new-workspace.md | 10 + docs/cli/query.md | 3 +- docs/cli/send-to-last-workspace.md | 10 + docs/cli/workspace-layout.md | 29 ++ docs/cli/workspace-name.md | 20 ++ docs/cli/workspace-tiling.md | 20 ++ docs/dev/ARCHITECTURE.md | 30 +- docs/usage/workspaces.md | 68 +++++ komorebi/src/core/mod.rs | 21 ++ komorebi/src/monitor.rs | 14 + komorebi/src/process_command.rs | 226 +++++++++++++++ komorebi/src/state.rs | 3 + komorebi/src/window_manager.rs | 360 +++++++++++++++++++++++- komorebi/src/workspace.rs | 2 + komorebi/tests/workspace_commands.rs | 401 +++++++++++++++++++++++++++ komorebic/Cargo.toml | 3 + komorebic/src/main.rs | 251 +++++++++++++++++ komorebic/tests/cli.rs | 92 ++++++ nix/tests/vm/suites/commands/test.py | 32 +++ 33 files changed, 1782 insertions(+), 9 deletions(-) create mode 100644 docs/cli/close-workspace.md create mode 100644 docs/cli/cycle-empty-workspace.md create mode 100644 docs/cli/cycle-move-to-workspace.md create mode 100644 docs/cli/cycle-send-to-workspace.md create mode 100644 docs/cli/cycle-workspace.md create mode 100644 docs/cli/ensure-named-workspaces.md create mode 100644 docs/cli/ensure-workspaces.md create mode 100644 docs/cli/focus-last-workspace.md create mode 100644 docs/cli/focus-named-workspace.md create mode 100644 docs/cli/focus-workspaces.md create mode 100644 docs/cli/move-to-last-workspace.md create mode 100644 docs/cli/named-workspace-layout.md create mode 100644 docs/cli/named-workspace-tiling.md create mode 100644 docs/cli/new-workspace.md create mode 100644 docs/cli/send-to-last-workspace.md create mode 100644 docs/cli/workspace-layout.md create mode 100644 docs/cli/workspace-name.md create mode 100644 docs/cli/workspace-tiling.md create mode 100644 komorebi/tests/workspace_commands.rs diff --git a/README.md b/README.md index a746eaf8..8d1a7d0b 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,10 @@ layout, `manage-rule` tiles it whatever the ignore rules say, and `session-float-rule` floats the focused window and the windows like it. `focus-workspace` shows another workspace, and `move-to-workspace` and `send-to-workspace` put the focused window on another workspace, with and -without showing it. +without showing it; their `cycle-` and `-last-workspace` forms go to the next, +the previous or the last workspace, `workspace-name` names a workspace for +`focus-named-workspace` and the other named commands, and `new-workspace` and +`close-workspace` add and remove one. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/close-workspace.md b/docs/cli/close-workspace.md new file mode 100644 index 00000000..5ce04f43 --- /dev/null +++ b/docs/cli/close-workspace.md @@ -0,0 +1,10 @@ +```text +Close the focused workspace (must be empty and unnamed) + +Usage: close-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-empty-workspace.md b/docs/cli/cycle-empty-workspace.md new file mode 100644 index 00000000..ca6a6d58 --- /dev/null +++ b/docs/cli/cycle-empty-workspace.md @@ -0,0 +1,14 @@ +```text +Focus the next empty workspace in the given cycle direction (if one exists) + +Usage: cycle-empty-workspace + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-move-to-workspace.md b/docs/cli/cycle-move-to-workspace.md new file mode 100644 index 00000000..b2b86bfb --- /dev/null +++ b/docs/cli/cycle-move-to-workspace.md @@ -0,0 +1,14 @@ +```text +Move the focused window to the workspace in the given cycle direction + +Usage: cycle-move-to-workspace + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-send-to-workspace.md b/docs/cli/cycle-send-to-workspace.md new file mode 100644 index 00000000..a19499f3 --- /dev/null +++ b/docs/cli/cycle-send-to-workspace.md @@ -0,0 +1,14 @@ +```text +Send the focused window to the workspace in the given cycle direction + +Usage: cycle-send-to-workspace + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-workspace.md b/docs/cli/cycle-workspace.md new file mode 100644 index 00000000..2146fc81 --- /dev/null +++ b/docs/cli/cycle-workspace.md @@ -0,0 +1,14 @@ +```text +Focus the workspace in the given cycle direction + +Usage: cycle-workspace + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/ensure-named-workspaces.md b/docs/cli/ensure-named-workspaces.md new file mode 100644 index 00000000..8fa821f0 --- /dev/null +++ b/docs/cli/ensure-named-workspaces.md @@ -0,0 +1,17 @@ +```text +Create these many named workspaces for the specified monitor + +Usage: ensure-named-workspaces [NAMES]... + +Arguments: + + Monitor index (zero-indexed) + + [NAMES]... + Names of desired workspaces + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/ensure-workspaces.md b/docs/cli/ensure-workspaces.md new file mode 100644 index 00000000..a91e64a1 --- /dev/null +++ b/docs/cli/ensure-workspaces.md @@ -0,0 +1,17 @@ +```text +Create at least this many workspaces for the specified monitor + +Usage: ensure-workspaces + +Arguments: + + Monitor index (zero-indexed) + + + Number of desired workspaces + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-last-workspace.md b/docs/cli/focus-last-workspace.md new file mode 100644 index 00000000..168226d5 --- /dev/null +++ b/docs/cli/focus-last-workspace.md @@ -0,0 +1,10 @@ +```text +Focus the last focused workspace on the focused monitor + +Usage: focus-last-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-named-workspace.md b/docs/cli/focus-named-workspace.md new file mode 100644 index 00000000..e3d31cfc --- /dev/null +++ b/docs/cli/focus-named-workspace.md @@ -0,0 +1,14 @@ +```text +Focus the specified workspace + +Usage: focus-named-workspace + +Arguments: + + Target workspace name + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-workspaces.md b/docs/cli/focus-workspaces.md new file mode 100644 index 00000000..e2bbc0c3 --- /dev/null +++ b/docs/cli/focus-workspaces.md @@ -0,0 +1,14 @@ +```text +Focus the specified workspace on all monitors + +Usage: focus-workspaces + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-to-last-workspace.md b/docs/cli/move-to-last-workspace.md new file mode 100644 index 00000000..83bf3e9a --- /dev/null +++ b/docs/cli/move-to-last-workspace.md @@ -0,0 +1,10 @@ +```text +Move the focused window to the last focused monitor workspace + +Usage: move-to-last-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/named-workspace-layout.md b/docs/cli/named-workspace-layout.md new file mode 100644 index 00000000..03eb3ea3 --- /dev/null +++ b/docs/cli/named-workspace-layout.md @@ -0,0 +1,26 @@ +```text +Set the layout for the specified workspace + +Usage: named-workspace-layout + +Arguments: + + Target workspace name + + + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/named-workspace-tiling.md b/docs/cli/named-workspace-tiling.md new file mode 100644 index 00000000..fb11fd49 --- /dev/null +++ b/docs/cli/named-workspace-tiling.md @@ -0,0 +1,17 @@ +```text +Enable or disable window tiling for the specified workspace + +Usage: named-workspace-tiling + +Arguments: + + Target workspace name + + + [possible values: enable, disable] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/new-workspace.md b/docs/cli/new-workspace.md new file mode 100644 index 00000000..6fad0ed7 --- /dev/null +++ b/docs/cli/new-workspace.md @@ -0,0 +1,10 @@ +```text +Create and append a new workspace on the focused monitor + +Usage: new-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/query.md b/docs/cli/query.md index f2a6a955..1dfeae39 100644 --- a/docs/cli/query.md +++ b/docs/cli/query.md @@ -6,7 +6,8 @@ Usage: query Arguments: [possible values: focused-monitor-index, focused-workspace-index, focused-container-index, - focused-window-index, focused-workspace-layout, focused-container-kind, version] + focused-window-index, focused-workspace-name, focused-workspace-layout, + focused-container-kind, version] Options: -h, --help diff --git a/docs/cli/send-to-last-workspace.md b/docs/cli/send-to-last-workspace.md new file mode 100644 index 00000000..7b9ac014 --- /dev/null +++ b/docs/cli/send-to-last-workspace.md @@ -0,0 +1,10 @@ +```text +Send the focused window to the last focused monitor workspace + +Usage: send-to-last-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/workspace-layout.md b/docs/cli/workspace-layout.md new file mode 100644 index 00000000..21e8107b --- /dev/null +++ b/docs/cli/workspace-layout.md @@ -0,0 +1,29 @@ +```text +Set the layout for the specified workspace + +Usage: workspace-layout + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + + + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/workspace-name.md b/docs/cli/workspace-name.md new file mode 100644 index 00000000..7110d1a5 --- /dev/null +++ b/docs/cli/workspace-name.md @@ -0,0 +1,20 @@ +```text +Set the workspace name for the specified workspace + +Usage: workspace-name + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + + + Name of the workspace as a String + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/workspace-tiling.md b/docs/cli/workspace-tiling.md new file mode 100644 index 00000000..01157a40 --- /dev/null +++ b/docs/cli/workspace-tiling.md @@ -0,0 +1,20 @@ +```text +Enable or disable window tiling for the specified workspace + +Usage: workspace-tiling + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + + + [possible values: enable, disable] + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index d4c86da3..906490c4 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -20,7 +20,8 @@ each part of the daemon that is added has its place here. the panels). - **Workspace**: the containers a monitor shows, in order, and the layout that tiles them. A monitor has a ring of workspaces and shows one of them. Workspace `i` is the - compositor's desktop `i` on that monitor. + compositor's desktop `i` on that monitor. A workspace can have a name, which the named + commands find it by. - **Desktop**: one of KWin's virtual desktops. KWin shows the windows of one desktop on each output and hides the others; with its per-output virtual desktops on, each output shows a desktop of its own. @@ -421,6 +422,22 @@ of the monitor and shows that workspace, and `SendContainerToWorkspaceNumber` do and leaves the workspace in front showing ([`WindowManager::move_container_to_workspace`]). A workspace that does not exist yet is created, with the ones before it, and gets a desktop. +The other workspace commands are made of the same two operations. `CycleFocusWorkspace`, +`CycleMoveContainerToWorkspace` and `CycleSendContainerToWorkspace` take the next or the previous +workspace, which wraps around, and `CycleFocusEmptyWorkspace` the next or the previous with no +window. A monitor remembers the workspace that was in front before ([`Monitor::focus_workspace`] +records it), which `FocusLastWorkspace`, `MoveContainerToLastWorkspace` and +`SendContainerToLastWorkspace` take. `FocusWorkspaceNumbers` shows a workspace on every monitor. +`WorkspaceName` names a workspace, `EnsureNamedWorkspaces` gives a monitor named workspaces, and +`FocusNamedWorkspace`, `NamedWorkspaceLayout` and `NamedWorkspaceTiling` look a workspace up by +its name on every monitor ([`WindowManager::monitor_workspace_index_by_name`]); a name no +workspace has changes nothing. `FocusNamedWorkspace` focuses the monitor that has the workspace +([`WindowManager::focus_monitor`]). `WorkspaceLayout` and `WorkspaceTiling` set the layout and the +tiling of a workspace by index. `NewWorkspace` adds a workspace and shows it, `EnsureWorkspaces` +gives a monitor workspaces up to a number, and `CloseWorkspace` removes the workspace in front +when it has no window and no name and is not the monitor's last. A name is komorebi's: the +compositor's desktops keep theirs. + `PreselectDirection` reserves the index on one side of the focused container for the next window ([`WindowManager::preselect_container_in_direction`]). The workspace inserts an empty container there ([`Container::preselect`]), which [`Workspace::update`] keeps and the layout @@ -481,7 +498,8 @@ module's unit. window out, move the focus, move the focused container, change the layout, resize or promote the focused container, float a window, lock a container, set the padding of a workspace, manage and unmanage a window, show a workspace, move a container to another - workspace, follow a workspace switch made by something else). + workspace, follow a workspace switch made by something else, name a workspace and find + it by its name, set the layout of a workspace that is not in front). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -583,6 +601,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A workspace switch or a window move made by something else is followed, and answered with no command | framework path: the table reports what it did not send as a `WorkspaceChange` or a `WorkspaceMove`, and [`WindowManager::adopt_workspace_change`] asks the compositor for nothing | `a_workspace_switch_by_someone_else_is_followed_not_undone`, `a_window_moved_to_another_desktop_by_someone_else_changes_workspace`, `another_party_switching_a_monitor_is_a_workspace_change`, `vm-workspace-switch` ("nothing is flip-flopping") | none | | komorebi's own switch or move, reported back by KWin, changes nothing | framework path: the table records a switch and a move when it makes their commands | `the_compositor_reporting_komorebis_own_switch_changes_nothing`, `komorebis_own_move_coming_back_as_an_event_moves_nothing`, `komorebi_switching_a_monitor_comes_back_as_a_change_to_what_it_already_knows` | none | | The user's `kwinrc` gets back the value komorebi changed, also after a crash | framework path: [`Kwinrc`] records the first value of a key in a backup file, and the backend's `shutdown` puts it back | `what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed`, `a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run`, `vm-workspace-switch` ("back as they were") | `SIGKILL`: the next run puts it back when it stops | +| A workspace is closed only when it has no window and no name and is not the monitor's last | framework path: the `CloseWorkspace` arm of [`WindowManager::process_command`] checks all three | `new_workspace_adds_one_and_close_workspace_removes_it_when_it_is_empty_and_unnamed` | none | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | 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 | @@ -714,7 +733,9 @@ A window is shown, and ends up on a tile: - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, and every `komorebic` command, against a real KWin with two outputs. - [`komorebi/tests/workspaces.rs`](../../komorebi/tests/workspaces.rs): workspaces as the - fake's desktops; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the + fake's desktops; + [`komorebi/tests/workspace_commands.rs`](../../komorebi/tests/workspace_commands.rs), naming, + cycling and the other workspace commands; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the `kwinrc` editor and its tests. - [`nix/tests/vm/suites/workspace-switch`](../../nix/tests/vm/suites/workspace-switch/test.py): workspaces as a real KWin's desktops, switched by `komorebic` and by KWin; @@ -809,6 +830,9 @@ A window is shown, and ends up on a tile: [`WindowManager::adopt_workspace_change`]: ../../komorebi/src/window_manager.rs [`WindowManager::focus_workspace`]: ../../komorebi/src/window_manager.rs [`WindowManager::move_container_to_workspace`]: ../../komorebi/src/window_manager.rs +[`WindowManager::monitor_workspace_index_by_name`]: ../../komorebi/src/window_manager.rs +[`WindowManager::focus_monitor`]: ../../komorebi/src/window_manager.rs +[`Monitor::focus_workspace`]: ../../komorebi/src/monitor.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 diff --git a/docs/usage/workspaces.md b/docs/usage/workspaces.md index c3713c31..d41986a2 100644 --- a/docs/usage/workspaces.md +++ b/docs/usage/workspaces.md @@ -36,6 +36,74 @@ komorebic move-to-workspace 1 komorebic send-to-workspace 2 ``` +## Going round the workspaces + +[`komorebic cycle-workspace`](../cli/cycle-workspace.md) shows the next or the previous workspace +of the focused monitor, and wraps around at both ends; +[`komorebic cycle-empty-workspace`](../cli/cycle-empty-workspace.md) shows the next or the previous +one that has no window, if there is one. +[`komorebic cycle-move-to-workspace`](../cli/cycle-move-to-workspace.md) and +[`komorebic cycle-send-to-workspace`](../cli/cycle-send-to-workspace.md) take the focused window to +the next or the previous workspace, with and without showing it. + +```sh +komorebic cycle-workspace next +komorebic cycle-empty-workspace previous +komorebic cycle-move-to-workspace next +``` + +## The last workspace + +Each monitor remembers which workspace was in front before the one in front now. +[`komorebic focus-last-workspace`](../cli/focus-last-workspace.md) shows it again, so two in a row +go back and forth between the two. +[`komorebic move-to-last-workspace`](../cli/move-to-last-workspace.md) and +[`komorebic send-to-last-workspace`](../cli/send-to-last-workspace.md) take the focused window +there, with and without showing it. + +## Names + +[`komorebic workspace-name`](../cli/workspace-name.md) names a workspace, given by the index of its +monitor and its own index, and +[`komorebic ensure-named-workspaces`](../cli/ensure-named-workspaces.md) gives a monitor a workspace +for each name it is given, in order. The name is komorebi's, for the commands that find a +workspace by its name: KWin's desktop keeps the name it has. +[`komorebic focus-named-workspace`](../cli/focus-named-workspace.md) shows the workspace with that +name, on whichever monitor has it, and focuses that monitor. A name no workspace has changes +nothing. `komorebic query focused-workspace-name` prints the name of the workspace in front, or its +index when it has none. + +```sh +komorebic ensure-named-workspaces 0 web code mail +komorebic focus-named-workspace mail +``` + +## Adding and removing workspaces + +[`komorebic new-workspace`](../cli/new-workspace.md) adds a workspace after the last one of the +focused monitor and shows it, and [`komorebic ensure-workspaces`](../cli/ensure-workspaces.md) +gives a monitor at least as many workspaces as it is told. +[`komorebic close-workspace`](../cli/close-workspace.md) removes the workspace in front and shows +the one before it, when the workspace has no window and no name and is not the monitor's last. + +[`komorebic focus-workspaces`](../cli/focus-workspaces.md) shows the workspace with the same index +on every monitor. + +## The layout of another workspace + +[`komorebic workspace-layout`](../cli/workspace-layout.md) and +[`komorebic workspace-tiling`](../cli/workspace-tiling.md) set the layout of a workspace, and turn +its tiling off or on, by the index of its monitor and its own index; +[`komorebic named-workspace-layout`](../cli/named-workspace-layout.md) and +[`komorebic named-workspace-tiling`](../cli/named-workspace-tiling.md) find it by its name. The +focused workspace is tiled again at once, and another workspace the next time it is tiled, when it +is shown at the latest. + +```sh +komorebic workspace-layout 0 1 columns +komorebic named-workspace-tiling mail disable +``` + ## Switching with KWin Anything that switches KWin's desktop switches komorebi's workspace: the pager, KWin's own diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index e51b7894..e8d78060 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -274,6 +274,7 @@ pub enum StateQuery { FocusedWorkspaceIndex, FocusedContainerIndex, FocusedWindowIndex, + FocusedWorkspaceName, FocusedWorkspaceLayout, FocusedContainerKind, Version, @@ -348,8 +349,12 @@ pub enum SocketMessage { CycleMoveWindow(CycleDirection), ResizeWindowEdge(OperationDirection, Sizing), ResizeWindowAxis(Axis, Sizing), + MoveContainerToLastWorkspace, + SendContainerToLastWorkspace, MoveContainerToWorkspaceNumber(usize), + CycleMoveContainerToWorkspace(CycleDirection), SendContainerToWorkspaceNumber(usize), + CycleSendContainerToWorkspace(CycleDirection), // ForceFocus, Close, Minimize, @@ -375,6 +380,9 @@ pub enum SocketMessage { FlipLayout(Axis), // Monitor and Workspace Commands // MonitorIndexPreference(usize, i32, i32, i32, i32), + EnsureWorkspaces(usize, usize), + EnsureNamedWorkspaces(usize, Vec), + NewWorkspace, ToggleTiling, Stop, TogglePause, @@ -384,11 +392,24 @@ pub enum SocketMessage { QuickLoad, Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf), Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + CycleFocusWorkspace(CycleDirection), + CycleFocusEmptyWorkspace(CycleDirection), + FocusLastWorkspace, + CloseWorkspace, FocusWorkspaceNumber(usize), + FocusWorkspaceNumbers(usize), + FocusNamedWorkspace(String), ContainerPadding(usize, usize, i32), FocusedWorkspaceContainerPadding(i32), WorkspacePadding(usize, usize, i32), FocusedWorkspacePadding(i32), + WorkspaceTiling(usize, usize, bool), + NamedWorkspaceTiling(String, bool), + WorkspaceName(usize, usize, String), + WorkspaceLayout(usize, usize, DefaultLayout), + NamedWorkspaceLayout(String, DefaultLayout), + // WorkspaceLayoutCustom(usize, usize, #[serde_as(as = "ResolvedPathBuf")] PathBuf), + // NamedWorkspaceLayoutCustom(String, #[serde_as(as = "ResolvedPathBuf")] PathBuf), WorkAreaOffset(Rect), MonitorWorkAreaOffset(usize, Rect), WorkspaceWorkAreaOffset(usize, usize, Rect), diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 18160570..ea14c389 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -66,6 +66,10 @@ pub struct Monitor { pub window_based_work_area_offset_limit: isize, pub container_padding: Option, pub workspace_padding: Option, + /// The workspace that was in front before the one in front now, which `focus-last-workspace` + /// shows again + #[serde(skip_serializing_if = "Option::is_none")] + pub last_focused_workspace: Option, } /// Returns a monitor with one empty workspace, the way [`Monitor::new`] makes one, from owned @@ -90,6 +94,7 @@ pub fn new( window_based_work_area_offset: None, window_based_work_area_offset_limit: 1, workspaces, + last_focused_workspace: None, container_padding: None, workspace_padding: None, } @@ -119,6 +124,7 @@ impl Monitor { window_based_work_area_offset_limit: 1, container_padding: None, workspace_padding: None, + last_focused_workspace: None, } } @@ -176,6 +182,7 @@ impl Monitor { if workspaces.get(idx).is_none() { workspaces.resize(idx + 1, Workspace::default()); } + self.last_focused_workspace = Some(self.workspaces.focused_idx()); self.workspaces.focus(idx); } @@ -427,6 +434,13 @@ impl Monitor { } } + /// The name of the focused workspace, if it has one + pub fn focused_workspace_name(&self) -> Option { + self.focused_workspace() + .map(|w| w.name.clone()) + .unwrap_or(None) + } + /// The layout of the focused workspace, if the monitor has one and its tiling is on pub fn focused_workspace_layout(&self) -> Option { self.focused_workspace().and_then(|workspace| { diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index da0b26c0..88a4bb49 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -87,6 +87,19 @@ //! shows it, and **SendContainerToWorkspaceNumber** moves it there and stays //! ([`WindowManager::move_container_to_workspace`]). A workspace that does not exist yet is //! made, with the ones before it. +//! - **CycleFocusWorkspace**, **CycleMoveContainerToWorkspace** and +//! **CycleSendContainerToWorkspace** do the same for the next or the previous workspace, and +//! **FocusLastWorkspace**, **MoveContainerToLastWorkspace** and +//! **SendContainerToLastWorkspace** for the workspace that was in front before. +//! **CycleFocusEmptyWorkspace** shows the next or the previous workspace with no window, and +//! **FocusWorkspaceNumbers** shows a workspace on every monitor. +//! - **WorkspaceName** names a workspace and **EnsureNamedWorkspaces** gives a monitor named +//! workspaces; **FocusNamedWorkspace** shows the workspace with a name, on its monitor +//! ([`WindowManager::monitor_workspace_index_by_name`]), and **NamedWorkspaceLayout** and +//! **NamedWorkspaceTiling** set its layout and its tiling, which **WorkspaceLayout** and +//! **WorkspaceTiling** do by index. **EnsureWorkspaces** gives a monitor workspaces up to a +//! number, **NewWorkspace** adds one and shows it, and **CloseWorkspace** removes the workspace +//! in front when it has no window and no name and is not the monitor's last. //! - **Retile** tiles the focused workspace of every monitor again, without the resize //! adjustments, and **RetileWithResizeDimensions** with them. //! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name @@ -133,6 +146,7 @@ use std::fs::File; use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; +use std::num::NonZeroUsize; use std::os::unix::net::UnixStream; use std::str::FromStr; use std::sync::Arc; @@ -208,6 +222,9 @@ impl WindowManager { /// `UnlockMonitorWorkspaceContainer` is not there (a container that is not there is ignored). /// - The focused window cannot be floated or put back, for one of the reasons /// [`WindowManager::toggle_float`] gives. + /// - The monitor or the workspace a message names by its index is not there + /// (`WorkspaceName`, `WorkspaceLayout`, `WorkspaceTiling`, `EnsureWorkspaces`, + /// `EnsureNamedWorkspaces`). A name no workspace has is ignored. /// - The focused monitor has no workspace or no container to move to another workspace, or /// the compositor reports no window with the focus (`MoveContainerToWorkspaceNumber`, /// `SendContainerToWorkspaceNumber`), or the focused window of the workspace that is shown @@ -282,11 +299,119 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::CycleFocusWorkspace(direction) => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + + self.focus_workspace(workspace_idx)?; + } + SocketMessage::CycleFocusEmptyWorkspace(direction) => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let mut empty_workspaces = vec![]; + + for (idx, w) in focused_monitor.workspaces().iter().enumerate() { + if w.is_empty() { + empty_workspaces.push(idx); + } + } + + if !empty_workspaces.is_empty() { + let mut workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + + while !empty_workspaces.contains(&workspace_idx) { + workspace_idx = direction.next_idx( + workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + } + + self.focus_workspace(workspace_idx)?; + } + } + SocketMessage::FocusLastWorkspace => { + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.focus_workspace(last_focused_workspace)?; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + } SocketMessage::FocusWorkspaceNumber(workspace_idx) => { if self.focused_workspace_idx().unwrap_or_default() != workspace_idx { self.focus_workspace(workspace_idx)?; } } + SocketMessage::FocusWorkspaceNumbers(workspace_idx) => { + let focused_monitor_idx = self.focused_monitor_idx(); + + for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { + if i != focused_monitor_idx { + monitor.focus_workspace(workspace_idx)?; + monitor.load_focused_workspace(false)?; + } + } + + self.focus_workspace(workspace_idx)?; + } + SocketMessage::FocusNamedWorkspace(ref name) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(name) + { + self.focus_monitor(monitor_idx)?; + self.focus_workspace(workspace_idx)?; + } + } + SocketMessage::CloseWorkspace => { + let mut can_close = false; + + if let Some(monitor) = self.focused_monitor_mut() { + let focused_workspace_idx = monitor.focused_workspace_idx(); + let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); + + if let Some(workspace) = monitor.focused_workspace() + && monitor.workspaces().len() > 1 + && workspace.containers().is_empty() + && workspace.floating_windows().is_empty() + && workspace.name.is_none() + { + can_close = true; + } + + if can_close + && monitor + .workspaces_mut() + .remove(focused_workspace_idx) + .is_some() + { + self.focus_workspace(next_focused_workspace_idx)?; + } + } + } SocketMessage::MoveContainerToWorkspaceNumber(workspace_idx) => { self.move_container_to_workspace(workspace_idx, true, None)?; @@ -294,6 +419,97 @@ impl WindowManager { SocketMessage::SendContainerToWorkspaceNumber(workspace_idx) => { self.move_container_to_workspace(workspace_idx, false, None)?; } + SocketMessage::MoveContainerToLastWorkspace => { + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.move_container_to_workspace(last_focused_workspace, true, None)?; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + } + SocketMessage::SendContainerToLastWorkspace => { + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.move_container_to_workspace(last_focused_workspace, false, None)?; + } + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + } + SocketMessage::CycleMoveContainerToWorkspace(direction) => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + + self.move_container_to_workspace(workspace_idx, true, None)?; + } + SocketMessage::CycleSendContainerToWorkspace(direction) => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + + self.move_container_to_workspace(workspace_idx, false, None)?; + } + SocketMessage::NewWorkspace => { + self.new_workspace()?; + } + SocketMessage::WorkspaceTiling(monitor_idx, workspace_idx, tile) => { + self.set_workspace_tiling(monitor_idx, workspace_idx, tile)?; + } + SocketMessage::WorkspaceLayout(monitor_idx, workspace_idx, layout) => { + self.set_workspace_layout_default(monitor_idx, workspace_idx, layout)?; + } + SocketMessage::NamedWorkspaceTiling(ref workspace, tile) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + self.set_workspace_tiling(monitor_idx, workspace_idx, tile)?; + } + } + SocketMessage::WorkspaceName(monitor_idx, workspace_idx, ref name) => { + self.set_workspace_name(monitor_idx, workspace_idx, name.to_string())?; + } + SocketMessage::NamedWorkspaceLayout(ref workspace, layout) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + self.set_workspace_layout_default(monitor_idx, workspace_idx, layout)?; + } + } + SocketMessage::EnsureWorkspaces(monitor_idx, workspace_count) => { + self.ensure_workspaces_for_monitor(monitor_idx, workspace_count)?; + } + SocketMessage::EnsureNamedWorkspaces(monitor_idx, ref names) => { + self.ensure_named_workspaces_for_monitor(monitor_idx, names)?; + } SocketMessage::ToggleFloat => self.toggle_float(false)?, SocketMessage::ResizeWindowEdge(direction, sizing) => { self.resize_window(direction, sizing, self.resize_delta, true)?; @@ -489,6 +705,14 @@ impl WindowManager { StateQuery::FocusedWindowIndex => { self.focused_container()?.focused_window_idx().to_string() } + StateQuery::FocusedWorkspaceName => { + let focused_monitor = + self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor + .focused_workspace_name() + .unwrap_or_else(|| focused_monitor.focused_workspace_idx().to_string()) + } StateQuery::Version => build::VERSION.to_string(), StateQuery::FocusedWorkspaceLayout => { let focused_monitor = @@ -1062,6 +1286,8 @@ mod tests { assert_eq!(query(StateQuery::FocusedWorkspaceIndex)?, "0"); assert_eq!(query(StateQuery::FocusedContainerIndex)?, "0"); assert_eq!(query(StateQuery::FocusedWindowIndex)?, "0"); + // a workspace with no name is named by its index + assert_eq!(query(StateQuery::FocusedWorkspaceName)?, "0"); assert_eq!(query(StateQuery::FocusedWorkspaceLayout)?, "BSP"); assert_eq!(query(StateQuery::FocusedContainerKind)?, "Single"); // the version is shadow-rs's description of the build, the package version first diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 6aaf51aa..8f3ea9ad 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -149,6 +149,7 @@ impl From<&WindowManager> for State { .workspaces() .iter() .map(|workspace| Workspace { + name: workspace.name.clone(), containers: workspace.containers.clone(), floating_windows: workspace.floating_windows.clone(), layout: workspace.layout.clone(), @@ -170,6 +171,8 @@ impl From<&WindowManager> for State { ws.focus(monitor.workspaces.focused_idx()); ws }, + last_focused_workspace: monitor.last_focused_workspace, + // workspace_names: monitor.workspace_names.clone(), container_padding: monitor.container_padding, workspace_padding: monitor.workspace_padding, }) diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index cb549330..d39b54c8 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -18,7 +18,9 @@ //! ([`WindowManager::focus_workspace`]), moves a container to one //! ([`WindowManager::move_container_to_workspace`]), makes sure the compositor has a desktop for //! each ([`WindowManager::sync_workspace_desktops`]), and follows a workspace switch that -//! something else made ([`WindowManager::adopt_workspace_change`]). +//! something else made ([`WindowManager::adopt_workspace_change`]). A workspace can be named +//! ([`WindowManager::set_workspace_name`]) and found by its name on any monitor +//! ([`WindowManager::monitor_workspace_index_by_name`]). //! //! [`listen_for_commands`]: crate::process_command::listen_for_commands @@ -327,6 +329,40 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, false) } + #[tracing::instrument(skip(self))] + pub fn set_workspace_layout_default( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + layout: DefaultLayout, + ) -> eyre::Result<()> { + tracing::info!("setting workspace layout"); + + let focused_monitor_idx = self.focused_monitor_idx(); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = monitor.focused_workspace_idx(); + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("there is no monitor")?; + + workspace.layout = Layout::Default(layout); + + // If this is the focused workspace on a non-focused screen, let's update it + if focused_monitor_idx != monitor_idx && focused_workspace_idx == workspace_idx { + workspace.update()?; + Ok(()) + } else { + Ok(self.update_focused_workspace(false, false)?) + } + } + pub fn focused_workspace_idx(&self) -> eyre::Result { Ok(self .focused_monitor() @@ -348,6 +384,21 @@ impl WindowManager { .ok_or_eyre("there is no workspace") } + #[tracing::instrument(skip(self))] + pub fn new_workspace(&mut self) -> eyre::Result<()> { + tracing::info!("adding new workspace"); + + let mouse_follows_focus = self.mouse_follows_focus; + let monitor = self + .focused_monitor_mut() + .ok_or_eyre("there is no workspace")?; + + monitor.focus_workspace(monitor.new_workspace_idx())?; + monitor.load_focused_workspace(mouse_follows_focus)?; + + self.update_focused_workspace(self.mouse_follows_focus, false) + } + pub fn focused_container(&self) -> eyre::Result<&Container> { self.focused_workspace()? .focused_container() @@ -958,6 +1009,36 @@ impl WindowManager { self.update_focused_workspace(false, false) } + #[tracing::instrument(skip(self))] + pub fn focus_monitor(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("focusing monitor"); + + if self.monitors().get(idx).is_some() { + self.monitors.focus(idx); + } else { + eyre::bail!("this is not a valid monitor index"); + } + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn monitor_workspace_index_by_name(&mut self, name: &str) -> Option<(usize, usize)> { + tracing::info!("looking up workspace by name"); + + for (monitor_idx, monitor) in self.monitors().iter().enumerate() { + for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { + if let Some(workspace_name) = &workspace.name + && workspace_name == name + { + return Option::from((monitor_idx, workspace_idx)); + } + } + } + + None + } + /// Gives the focus to the window of the next (or the previous) container of the focused /// workspace, wrapping around at the ends, and the pointer follows it if /// [`WindowManager::mouse_follows_focus`] is set @@ -1047,8 +1128,9 @@ impl WindowManager { Ok(()) } - /// Make sure the compositor has a virtual desktop for every workspace any monitor has, named - /// "Workspace 1", "Workspace 2" and so on where it has to create them + /// Make sure the compositor has a virtual desktop for every workspace any monitor has, with + /// the workspaces' names where it has to create them (and "Workspace 2" and so on for a + /// workspace without one) pub fn sync_workspace_desktops(&self) { let count = self .monitors() @@ -1058,7 +1140,15 @@ impl WindowManager { .unwrap_or(1) .max(1); - let names: Vec = (0..count).map(|i| format!("Workspace {}", i + 1)).collect(); + let names: Vec = (0..count) + .map(|i| { + self.monitors() + .iter() + .filter_map(|m| m.workspaces().get(i).and_then(|w| w.name.clone())) + .find(|name| !name.is_empty()) + .unwrap_or_else(|| format!("Workspace {}", i + 1)) + }) + .collect(); if let Err(error) = backend().ensure_workspaces(&names) { tracing::warn!("could not make sure there are desktops for the workspaces: {error}"); @@ -1143,6 +1233,31 @@ impl WindowManager { self.update_focused_workspace(false, false) } + #[tracing::instrument(skip(self))] + pub fn set_workspace_name( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + name: String, + ) -> eyre::Result<()> { + tracing::info!("setting workspace name"); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("there is no monitor")?; + + workspace.name = Option::from(name.clone()); + // monitor.workspace_names.insert(workspace_idx, name); + + Ok(()) + } + /// Gives the workspace at `workspace_idx` on the monitor at `monitor_idx` a container padding /// of `size` pixels, around each tile, and tiles the focused workspace again /// @@ -1174,6 +1289,28 @@ impl WindowManager { self.update_focused_workspace(false, false) } + #[tracing::instrument(skip(self))] + pub fn set_workspace_tiling( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + tile: bool, + ) -> eyre::Result<()> { + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("there is no monitor")?; + + workspace.tile = tile; + + self.update_focused_workspace(false, false) + } + /// Makes the workspace padding of the focused workspace `adjustment` pixels larger or smaller, /// and tiles it again /// @@ -1226,6 +1363,62 @@ impl WindowManager { self.update_focused_workspace(false, false) } + #[tracing::instrument(skip(self))] + pub fn ensure_workspaces_for_monitor( + &mut self, + monitor_idx: usize, + workspace_count: usize, + ) -> eyre::Result<()> { + tracing::info!("ensuring workspace count"); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + monitor.ensure_workspace_count(workspace_count); + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn ensure_named_workspaces_for_monitor( + &mut self, + monitor_idx: usize, + names: &Vec, + ) -> eyre::Result<()> { + tracing::info!("ensuring workspace count"); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + monitor.ensure_workspace_count(names.len()); + + for (workspace_idx, name) in names.iter().enumerate() { + if let Some(workspace) = monitor.workspaces_mut().get_mut(workspace_idx) { + workspace.name = Option::from(name.clone()); + } + } + + Ok(()) + } + + pub fn remove_focused_workspace(&mut self) -> Option { + let focused_monitor: &mut Monitor = self.focused_monitor_mut()?; + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspace = focused_monitor.remove_workspace_by_idx(focused_workspace_idx); + if let Err(error) = focused_monitor.focus_workspace(focused_workspace_idx.saturating_sub(1)) + { + tracing::error!( + "Error focusing previous workspace while removing the focused workspace: {}", + error + ); + } + workspace + } + /// Asks the window manager to manage the window that has the focus in the compositor again /// after [`WindowManager::unmanage_focused_window`], by raising a /// [`WindowManagerEvent::Manage`] for it, which is handled like a window that opens @@ -1366,6 +1559,96 @@ mod tests { assert_eq!(wm.focused_workspace_idx().unwrap(), 0); } + #[test] + fn test_remove_focused_workspace() { + let (mut wm, _context) = setup_window_manager(); + + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // a new monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // the next index on the monitor should be the not-yet-created second workspace + let new_workspace_index = m.new_workspace_idx(); + assert_eq!(new_workspace_index, 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + + { + // focus a workspace which doesn't yet exist should create it + let monitor = wm.focused_monitor_mut().unwrap(); + monitor.focus_workspace(new_workspace_index + 1).unwrap(); + + // Monitor focused workspace should be 2 + assert_eq!(monitor.focused_workspace_idx(), 2); + + // Should have 3 Workspaces + assert_eq!(monitor.workspaces().len(), 3); + } + + // Remove the focused workspace + wm.remove_focused_workspace().unwrap(); + + { + let monitor = wm.focused_monitor_mut().unwrap(); + monitor.focus_workspace(new_workspace_index).unwrap(); + + // Should be focused on workspace 1 + assert_eq!(monitor.focused_workspace_idx(), 1); + + // Should have 2 Workspaces + assert_eq!(monitor.workspaces().len(), 2); + } + } + + #[test] + fn test_set_workspace_name() { + let (mut wm, _test_context) = setup_window_manager(); + + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // a new monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // create a new workspace + let new_workspace_index = m.new_workspace_idx(); + assert_eq!(new_workspace_index, 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + + { + // focusing a workspace which doesn't yet exist should create it + let monitor = wm.focused_monitor_mut().unwrap(); + monitor.focus_workspace(new_workspace_index).unwrap(); + assert_eq!(monitor.workspaces().len(), 2); + } + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + + // set the name of the first workspace + wm.set_workspace_name(0, 0, "workspace1".to_string()) + .unwrap(); + + // monitor_workspace_index_by_name should return the index of the workspace with the name "workspace1" + let workspace_index = wm.monitor_workspace_index_by_name("workspace1").unwrap(); + + // workspace index 0 should now have the name "workspace1" + assert_eq!(workspace_index.1, 0); + } + #[test] fn test_focus_container_in_cycle_direction() { let (mut wm, _test_context) = setup_window_manager(); @@ -1728,4 +2011,73 @@ mod tests { "Expected an error when trying to float a non-existent window" ); } + + #[test] + fn test_ensure_named_workspace_for_monitor() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a monitor + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + + { + // Create a monitor + let m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor1".to_string(), + "TestDeviceID1".to_string(), + ); + + // Add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + + // Workspace names list + let mut workspace_names = vec!["Workspace".to_string(), "Workspace1".to_string()]; + + // Ensure workspaces for monitor 1 + wm.ensure_named_workspaces_for_monitor(1, &workspace_names) + .ok(); + + { + // Monitor 1 should have 2 workspaces with names "Workspace" and "Workspace1" + let monitor = wm.monitors().get(1).unwrap(); + let workspaces = monitor.workspaces(); + assert_eq!(workspaces.len(), workspace_names.len()); + for (i, workspace) in workspaces.iter().enumerate() { + assert_eq!(workspace.name, Some(workspace_names[i].clone())); + } + } + + // Add more workspaces to list + workspace_names.push("Workspace2".to_string()); + workspace_names.push("Workspace3".to_string()); + + // Ensure workspaces for monitor 0 + wm.ensure_named_workspaces_for_monitor(0, &workspace_names) + .ok(); + + { + // Monitor 0 should have 4 workspaces with names "Workspace", "Workspace1", + // "Workspace2" and "Workspace3" + let monitor = wm.monitors().front().unwrap(); + let workspaces = monitor.workspaces(); + assert_eq!(workspaces.len(), workspace_names.len()); + for (i, workspace) in workspaces.iter().enumerate() { + assert_eq!(workspace.name, Some(workspace_names[i].clone())); + } + } + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 4233e559..7ec1771b 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -27,6 +27,7 @@ use std::num::NonZeroUsize; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Workspace { + pub name: Option, pub containers: Ring, pub floating_windows: Ring, pub layout: Layout, @@ -55,6 +56,7 @@ impl_ring_elements!(Workspace, Window, "floating_window"); impl Default for Workspace { fn default() -> Self { Self { + name: None, containers: Default::default(), workspace_padding: None, container_padding: None, diff --git a/komorebi/tests/workspace_commands.rs b/komorebi/tests/workspace_commands.rs new file mode 100644 index 00000000..c1f2638e --- /dev/null +++ b/komorebi/tests/workspace_commands.rs @@ -0,0 +1,401 @@ +//! The workspace commands beyond showing a workspace and moving a window to one by its index +//! (`workspaces.rs`), against an in-memory desktop: naming a workspace and finding it by its name, +//! cycling through the workspaces, going back to the last one, adding and closing workspaces, and +//! setting the layout and the tiling of a workspace that need not be in front. The messages go in +//! through [`WindowManager::process_command`]; what comes out is the workspaces of the window +//! manager and what the compositor was asked to show. +//! +//! Window ids are in the 31_000s. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::CycleDirection; +use komorebi::core::DefaultLayout; +use komorebi::core::Layout; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::core::StateQuery; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +const MONITOR: u32 = 1; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over `fake`, with a window for each of `ids`, opened in that order +fn desktop_on(fake: FakeBackend, ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(fake); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmw-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); + } + + (fake, wm) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor +fn desktop(ids: &[u32]) -> (Arc, WindowManager) { + desktop_on(FakeBackend::with_one_monitor(), ids) +} + +fn send( + fake: &Arc, + wm: &mut WindowManager, + message: SocketMessage, +) -> color_eyre::Result<()> { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())) +} + +fn query(fake: &Arc, wm: &mut WindowManager, query: StateQuery) -> String { + let mut answer = Vec::new(); + with_backend(fake.clone(), || { + wm.process_command(SocketMessage::Query(query), &mut answer) + }) + .unwrap(); + String::from_utf8(answer).unwrap() +} + +/// The ids of the windows of each workspace of the focused monitor +fn windows(wm: &WindowManager) -> Vec> { + wm.focused_monitor() + .unwrap() + .workspaces() + .iter() + .map(|workspace| { + workspace + .containers() + .iter() + .flat_map(|container| container.windows().iter().map(|window| window.id)) + .collect() + }) + .collect() +} + +fn names(wm: &WindowManager) -> Vec> { + wm.focused_monitor() + .unwrap() + .workspaces() + .iter() + .map(|workspace| workspace.name.clone()) + .collect() +} + +#[test] +fn a_named_workspace_is_found_by_its_name_and_shown() { + let (fake, mut wm) = desktop(&[31_001]); + + assert!( + send( + &fake, + &mut wm, + SocketMessage::WorkspaceName(0, 2, String::from("mail")), + ) + .is_err(), + "there is no workspace 2 to name yet" + ); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 3)).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::WorkspaceName(0, 2, String::from("mail")), + ) + .unwrap(); + assert_eq!(query(&fake, &mut wm, StateQuery::FocusedWorkspaceName), "0"); + + fake.clear_commands(); + send( + &fake, + &mut wm, + SocketMessage::FocusNamedWorkspace(String::from("mail")), + ) + .unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 2); + assert_eq!(fake.shown_workspace(MONITOR), 2); + assert!( + fake.commands() + .contains(&Command::SwitchWorkspace(MONITOR, 2)), + "{:?}", + fake.commands() + ); + assert_eq!( + query(&fake, &mut wm, StateQuery::FocusedWorkspaceName), + "mail" + ); +} + +#[test] +fn a_name_no_workspace_has_changes_nothing() { + let (fake, mut wm) = desktop(&[31_011]); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 2)).unwrap(); + fake.clear_commands(); + + send( + &fake, + &mut wm, + SocketMessage::FocusNamedWorkspace(String::from("nowhere")), + ) + .unwrap(); + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspaceTiling(String::from("nowhere"), false), + ) + .unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); +} + +#[test] +fn ensure_named_workspaces_gives_a_monitor_workspaces_with_those_names() { + let (fake, mut wm) = desktop(&[]); + + send( + &fake, + &mut wm, + SocketMessage::EnsureNamedWorkspaces(0, vec![String::from("web"), String::from("code")]), + ) + .unwrap(); + + assert_eq!( + names(&wm), + [Some(String::from("web")), Some(String::from("code"))] + ); +} + +#[test] +fn cycle_workspace_goes_round_the_workspaces_of_the_monitor() { + let (fake, mut wm) = desktop(&[31_021]); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 3)).unwrap(); + let mut shown = vec![]; + + for direction in [ + CycleDirection::Next, + CycleDirection::Next, + CycleDirection::Next, + CycleDirection::Previous, + ] { + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWorkspace(direction), + ) + .unwrap(); + shown.push(( + wm.focused_workspace_idx().unwrap(), + fake.shown_workspace(MONITOR), + )); + } + + assert_eq!(shown, [(1, 1), (2, 2), (0, 0), (2, 2)]); +} + +#[test] +fn cycle_empty_workspace_goes_to_the_next_workspace_without_windows() { + let (fake, mut wm) = desktop(&[31_031, 31_032]); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 3)).unwrap(); + // the focused window (31_032) on workspace 1: workspace 2 is the only empty one + send( + &fake, + &mut wm, + SocketMessage::SendContainerToWorkspaceNumber(1), + ) + .unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusEmptyWorkspace(CycleDirection::Next), + ) + .unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 2); + assert_eq!(windows(&wm), [vec![31_031], vec![31_032], vec![]]); +} + +#[test] +fn focus_last_workspace_goes_back_and_forth_between_the_last_two() { + let (fake, mut wm) = desktop(&[31_041]); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(2)).unwrap(); + let mut shown = vec![]; + + for _ in 0..3 { + send(&fake, &mut wm, SocketMessage::FocusLastWorkspace).unwrap(); + shown.push(fake.shown_workspace(MONITOR)); + } + + assert_eq!(shown, [0, 2, 0]); +} + +#[test] +fn send_to_last_workspace_takes_the_window_to_the_one_in_front_before_and_stays() { + let (fake, mut wm) = desktop(&[31_051, 31_052]); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)).unwrap(); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(0)).unwrap(); + + send(&fake, &mut wm, SocketMessage::SendContainerToLastWorkspace).unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + assert_eq!(windows(&wm), [vec![31_051], vec![31_052]]); + assert_eq!(fake.workspace_of(31_052), Some(1)); +} + +#[test] +fn move_to_last_workspace_takes_the_window_to_the_one_in_front_before_and_shows_it() { + let (fake, mut wm) = desktop(&[31_055, 31_056]); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)).unwrap(); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(0)).unwrap(); + + send(&fake, &mut wm, SocketMessage::MoveContainerToLastWorkspace).unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert_eq!(fake.shown_workspace(MONITOR), 1); + assert_eq!(windows(&wm), [vec![31_055], vec![31_056]]); + assert!(fake.on_screen(31_056) && !fake.on_screen(31_055)); +} + +#[test] +fn cycle_send_and_cycle_move_take_the_window_to_the_next_workspace() { + let (fake, mut wm) = desktop(&[31_061, 31_062]); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 2)).unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::CycleSendContainerToWorkspace(CycleDirection::Next), + ) + .unwrap(); + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + assert_eq!(windows(&wm), [vec![31_061], vec![31_062]]); + + // from workspace 0, the previous workspace is the last one, and the window goes with it + send( + &fake, + &mut wm, + SocketMessage::CycleMoveContainerToWorkspace(CycleDirection::Previous), + ) + .unwrap(); + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert_eq!(windows(&wm), [vec![], vec![31_062, 31_061]]); + assert_eq!(fake.shown_workspace(MONITOR), 1); +} + +#[test] +fn new_workspace_adds_one_and_close_workspace_removes_it_when_it_is_empty_and_unnamed() { + let (fake, mut wm) = desktop(&[31_071]); + + send(&fake, &mut wm, SocketMessage::NewWorkspace).unwrap(); + assert_eq!(windows(&wm).len(), 2); + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert_eq!(fake.shown_workspace(MONITOR), 1); + + send(&fake, &mut wm, SocketMessage::CloseWorkspace).unwrap(); + assert_eq!(windows(&wm).len(), 1); + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + assert_eq!(fake.shown_workspace(MONITOR), 0); + + // the last workspace, a workspace with a window, and a named workspace stay + send(&fake, &mut wm, SocketMessage::CloseWorkspace).unwrap(); + assert_eq!(windows(&wm), [vec![31_071]]); + send(&fake, &mut wm, SocketMessage::NewWorkspace).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::WorkspaceName(0, 1, String::from("kept")), + ) + .unwrap(); + send(&fake, &mut wm, SocketMessage::CloseWorkspace).unwrap(); + assert_eq!(names(&wm), [None, Some(String::from("kept"))]); +} + +#[test] +fn focus_workspaces_shows_the_workspace_on_every_monitor() { + let fake = FakeBackend::with_one_monitor(); + let second = Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1080, + }; + fake.add_monitor(2, "Virtual-1", second, second); + let (fake, mut wm) = desktop_on(fake, &[]); + + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumbers(1)).unwrap(); + + assert_eq!((fake.shown_workspace(1), fake.shown_workspace(2)), (1, 1)); + assert!( + wm.monitors() + .iter() + .all(|monitor| monitor.focused_workspace_idx() == 1) + ); +} + +#[test] +fn the_layout_and_the_tiling_of_a_workspace_are_set_by_its_index_or_its_name() { + let (fake, mut wm) = desktop(&[31_081, 31_082]); + send( + &fake, + &mut wm, + SocketMessage::EnsureNamedWorkspaces(0, vec![String::from("main"), String::from("side")]), + ) + .unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::WorkspaceLayout(0, 0, DefaultLayout::Rows), + ) + .unwrap(); + let workspace = wm.focused_workspace().unwrap(); + assert_eq!(workspace.layout, Layout::Default(DefaultLayout::Rows)); + // the workspace in front is tiled again: one row above the other + let (first, second) = (fake.rect_of(31_081).unwrap(), fake.rect_of(31_082).unwrap()); + assert_eq!(first.left, second.left); + assert_ne!(first.top, second.top); + + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspaceLayout(String::from("side"), DefaultLayout::Columns), + ) + .unwrap(); + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspaceTiling(String::from("main"), false), + ) + .unwrap(); + send(&fake, &mut wm, SocketMessage::WorkspaceTiling(0, 1, false)).unwrap(); + + let workspaces = wm.focused_monitor().unwrap().workspaces(); + assert_eq!( + workspaces[1].layout, + Layout::Default(DefaultLayout::Columns) + ); + assert!(!workspaces[0].tile && !workspaces[1].tile); +} diff --git a/komorebic/Cargo.toml b/komorebic/Cargo.toml index f4c5d1e7..881baeb7 100644 --- a/komorebic/Cargo.toml +++ b/komorebic/Cargo.toml @@ -19,3 +19,6 @@ sysinfo = { workspace = true } [features] default = ["schemars"] schemars = ["komorebi-client/default"] + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(FALSE)'] } diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index e030edbc..54dac229 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -33,6 +33,15 @@ //! - `focus-workspace` shows another workspace of the focused monitor, `move-to-workspace` moves //! the focused window to a workspace and shows it, and `send-to-workspace` moves it there and //! stays. A workspace is KWin's virtual desktop of the same number, counted from 0. +//! `cycle-workspace`, `cycle-empty-workspace`, `cycle-move-to-workspace` and +//! `cycle-send-to-workspace` go to the next or the previous workspace, `focus-last-workspace`, +//! `move-to-last-workspace` and `send-to-last-workspace` to the one that was in front before, +//! `focus-workspaces` shows a workspace on every monitor, and `new-workspace` and +//! `close-workspace` add a workspace and remove an empty one. +//! - `workspace-name` names a workspace, which `focus-named-workspace`, `named-workspace-layout` +//! and `named-workspace-tiling` find by its name; `workspace-layout` and `workspace-tiling` set +//! the layout and the tiling of a workspace by its index, and `ensure-workspaces` and +//! `ensure-named-workspaces` give a monitor workspaces up to a number, or with names. //! //! `ignore-rule` and `manage-rule` add a rule that keeps an application out of the layout or //! always in it, `session-float-rule` floats the focused window and every window like it until the @@ -113,6 +122,10 @@ gen_enum_subcommand_args! { PreselectDirection: OperationDirection, CycleFocus: CycleDirection, CycleMove: CycleDirection, + CycleMoveToWorkspace: CycleDirection, + CycleSendToWorkspace: CycleDirection, + CycleWorkspace: CycleDirection, + CycleEmptyWorkspace: CycleDirection, FlipLayout: Axis, ChangeLayout: DefaultLayout, CycleLayout: CycleDirection, @@ -140,6 +153,86 @@ gen_target_subcommand_args! { MoveToWorkspace, SendToWorkspace, FocusWorkspace, + FocusWorkspaces, +} + +macro_rules! gen_named_target_subcommand_args { + // SubCommand Pattern + ( $( $name:ident ),+ $(,)? ) => { + $( + #[derive(clap::Parser)] + pub struct $name { + /// Target workspace name + workspace: String, + } + )+ + }; +} + +gen_named_target_subcommand_args! { + FocusNamedWorkspace, +} + +// Thanks to @danielhenrymantilla for showing me how to use cfg_attr with an optional argument like +// this on the Rust Programming Language Community Discord Server +macro_rules! gen_workspace_subcommand_args { + // Workspace Property: #[enum] Value Enum (if the value is an Enum) + // Workspace Property: Value Type (if the value is anything else) + ( $( $name:ident: $(#[enum] $(@$value_enum:tt)?)? $value:ty ),+ $(,)? ) => ( + pastey::paste! { + $( + #[derive(clap::Parser)] + pub struct [] { + /// Monitor index (zero-indexed) + monitor: usize, + + /// Workspace index on the specified monitor (zero-indexed) + workspace: usize, + + $(#[clap(value_enum)] $($value_enum)?)? + #[cfg_attr( + all($(FALSE $($value_enum)?)?), + doc = ""$name " of the workspace as a "$value "" + )] + value: $value, + } + )+ + } + ) +} + +gen_workspace_subcommand_args! { + Name: String, + Layout: #[enum] DefaultLayout, + Tiling: #[enum] BooleanState, +} + +macro_rules! gen_named_workspace_subcommand_args { + // Workspace Property: #[enum] Value Enum (if the value is an Enum) + // Workspace Property: Value Type (if the value is anything else) + ( $( $name:ident: $(#[enum] $(@$value_enum:tt)?)? $value:ty ),+ $(,)? ) => ( + pastey::paste! { + $( + #[derive(clap::Parser)] + pub struct [] { + /// Target workspace name + workspace: String, + + $(#[clap(value_enum)] $($value_enum)?)? + #[cfg_attr( + all($(FALSE $($value_enum)?)?), + doc = ""$name " of the workspace as a "$value "" + )] + value: $value, + } + )+ + } + ) +} + +gen_named_workspace_subcommand_args! { + Layout: #[enum] DefaultLayout, + Tiling: #[enum] BooleanState, } macro_rules! gen_focused_workspace_padding_subcommand_args { @@ -303,6 +396,22 @@ struct WorkspaceWorkAreaOffset { bottom: i32, } +#[derive(Parser)] +struct EnsureWorkspaces { + /// Monitor index (zero-indexed) + monitor: usize, + /// Number of desired workspaces + workspace_count: usize, +} + +#[derive(Parser)] +struct EnsureNamedWorkspaces { + /// Monitor index (zero-indexed) + monitor: usize, + /// Names of desired workspaces + names: Vec, +} + #[derive(Parser)] #[allow(clippy::struct_excessive_bools)] struct Start { @@ -451,12 +560,40 @@ enum SubCommand { /// Move the focused window to the specified workspace #[clap(arg_required_else_help = true)] MoveToWorkspace(MoveToWorkspace), + /// Move the focused window to the workspace in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleMoveToWorkspace(CycleMoveToWorkspace), /// Send the focused window to the specified workspace #[clap(arg_required_else_help = true)] SendToWorkspace(SendToWorkspace), + /// Send the focused window to the workspace in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleSendToWorkspace(CycleSendToWorkspace), + /// Send the focused window to the last focused monitor workspace + SendToLastWorkspace, + /// Move the focused window to the last focused monitor workspace + MoveToLastWorkspace, + /// Focus the last focused workspace on the focused monitor + FocusLastWorkspace, /// Focus the specified workspace on the focused monitor #[clap(arg_required_else_help = true)] FocusWorkspace(FocusWorkspace), + /// Focus the specified workspace on all monitors + #[clap(arg_required_else_help = true)] + FocusWorkspaces(FocusWorkspaces), + /// Focus the specified workspace + #[clap(arg_required_else_help = true)] + FocusNamedWorkspace(FocusNamedWorkspace), + /// Close the focused workspace (must be empty and unnamed) + CloseWorkspace, + /// Focus the workspace in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleWorkspace(CycleWorkspace), + /// Focus the next empty workspace in the given cycle direction (if one exists) + #[clap(arg_required_else_help = true)] + CycleEmptyWorkspace(CycleWorkspace), + /// Create and append a new workspace on the focused monitor + NewWorkspace, /// Set the resize delta (used by resize-edge and resize-axis) #[clap(arg_required_else_help = true)] ResizeDelta(ResizeDelta), @@ -514,12 +651,41 @@ enum SubCommand { PromoteWindow(PromoteWindow), /// Force the retiling of all managed windows Retile, + /// Create at least this many workspaces for the specified monitor + #[clap(arg_required_else_help = true)] + EnsureWorkspaces(EnsureWorkspaces), + /// Create these many named workspaces for the specified monitor + #[clap(arg_required_else_help = true)] + EnsureNamedWorkspaces(EnsureNamedWorkspaces), /// Set the container padding for the specified workspace #[clap(arg_required_else_help = true)] ContainerPadding(ContainerPadding), /// Set the workspace padding for the specified workspace #[clap(arg_required_else_help = true)] WorkspacePadding(WorkspacePadding), + /// Set the layout for the specified workspace + #[clap(arg_required_else_help = true)] + WorkspaceLayout(WorkspaceLayout), + /// Set the layout for the specified workspace + #[clap(arg_required_else_help = true)] + NamedWorkspaceLayout(NamedWorkspaceLayout), + // /// Set a custom layout for the specified workspace + // #[clap(hide = true)] + // #[clap(arg_required_else_help = true)] + // WorkspaceCustomLayout(WorkspaceCustomLayout), + // /// Set a custom layout for the specified workspace + // #[clap(hide = true)] + // #[clap(arg_required_else_help = true)] + // NamedWorkspaceCustomLayout(NamedWorkspaceCustomLayout), + /// Enable or disable window tiling for the specified workspace + #[clap(arg_required_else_help = true)] + WorkspaceTiling(WorkspaceTiling), + /// Enable or disable window tiling for the specified workspace + #[clap(arg_required_else_help = true)] + NamedWorkspaceTiling(NamedWorkspaceTiling), + /// Set the workspace name for the specified workspace + #[clap(arg_required_else_help = true)] + WorkspaceName(WorkspaceName), /// Toggle the paused state for all window tiling TogglePause, /// Toggle window tiling on the focused workspace @@ -703,6 +869,26 @@ fn main() -> eyre::Result<()> { SubCommand::FocusWorkspace(args) => { send_message(&SocketMessage::FocusWorkspaceNumber(args.target))?; } + SubCommand::FocusLastWorkspace => { + send_message(&SocketMessage::FocusLastWorkspace)?; + } + SubCommand::FocusWorkspaces(args) => { + send_message(&SocketMessage::FocusWorkspaceNumbers(args.target))?; + } + SubCommand::FocusNamedWorkspace(args) => { + send_message(&SocketMessage::FocusNamedWorkspace(args.workspace))?; + } + SubCommand::CloseWorkspace => { + send_message(&SocketMessage::CloseWorkspace)?; + } + SubCommand::CycleWorkspace(args) => { + send_message(&SocketMessage::CycleFocusWorkspace(args.cycle_direction))?; + } + SubCommand::CycleEmptyWorkspace(args) => { + send_message(&SocketMessage::CycleFocusEmptyWorkspace( + args.cycle_direction, + ))?; + } SubCommand::ToggleFloat => { send_message(&SocketMessage::ToggleFloat)?; } @@ -715,9 +901,25 @@ fn main() -> eyre::Result<()> { SubCommand::MoveToWorkspace(args) => { send_message(&SocketMessage::MoveContainerToWorkspaceNumber(args.target))?; } + SubCommand::CycleMoveToWorkspace(args) => { + send_message(&SocketMessage::CycleMoveContainerToWorkspace( + args.cycle_direction, + ))?; + } SubCommand::SendToWorkspace(args) => { send_message(&SocketMessage::SendContainerToWorkspaceNumber(args.target))?; } + SubCommand::CycleSendToWorkspace(args) => { + send_message(&SocketMessage::CycleSendContainerToWorkspace( + args.cycle_direction, + ))?; + } + SubCommand::MoveToLastWorkspace => { + send_message(&SocketMessage::MoveContainerToLastWorkspace)?; + } + SubCommand::SendToLastWorkspace => { + send_message(&SocketMessage::SendContainerToLastWorkspace)?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } @@ -781,6 +983,16 @@ fn main() -> eyre::Result<()> { SubCommand::ManageRule(args) => { send_message(&SocketMessage::ManageRule(args.identifier, args.id))?; } + SubCommand::NewWorkspace => { + send_message(&SocketMessage::NewWorkspace)?; + } + SubCommand::WorkspaceName(name) => { + send_message(&SocketMessage::WorkspaceName( + name.monitor, + name.workspace, + name.value, + ))?; + } SubCommand::ResizeDelta(args) => { send_message(&SocketMessage::ResizeDelta(args.pixels))?; } @@ -848,6 +1060,33 @@ fn main() -> eyre::Result<()> { args.adjustment, ))?; } + SubCommand::WorkspaceLayout(args) => { + send_message(&SocketMessage::WorkspaceLayout( + args.monitor, + args.workspace, + args.value, + ))?; + } + SubCommand::NamedWorkspaceLayout(args) => { + send_message(&SocketMessage::NamedWorkspaceLayout( + args.workspace, + args.value, + ))?; + } + + SubCommand::WorkspaceTiling(args) => { + send_message(&SocketMessage::WorkspaceTiling( + args.monitor, + args.workspace, + args.value.into(), + ))?; + } + SubCommand::NamedWorkspaceTiling(args) => { + send_message(&SocketMessage::NamedWorkspaceTiling( + args.workspace, + args.value.into(), + ))?; + } SubCommand::ScrollingLayoutColumns(args) => { send_message(&SocketMessage::ScrollingLayoutColumns(args.count))?; } @@ -860,6 +1099,18 @@ fn main() -> eyre::Result<()> { send_message(&SocketMessage::LayoutRatios(args.columns, args.rows))?; } } + SubCommand::EnsureWorkspaces(workspaces) => { + send_message(&SocketMessage::EnsureWorkspaces( + workspaces.monitor, + workspaces.workspace_count, + ))?; + } + SubCommand::EnsureNamedWorkspaces(args) => { + send_message(&SocketMessage::EnsureNamedWorkspaces( + args.monitor, + args.names, + ))?; + } SubCommand::UnmanagedWindowOperationBehaviour(args) => { send_message(&SocketMessage::UnmanagedWindowOperationBehaviour( args.operation_behaviour, diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 414670d2..3b98916f 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -440,6 +440,80 @@ fn the_workspace_subcommands_send_the_index_they_are_given() { ); } +#[test] +fn the_other_workspace_subcommands_send_what_they_are_given() { + sends( + &["cycle-workspace", "next"], + r#"{"type":"CycleFocusWorkspace","content":"Next"}"#, + ); + sends( + &["cycle-empty-workspace", "previous"], + r#"{"type":"CycleFocusEmptyWorkspace","content":"Previous"}"#, + ); + sends( + &["cycle-move-to-workspace", "next"], + r#"{"type":"CycleMoveContainerToWorkspace","content":"Next"}"#, + ); + sends( + &["cycle-send-to-workspace", "previous"], + r#"{"type":"CycleSendContainerToWorkspace","content":"Previous"}"#, + ); + sends( + &["focus-last-workspace"], + r#"{"type":"FocusLastWorkspace"}"#, + ); + sends( + &["move-to-last-workspace"], + r#"{"type":"MoveContainerToLastWorkspace"}"#, + ); + sends( + &["send-to-last-workspace"], + r#"{"type":"SendContainerToLastWorkspace"}"#, + ); + sends( + &["focus-workspaces", "2"], + r#"{"type":"FocusWorkspaceNumbers","content":2}"#, + ); + sends(&["new-workspace"], r#"{"type":"NewWorkspace"}"#); + sends(&["close-workspace"], r#"{"type":"CloseWorkspace"}"#); +} + +#[test] +fn the_named_workspace_subcommands_send_the_names_they_are_given() { + sends( + &["workspace-name", "0", "1", "mail"], + r#"{"type":"WorkspaceName","content":[0,1,"mail"]}"#, + ); + sends( + &["focus-named-workspace", "mail"], + r#"{"type":"FocusNamedWorkspace","content":"mail"}"#, + ); + sends( + &["ensure-workspaces", "0", "3"], + r#"{"type":"EnsureWorkspaces","content":[0,3]}"#, + ); + sends( + &["ensure-named-workspaces", "0", "web", "code"], + r#"{"type":"EnsureNamedWorkspaces","content":[0,["web","code"]]}"#, + ); + sends( + &["workspace-layout", "0", "1", "columns"], + r#"{"type":"WorkspaceLayout","content":[0,1,"Columns"]}"#, + ); + sends( + &["named-workspace-layout", "mail", "rows"], + r#"{"type":"NamedWorkspaceLayout","content":["mail","Rows"]}"#, + ); + sends( + &["workspace-tiling", "0", "1", "disable"], + r#"{"type":"WorkspaceTiling","content":[0,1,false]}"#, + ); + sends( + &["named-workspace-tiling", "mail", "enable"], + r#"{"type":"NamedWorkspaceTiling","content":["mail",true]}"#, + ); +} + #[test] fn without_a_daemon_a_question_fails() { let runtime = Runtime::new(); @@ -484,15 +558,25 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "cancel-preselect.md", "change-layout.md", "clear-session-float-rules.md", + "close-workspace.md", "close.md", "completions.md", "container-padding.md", + "cycle-empty-workspace.md", "cycle-focus.md", "cycle-layout.md", + "cycle-move-to-workspace.md", "cycle-move.md", + "cycle-send-to-workspace.md", + "cycle-workspace.md", "data-directory.md", + "ensure-named-workspaces.md", + "ensure-workspaces.md", "flip-layout.md", + "focus-last-workspace.md", + "focus-named-workspace.md", "focus-workspace.md", + "focus-workspaces.md", "focus.md", "focused-workspace-container-padding.md", "focused-workspace-padding.md", @@ -508,8 +592,12 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "monitor-information.md", "monitor-work-area-offset.md", "mouse-follows-focus.md", + "move-to-last-workspace.md", "move-to-workspace.md", "move.md", + "named-workspace-layout.md", + "named-workspace-tiling.md", + "new-workspace.md", "preselect-direction.md", "promote-focus.md", "promote-swap.md", @@ -524,6 +612,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "retile.md", "save-resize.md", "scrolling-layout-columns.md", + "send-to-last-workspace.md", "send-to-workspace.md", "session-float-rule.md", "session-float-rules.md", @@ -540,7 +629,10 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "unmanage.md", "unmanaged-window-operation-behaviour.md", "unsubscribe-socket.md", + "workspace-layout.md", + "workspace-name.md", "workspace-padding.md", + "workspace-tiling.md", "workspace-work-area-offset.md", ] ); diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index f13df547..e57dd17a 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -192,12 +192,43 @@ toggle-tiling toggle-tiling toggle-pause toggle-pause +ensure-named-workspaces 0 one two three +workspace-name 0 0 one +ensure-workspaces 0 3 +workspace-tiling 0 0 disable +workspace-tiling 0 0 enable +named-workspace-tiling one disable +named-workspace-tiling one enable focus-workspace 1 focus-workspace 0 +focus-last-workspace +focus-last-workspace +focus-workspaces 1 +focus-workspaces 0 +cycle-workspace next +cycle-workspace previous +cycle-empty-workspace next +focus-workspace 0 +focus-named-workspace two +focus-named-workspace one send-to-workspace 1 focus-workspace 1 move-to-workspace 0 focus-workspace 0 +cycle-send-to-workspace next +focus-workspace 1 +cycle-move-to-workspace previous +focus-workspace 0 +send-to-last-workspace +move-to-last-workspace +focus-workspace 0 +new-workspace +close-workspace +focus-workspace 0 +workspace-layout 0 0 columns +workspace-layout 0 0 bsp +named-workspace-layout one columns +named-workspace-layout one bsp global-work-area-offset 10 10 20 20 global-work-area-offset 0 0 0 0 monitor-work-area-offset 0 10 10 20 20 @@ -331,6 +362,7 @@ for query in [ "focused-workspace-index", "focused-container-index", "focused-window-index", + "focused-workspace-name", "focused-workspace-layout", "focused-container-kind", "version", From 189aeb1005397812e76ff255e570e5c919ad7bc8 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 18:05:12 -0700 Subject: [PATCH 031/255] feat(wm): more than one monitor Every monitor has workspaces of its own, which KWin's per-output desktops show independently, so a second monitor is mostly the window manager's business: which monitor has the focus, and how a window gets from one to the other. At the edge of a monitor, focus and move now cross to the monitor on that side, where they used to fail with "there is no container in this direction": the focus lands on the container nearest the monitor it came from, and a move swaps with the container at that edge (cross-monitor-move-behaviour insert puts it in among the containers there, no-op keeps it). A window that opens or gets the focus on a monitor that is not the focused one focuses that monitor, which also makes the scrolling test of a strip next to another monitor guard real code. The monitor commands come with it: focusing a monitor by index, in order or under the pointer, a workspace of another monitor, moving and sending the focused window to another monitor, to a workspace of it or to a named workspace (in the window manager these are moves between monitors, so they were left out of the workspace commands), moving and swapping workspaces between monitors, and a display index preference that keeps a monitor at the index the user gives it. eager-focus focuses the first window of an executable on any workspace of any monitor; its window is found in a container or among the floating windows, the two places a window can be until stacks, monocle and maximize exist. --- README.md | 3 + docs/cli/cross-monitor-move-behaviour.md | 19 + docs/cli/cycle-monitor.md | 14 + docs/cli/cycle-move-to-monitor.md | 14 + docs/cli/cycle-move-workspace-to-monitor.md | 14 + docs/cli/cycle-send-to-monitor.md | 14 + docs/cli/display-index-preference.md | 17 + docs/cli/eager-focus.md | 14 + docs/cli/focus-monitor-at-cursor.md | 10 + docs/cli/focus-monitor-workspace.md | 17 + docs/cli/focus-monitor.md | 14 + docs/cli/move-to-monitor-workspace.md | 17 + docs/cli/move-to-monitor.md | 14 + docs/cli/move-to-named-workspace.md | 14 + docs/cli/move-workspace-to-monitor.md | 14 + docs/cli/send-to-monitor-workspace.md | 17 + docs/cli/send-to-monitor.md | 14 + docs/cli/send-to-named-workspace.md | 14 + docs/cli/swap-workspaces-with-monitor.md | 14 + .../toggle-cross-monitor-move-behaviour.md | 10 + docs/dev/ARCHITECTURE.md | 43 +- docs/usage/focusing-windows.md | 17 +- docs/usage/moving-windows.md | 30 +- komorebi-client/src/lib.rs | 4 +- komorebi/src/container.rs | 13 + komorebi/src/core/mod.rs | 19 + komorebi/src/desktop.rs | 83 +- komorebi/src/lib.rs | 9 +- komorebi/src/monitor.rs | 44 + komorebi/src/process_command.rs | 258 ++- komorebi/src/process_event.rs | 10 + komorebi/src/state.rs | 10 + komorebi/src/window.rs | 28 + komorebi/src/window_manager.rs | 1575 ++++++++++++++++- komorebi/src/workspace.rs | 36 + komorebi/tests/focus.rs | 4 +- komorebi/tests/monitors.rs | 402 +++++ komorebi/tests/moving.rs | 4 +- komorebic/src/main.rs | 199 +++ komorebic/tests/cli.rs | 99 ++ nix/tests/vm/suites/commands/test.py | 35 + 41 files changed, 3172 insertions(+), 28 deletions(-) create mode 100644 docs/cli/cross-monitor-move-behaviour.md create mode 100644 docs/cli/cycle-monitor.md create mode 100644 docs/cli/cycle-move-to-monitor.md create mode 100644 docs/cli/cycle-move-workspace-to-monitor.md create mode 100644 docs/cli/cycle-send-to-monitor.md create mode 100644 docs/cli/display-index-preference.md create mode 100644 docs/cli/eager-focus.md create mode 100644 docs/cli/focus-monitor-at-cursor.md create mode 100644 docs/cli/focus-monitor-workspace.md create mode 100644 docs/cli/focus-monitor.md create mode 100644 docs/cli/move-to-monitor-workspace.md create mode 100644 docs/cli/move-to-monitor.md create mode 100644 docs/cli/move-to-named-workspace.md create mode 100644 docs/cli/move-workspace-to-monitor.md create mode 100644 docs/cli/send-to-monitor-workspace.md create mode 100644 docs/cli/send-to-monitor.md create mode 100644 docs/cli/send-to-named-workspace.md create mode 100644 docs/cli/swap-workspaces-with-monitor.md create mode 100644 docs/cli/toggle-cross-monitor-move-behaviour.md create mode 100644 komorebi/tests/monitors.rs diff --git a/README.md b/README.md index 8d1a7d0b..0f402fe3 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,9 @@ without showing it; their `cycle-` and `-last-workspace` forms go to the next, the previous or the last workspace, `workspace-name` names a workspace for `focus-named-workspace` and the other named commands, and `new-workspace` and `close-workspace` add and remove one. +At the edge of a monitor, `focus` and `move` cross to the monitor on that side; +`focus-monitor`, `move-to-monitor`, `send-to-monitor` and their kind work on the +monitors, and `eager-focus` finds the window of an application wherever it is. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/cross-monitor-move-behaviour.md b/docs/cli/cross-monitor-move-behaviour.md new file mode 100644 index 00000000..aa3dbfb2 --- /dev/null +++ b/docs/cli/cross-monitor-move-behaviour.md @@ -0,0 +1,19 @@ +```text +Set the behaviour when moving windows across monitor boundaries + +Usage: cross-monitor-move-behaviour + +Arguments: + + Possible values: + - swap: Swap the window container with the window container at the edge of the adjacent + monitor + - insert: Insert the window container into the focused workspace on the adjacent monitor + - no-op: Do nothing if trying to move a window container in the direction of an adjacent + monitor + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/cycle-monitor.md b/docs/cli/cycle-monitor.md new file mode 100644 index 00000000..5ff4e41b --- /dev/null +++ b/docs/cli/cycle-monitor.md @@ -0,0 +1,14 @@ +```text +Focus the monitor in the given cycle direction + +Usage: cycle-monitor + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-move-to-monitor.md b/docs/cli/cycle-move-to-monitor.md new file mode 100644 index 00000000..66e561a3 --- /dev/null +++ b/docs/cli/cycle-move-to-monitor.md @@ -0,0 +1,14 @@ +```text +Move the focused window to the monitor in the given cycle direction + +Usage: cycle-move-to-monitor + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-move-workspace-to-monitor.md b/docs/cli/cycle-move-workspace-to-monitor.md new file mode 100644 index 00000000..e7b5353b --- /dev/null +++ b/docs/cli/cycle-move-workspace-to-monitor.md @@ -0,0 +1,14 @@ +```text +Move the focused workspace monitor in the given cycle direction + +Usage: cycle-move-workspace-to-monitor + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-send-to-monitor.md b/docs/cli/cycle-send-to-monitor.md new file mode 100644 index 00000000..e872f961 --- /dev/null +++ b/docs/cli/cycle-send-to-monitor.md @@ -0,0 +1,14 @@ +```text +Send the focused window to the monitor in the given cycle direction + +Usage: cycle-send-to-monitor + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/display-index-preference.md b/docs/cli/display-index-preference.md new file mode 100644 index 00000000..fa39695b --- /dev/null +++ b/docs/cli/display-index-preference.md @@ -0,0 +1,17 @@ +```text +Set the display index preference for a monitor identified using its display name + +Usage: display-index-preference + +Arguments: + + Preferred monitor index (zero-indexed) + + + Display name as identified in komorebic state + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/eager-focus.md b/docs/cli/eager-focus.md new file mode 100644 index 00000000..826abe1d --- /dev/null +++ b/docs/cli/eager-focus.md @@ -0,0 +1,14 @@ +```text +Focus the first managed window matching the given executable + +Usage: eager-focus + +Arguments: + + Case-sensitive exe identifier + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-monitor-at-cursor.md b/docs/cli/focus-monitor-at-cursor.md new file mode 100644 index 00000000..dba13349 --- /dev/null +++ b/docs/cli/focus-monitor-at-cursor.md @@ -0,0 +1,10 @@ +```text +Focus the monitor at the current cursor location + +Usage: focus-monitor-at-cursor + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-monitor-workspace.md b/docs/cli/focus-monitor-workspace.md new file mode 100644 index 00000000..c20cbb22 --- /dev/null +++ b/docs/cli/focus-monitor-workspace.md @@ -0,0 +1,17 @@ +```text +Focus the specified workspace on the target monitor + +Usage: focus-monitor-workspace + +Arguments: + + Target monitor index (zero-indexed) + + + Workspace index on the target monitor (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-monitor.md b/docs/cli/focus-monitor.md new file mode 100644 index 00000000..28bc26d6 --- /dev/null +++ b/docs/cli/focus-monitor.md @@ -0,0 +1,14 @@ +```text +Focus the specified monitor + +Usage: focus-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-to-monitor-workspace.md b/docs/cli/move-to-monitor-workspace.md new file mode 100644 index 00000000..cab10d66 --- /dev/null +++ b/docs/cli/move-to-monitor-workspace.md @@ -0,0 +1,17 @@ +```text +Move the focused window to the specified monitor workspace + +Usage: move-to-monitor-workspace + +Arguments: + + Target monitor index (zero-indexed) + + + Workspace index on the target monitor (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-to-monitor.md b/docs/cli/move-to-monitor.md new file mode 100644 index 00000000..fe9f95f8 --- /dev/null +++ b/docs/cli/move-to-monitor.md @@ -0,0 +1,14 @@ +```text +Move the focused window to the specified monitor + +Usage: move-to-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-to-named-workspace.md b/docs/cli/move-to-named-workspace.md new file mode 100644 index 00000000..8233cbb7 --- /dev/null +++ b/docs/cli/move-to-named-workspace.md @@ -0,0 +1,14 @@ +```text +Move the focused window to the specified workspace + +Usage: move-to-named-workspace + +Arguments: + + Target workspace name + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-workspace-to-monitor.md b/docs/cli/move-workspace-to-monitor.md new file mode 100644 index 00000000..c1f3148d --- /dev/null +++ b/docs/cli/move-workspace-to-monitor.md @@ -0,0 +1,14 @@ +```text +Move the focused workspace to the specified monitor + +Usage: move-workspace-to-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/send-to-monitor-workspace.md b/docs/cli/send-to-monitor-workspace.md new file mode 100644 index 00000000..213303ea --- /dev/null +++ b/docs/cli/send-to-monitor-workspace.md @@ -0,0 +1,17 @@ +```text +Send the focused window to the specified monitor workspace + +Usage: send-to-monitor-workspace + +Arguments: + + Target monitor index (zero-indexed) + + + Workspace index on the target monitor (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/send-to-monitor.md b/docs/cli/send-to-monitor.md new file mode 100644 index 00000000..5ae3ae21 --- /dev/null +++ b/docs/cli/send-to-monitor.md @@ -0,0 +1,14 @@ +```text +Send the focused window to the specified monitor + +Usage: send-to-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/send-to-named-workspace.md b/docs/cli/send-to-named-workspace.md new file mode 100644 index 00000000..75cea540 --- /dev/null +++ b/docs/cli/send-to-named-workspace.md @@ -0,0 +1,14 @@ +```text +Send the focused window to the specified workspace + +Usage: send-to-named-workspace + +Arguments: + + Target workspace name + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/swap-workspaces-with-monitor.md b/docs/cli/swap-workspaces-with-monitor.md new file mode 100644 index 00000000..c4c8bebe --- /dev/null +++ b/docs/cli/swap-workspaces-with-monitor.md @@ -0,0 +1,14 @@ +```text +Swap focused monitor workspaces with specified monitor + +Usage: swap-workspaces-with-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-cross-monitor-move-behaviour.md b/docs/cli/toggle-cross-monitor-move-behaviour.md new file mode 100644 index 00000000..a5c8900b --- /dev/null +++ b/docs/cli/toggle-cross-monitor-move-behaviour.md @@ -0,0 +1,10 @@ +```text +Toggle the behaviour when moving windows across monitor boundaries + +Usage: toggle-cross-monitor-move-behaviour + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 906490c4..07dc1607 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -304,7 +304,10 @@ direction, both from `komorebi-layouts`: `FocusWindow` and `CycleFocusWindow` focus another container of the focused workspace and give its window the focus with the backend's `focus` ([`WindowManager::focus_container_in_direction`], [`WindowManager::focus_container_in_cycle_direction`]). They retile nothing. When there is no -container in that direction, the message fails and changes nothing. Whether the pointer follows +container in that direction, the focus goes to the monitor in that direction +([`WindowManager::monitor_idx_in_direction`], from the bounds of the monitors), to its container +nearest the monitor the focus came from (the leftmost one going right); with no monitor there +either, the message fails and changes nothing. Whether the pointer follows the focus is [`WindowManager::mouse_follows_focus`], which `MouseFollowsFocus` and `ToggleMouseFollowsFocus` set. @@ -313,8 +316,13 @@ direction ([`WindowManager::move_container_in_direction`], [`WindowManager::move_container_in_cycle_direction`]), and tile the workspace again: the window that moved takes the other's tile, keeps the focus, and the pointer follows it. The swap goes through `LockableSequence`, so a lock stays with its index: the container swapped onto a locked -index is locked in its place. When there is no container in that direction, the message fails -and nothing moves. +index is locked in its place. When there is no container in that direction, the container goes +to the monitor in that direction ([`WindowManager::move_container_to_monitor`]), and +[`WindowManager::cross_monitor_move_behaviour`] says what it does there: by default (`Swap`) the +container at that edge of the other monitor comes back in its place, `Insert` puts it in among +the containers there, and `NoOp` keeps it where it is. With no monitor in that direction, the +message fails and nothing moves. [`WindowManager::cross_boundary_behaviour`] can make both cross +to the next workspace of the same monitor instead. `ChangeLayout` and `CycleLayout` set the focused workspace's [`Layout`], and `FlipLayout` mirrors it along an axis, on top of the flip it has ([`Workspace::layout_flip`]); each tiles @@ -438,6 +446,21 @@ gives a monitor workspaces up to a number, and `CloseWorkspace` removes the work when it has no window and no name and is not the monitor's last. A name is komorebi's: the compositor's desktops keep theirs. +A window the compositor reports shown or focused on a monitor that is not the focused one +focuses that monitor ([`WindowManager::monitor_idx_from_window`]). The monitor commands work on +the ring of monitors: `FocusMonitorNumber`, `CycleFocusMonitor` and `FocusMonitorAtCursor` focus +one ([`WindowManager::focus_monitor`]), and `FocusMonitorWorkspaceNumber` a workspace of it; +`MoveContainerToMonitorNumber`, `SendContainerToMonitorNumber`, their cycle and monitor-workspace +forms, and `MoveContainerToNamedWorkspace` and `SendContainerToNamedWorkspace` take the focused +container to another monitor, put its windows on the desktop of the workspace they go to, and tile +both monitors ([`WindowManager::move_container_to_monitor`]); `MoveWorkspaceToMonitorNumber` and +`CycleMoveWorkspaceToMonitor` take the workspace in front to another monitor, and +`SwapWorkspacesToMonitorNumber` exchanges the workspaces of two monitors. +`DisplayIndexPreference` gives a monitor, by its serial number id, the index the window manager +puts it at when it loads the monitors, with placeholders before it while the monitors in between +are not connected. `EagerFocus` focuses the first window of an executable, searching every +workspace of every monitor, and shows its workspace. + `PreselectDirection` reserves the index on one side of the focused container for the next window ([`WindowManager::preselect_container_in_direction`]). The workspace inserts an empty container there ([`Container::preselect`]), which [`Workspace::update`] keeps and the layout @@ -499,7 +522,8 @@ module's unit. promote the focused container, float a window, lock a container, set the padding of a workspace, manage and unmanage a window, show a workspace, move a container to another workspace, follow a workspace switch made by something else, name a workspace and find - it by its name, set the layout of a workspace that is not in front). + it by its name, set the layout of a workspace that is not in front, focus another monitor, + and move containers and workspaces between monitors). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -602,6 +626,8 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | komorebi's own switch or move, reported back by KWin, changes nothing | framework path: the table records a switch and a move when it makes their commands | `the_compositor_reporting_komorebis_own_switch_changes_nothing`, `komorebis_own_move_coming_back_as_an_event_moves_nothing`, `komorebi_switching_a_monitor_comes_back_as_a_change_to_what_it_already_knows` | none | | The user's `kwinrc` gets back the value komorebi changed, also after a crash | framework path: [`Kwinrc`] records the first value of a key in a backup file, and the backend's `shutdown` puts it back | `what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed`, `a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run`, `vm-workspace-switch` ("back as they were") | `SIGKILL`: the next run puts it back when it stops | | A workspace is closed only when it has no window and no name and is not the monitor's last | framework path: the `CloseWorkspace` arm of [`WindowManager::process_command`] checks all three | `new_workspace_adds_one_and_close_workspace_removes_it_when_it_is_empty_and_unnamed` | none | +| The focus and a move at the edge of a monitor go to the monitor on that side, and fail only when there is none | framework path: the `None` arms of [`WindowManager::focus_container_in_direction`] and [`WindowManager::move_container_in_direction`] | `the_focus_crosses_to_the_monitor_on_that_side`, `a_move_at_the_edge_of_a_monitor_swaps_with_the_window_on_the_next_one_by_default`, `focus_towards_a_side_with_no_window_is_an_error_and_changes_nothing` | `NoOp` keeps a move on its monitor | +| A window shown or focused on another monitor focuses that monitor, and nothing else does | framework path: `handle_event` focuses the monitor of a `Show` or `FocusChange` before it acts on it | `a_window_that_opens_on_the_monitor_that_is_not_focused_focuses_it`, `a_scrolling_strip_on_the_next_monitor_over_does_not_take_focus_with_it` | none | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | 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 | @@ -735,7 +761,9 @@ A window is shown, and ends up on a tile: - [`komorebi/tests/workspaces.rs`](../../komorebi/tests/workspaces.rs): workspaces as the fake's desktops; [`komorebi/tests/workspace_commands.rs`](../../komorebi/tests/workspace_commands.rs), naming, - cycling and the other workspace commands; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the + cycling and the other workspace commands; + [`komorebi/tests/monitors.rs`](../../komorebi/tests/monitors.rs), two monitors: crossing from + one to the other, the monitor commands and `EagerFocus`; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the `kwinrc` editor and its tests. - [`nix/tests/vm/suites/workspace-switch`](../../nix/tests/vm/suites/workspace-switch/test.py): workspaces as a real KWin's desktops, switched by `komorebic` and by KWin; @@ -832,6 +860,11 @@ A window is shown, and ends up on a tile: [`WindowManager::move_container_to_workspace`]: ../../komorebi/src/window_manager.rs [`WindowManager::monitor_workspace_index_by_name`]: ../../komorebi/src/window_manager.rs [`WindowManager::focus_monitor`]: ../../komorebi/src/window_manager.rs +[`WindowManager::monitor_idx_in_direction`]: ../../komorebi/src/window_manager.rs +[`WindowManager::monitor_idx_from_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::move_container_to_monitor`]: ../../komorebi/src/window_manager.rs +[`WindowManager::cross_monitor_move_behaviour`]: ../../komorebi/src/window_manager.rs +[`WindowManager::cross_boundary_behaviour`]: ../../komorebi/src/window_manager.rs [`Monitor::focus_workspace`]: ../../komorebi/src/monitor.rs [`bridge.js`]: ../../komorebi/src/kwin/bridge.js [`kwin-api.d.ts`]: ../../komorebi/src/kwin/kwin-api.d.ts diff --git a/docs/usage/focusing-windows.md b/docs/usage/focusing-windows.md index ee9ed845..c582636f 100644 --- a/docs/usage/focusing-windows.md +++ b/docs/usage/focusing-windows.md @@ -18,8 +18,21 @@ komorebic focus up komorebic focus right ``` -When there is no tile on that side, nothing happens, and the daemon logs "there is no container -in this direction". +When there is no tile on that side, the focus goes to the monitor on that side, if there is one, +to the tile nearest the monitor the focus came from: `focus right` lands on the leftmost tile of +the monitor on the right. With no monitor there either, nothing happens, and the daemon logs +"there is no container or monitor in this direction". + +[`komorebic focus-monitor`](../cli/focus-monitor.md) focuses a monitor by its index, +[`komorebic cycle-monitor`](../cli/cycle-monitor.md) the next or the previous one, and +[`komorebic focus-monitor-at-cursor`](../cli/focus-monitor-at-cursor.md) the one the pointer is +on. [`komorebic eager-focus`](../cli/eager-focus.md) focuses the first window komorebi manages of +an executable, whichever workspace of whichever monitor it is on, and shows its workspace. + +```sh +komorebic focus-monitor 1 +komorebic eager-focus firefox +``` ## In order diff --git a/docs/usage/moving-windows.md b/docs/usage/moving-windows.md index 4a8ff2c1..62b4db47 100644 --- a/docs/usage/moving-windows.md +++ b/docs/usage/moving-windows.md @@ -18,8 +18,34 @@ komorebic move up komorebic move right ``` -When there is no tile on that side, nothing moves, and the daemon logs "there is no container -in this direction". +When there is no tile on that side, the window goes to the monitor on that side, if there is one, +and takes the place nearest the monitor it came from. What it does there is +[`komorebic cross-monitor-move-behaviour`](../cli/cross-monitor-move-behaviour.md): `swap`, the +default, sends the window it takes the place of back to where it came from; `insert` puts it in +among the windows there; `no-op` keeps it where it is. +[`komorebic toggle-cross-monitor-move-behaviour`](../cli/toggle-cross-monitor-move-behaviour.md) +switches between `insert` and `swap`. With no monitor on that side, nothing moves, and the daemon +logs "there is no container or monitor in this direction". + +## To another monitor + +[`komorebic move-to-monitor`](../cli/move-to-monitor.md) takes the focused window to a monitor, by +its index, and focuses it there; [`komorebic send-to-monitor`](../cli/send-to-monitor.md) does the +same and leaves the focus on the monitor it came from. Their `cycle-` forms take the next or the +previous monitor. [`komorebic move-to-monitor-workspace`](../cli/move-to-monitor-workspace.md) and +[`komorebic send-to-monitor-workspace`](../cli/send-to-monitor-workspace.md) name a workspace of +that monitor too, and [`komorebic move-to-named-workspace`](../cli/move-to-named-workspace.md) and +[`komorebic send-to-named-workspace`](../cli/send-to-named-workspace.md) find it by its name. + +```sh +komorebic move-to-monitor 1 +komorebic send-to-monitor-workspace 1 2 +``` + +[`komorebic move-workspace-to-monitor`](../cli/move-workspace-to-monitor.md) takes the whole +workspace in front to another monitor, and +[`komorebic swap-workspaces-with-monitor`](../cli/swap-workspaces-with-monitor.md) exchanges the +workspaces of the focused monitor with those of another. ## In order diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index 699ebbc3..a0c037b7 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -198,7 +198,7 @@ where /// # let daemon = std::thread::spawn(move || -> std::io::Result<()> { /// # let (mut stream, _) = listener.accept()?; /// # BufReader::new(stream.try_clone()?).read_line(&mut String::new())?; -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// # stream.write_all(state.as_bytes()) /// # }); /// use komorebi_client::SocketMessage; @@ -260,7 +260,7 @@ pub fn send_query(message: &SocketMessage) -> std::io::Result { /// # let mut message = String::new(); /// # BufReader::new(stream).read_line(&mut message)?; /// # let subscriber = komorebi_client::DATA_DIR.join("bar.sock"); -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// # let notification = format!(r#"{{"event":{message},"state":{state}}}"#); /// # std::os::unix::net::UnixStream::connect(subscriber)?.write_all(notification.as_bytes())?; /// # Ok(message) diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs index b7176388..e35450ee 100644 --- a/komorebi/src/container.rs +++ b/komorebi/src/container.rs @@ -62,6 +62,19 @@ impl Container { self.id == "PRESELECT" } + /// The index of the first window of the executable `exe` in this container + pub fn idx_from_exe(&self, exe: &str) -> Option { + for (idx, window) in self.windows().iter().enumerate() { + if let Some(window_exe) = window.exe() + && exe == window_exe + { + return Option::from(idx); + } + } + + None + } + pub fn contains_window(&self, window_id: u32) -> bool { for window in self.windows() { if window.id == window_id { diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index e8d78060..f33eae60 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -351,10 +351,21 @@ pub enum SocketMessage { ResizeWindowAxis(Axis, Sizing), MoveContainerToLastWorkspace, SendContainerToLastWorkspace, + MoveContainerToMonitorNumber(usize), + CycleMoveContainerToMonitor(CycleDirection), MoveContainerToWorkspaceNumber(usize), + MoveContainerToNamedWorkspace(String), CycleMoveContainerToWorkspace(CycleDirection), + SendContainerToMonitorNumber(usize), + CycleSendContainerToMonitor(CycleDirection), SendContainerToWorkspaceNumber(usize), CycleSendContainerToWorkspace(CycleDirection), + SendContainerToMonitorWorkspaceNumber(usize, usize), + MoveContainerToMonitorWorkspaceNumber(usize, usize), + SendContainerToNamedWorkspace(String), + CycleMoveWorkspaceToMonitor(CycleDirection), + MoveWorkspaceToMonitorNumber(usize), + SwapWorkspacesToMonitorNumber(usize), // ForceFocus, Close, Minimize, @@ -362,10 +373,13 @@ pub enum SocketMessage { PromoteSwap, PromoteFocus, PromoteWindow(OperationDirection), + EagerFocus(String), LockMonitorWorkspaceContainer(usize, usize, usize), UnlockMonitorWorkspaceContainer(usize, usize, usize), ToggleLock, ToggleFloat, + ToggleCrossMonitorMoveBehaviour, + CrossMonitorMoveBehaviour(MoveBehaviour), UnmanagedWindowOperationBehaviour(OperationBehaviour), // Current Workspace Commands ManageFocusedWindow, @@ -380,6 +394,7 @@ pub enum SocketMessage { FlipLayout(Axis), // Monitor and Workspace Commands // MonitorIndexPreference(usize, i32, i32, i32, i32), + DisplayIndexPreference(usize, String), EnsureWorkspaces(usize, usize), EnsureNamedWorkspaces(usize, Vec), NewWorkspace, @@ -392,12 +407,16 @@ pub enum SocketMessage { QuickLoad, Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf), Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + CycleFocusMonitor(CycleDirection), CycleFocusWorkspace(CycleDirection), CycleFocusEmptyWorkspace(CycleDirection), + FocusMonitorNumber(usize), + FocusMonitorAtCursor, FocusLastWorkspace, CloseWorkspace, FocusWorkspaceNumber(usize), FocusWorkspaceNumbers(usize), + FocusMonitorWorkspaceNumber(usize, usize), FocusNamedWorkspace(String), ContainerPadding(usize, usize, i32), FocusedWorkspaceContainerPadding(i32), diff --git a/komorebi/src/desktop.rs b/komorebi/src/desktop.rs index cf579a49..45725a4b 100644 --- a/komorebi/src/desktop.rs +++ b/komorebi/src/desktop.rs @@ -36,6 +36,7 @@ #![deny(missing_docs)] +use crate::DISPLAY_INDEX_PREFERENCES; use crate::backend::backend; use crate::container::Container; use crate::core::Rect; @@ -44,6 +45,7 @@ use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; use color_eyre::eyre; +use std::collections::HashMap; fn contains_point(area: &Rect, x: i32, y: i32) -> bool { x >= area.left && x < area.left + area.right && y >= area.top && y < area.top + area.bottom @@ -86,11 +88,14 @@ pub fn latest_monitor_information() -> eyre::Result> { .collect()) } -/// Adds the monitors the window manager does not have yet, after the ones it has, in the -/// backend's order. +/// Adds the monitors the window manager does not have yet, and rebuilds the map from the indices +/// the user gives monitors to the window manager's ([`WindowManager::monitor_usr_idx_map`]). /// -/// A monitor is known when the window manager has one with the same serial number id, so -/// loading twice adds nothing the second time, and a known monitor keeps its workspaces. +/// A monitor the user gave an index to (`DisplayIndexPreference`) is put at that index, with +/// placeholders before it while the monitors in between are not there; any other new monitor goes +/// after the ones the window manager has, in the backend's order. A monitor is known when the +/// window manager has one with the same serial number id, so loading twice adds nothing the +/// second time, and a known monitor keeps its workspaces. /// /// # Errors /// @@ -127,6 +132,7 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { let all_devices = latest_monitor_information()?; let monitors = &mut wm.monitors; + let monitor_usr_idx_map = &mut wm.monitor_usr_idx_map; 'read: for device in all_devices { for monitor in monitors.elements() { @@ -135,7 +141,74 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { } } - monitors.elements_mut().push_back(device); + let m = device.clone(); + + let mut index_preference = None; + let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + for (index, id) in &*display_index_preferences { + if m.serial_number_id.eq(id) { + index_preference = Option::from(index); + } + } + + if let Some(preference) = index_preference { + while *preference >= monitors.elements().len() { + monitors.elements_mut().push_back(Monitor::placeholder()); + } + + let current_serial_id = monitors + .elements_mut() + .get(*preference) + .map_or("", |m| &m.serial_number_id); + if current_serial_id == "PLACEHOLDER" { + let _ = monitors.elements_mut().remove(*preference); + monitors.elements_mut().insert(*preference, m); + } else { + monitors.elements_mut().insert(*preference, m); + } + } else { + monitors.elements_mut().push_back(m); + } + } + + monitors + .elements_mut() + .retain(|m| m.serial_number_id.ne("PLACEHOLDER")); + + // Rebuild monitor index map + *monitor_usr_idx_map = HashMap::new(); + let mut added_monitor_idxs = Vec::new(); + for (index, id) in &*DISPLAY_INDEX_PREFERENCES.read() { + if let Some(m_idx) = monitors + .elements() + .iter() + .position(|m| m.serial_number_id.eq(id)) + { + monitor_usr_idx_map.insert(*index, m_idx); + added_monitor_idxs.push(m_idx); + } + } + + let max_usr_idx = monitors + .elements() + .len() + .max(monitor_usr_idx_map.keys().max().map_or(0, |v| *v)); + + let mut available_usr_idxs = (0..max_usr_idx) + .filter(|i| !monitor_usr_idx_map.contains_key(i)) + .collect::>(); + + let not_added_monitor_idxs = (0..monitors.elements().len()) + .filter(|i| !added_monitor_idxs.contains(i)) + .collect::>(); + + for i in not_added_monitor_idxs { + if let Some(next_usr_idx) = available_usr_idxs.first() { + monitor_usr_idx_map.insert(*next_usr_idx, i); + available_usr_idxs.remove(0); + } else if let Some(idx) = monitor_usr_idx_map.keys().max() { + monitor_usr_idx_map.insert(*idx, i); + } } Ok(()) diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 3f0e3882..6b55a09b 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -34,6 +34,7 @@ use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; use lazy_static::lazy_static; use parking_lot::Mutex; +use parking_lot::RwLock; use regex::Regex; use serde::Deserialize; use serde::Serialize; @@ -100,6 +101,10 @@ lazy_static! { static ref FLOATING_WINDOW_TOGGLE_ASPECT_RATIO: Arc> = Arc::new(Mutex::new( AspectRatio::Predefined(PredefinedAspectRatio::Widescreen) )); + /// The index the user gives each monitor, by its serial number id + /// ([`SocketMessage::DisplayIndexPreference`]): the window manager orders its monitors by it + static ref DISPLAY_INDEX_PREFERENCES: Arc>> = + Arc::new(RwLock::new(HashMap::new())); /// The compiled regular expression of each rule whose matching strategy is `Regex`, by the /// rule's id static ref REGEX_IDENTIFIERS: Arc>> = @@ -165,7 +170,7 @@ pub enum NotificationEvent { /// use komorebi::core::SocketMessage; /// use komorebi::window_manager_event::WindowManagerEvent; /// -/// let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; +/// let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// /// let shown = format!( /// r#"{{"event":{{"type":"Show","content":[{{"type":"KWin","content":"WindowAdded"}},{{"id":7}}]}},"state":{state}}}"# @@ -240,7 +245,7 @@ pub struct Notification { /// ]); /// /// let state: State = serde_json::from_str( -/// r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#, +/// r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#, /// )?; /// let event = NotificationEvent::Socket(SocketMessage::Retile); /// notify_subscribers(Notification { event, state }, false)?; diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index ea14c389..5573429e 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -128,6 +128,26 @@ impl Monitor { } } + /// A stand-in for a monitor the user gave an index to (`DisplayIndexPreference`) that is not + /// connected, so that the monitors after it keep their indices while it is not there + pub fn placeholder() -> Self { + Self { + // temp + id: 2051316, + device: "".to_string(), + serial_number_id: "PLACEHOLDER".to_string(), + size: Default::default(), + work_area_size: Default::default(), + work_area_offset: None, + window_based_work_area_offset: None, + window_based_work_area_offset_limit: 0, + workspaces: Default::default(), + last_focused_workspace: None, + container_padding: None, + workspace_padding: None, + } + } + /// Tiles the focused workspace in this monitor's work area, less `offset` if the monitor has /// no offset of its own #[tracing::instrument(skip_all)] @@ -390,6 +410,30 @@ impl Monitor { Ok(()) } + pub fn update_workspaces_globals(&mut self, offset: Option) { + let container_padding = self + .container_padding + .or(Some(DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst))); + let workspace_padding = self + .workspace_padding + .or(Some(DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst))); + let work_area = self.work_area_size; + let work_area_offset = self.work_area_offset.or(offset); + let window_based_work_area_offset = self.window_based_work_area_offset; + let window_based_work_area_offset_limit = self.window_based_work_area_offset_limit; + + for workspace in self.workspaces_mut() { + workspace.globals = WorkspaceGlobals { + container_padding, + workspace_padding, + work_area, + work_area_offset, + window_based_work_area_offset, + window_based_work_area_offset_limit, + } + } + } + pub fn remove_workspace_by_idx(&mut self, idx: usize) -> Option { if idx < self.workspaces().len() { return self.workspaces_mut().remove(idx); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 88a4bb49..08b3624a 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -18,11 +18,14 @@ //! The others answer nothing: //! //! - **FocusWindow** and **CycleFocusWindow** give the focus to the container on one side of the -//! focused one, or to the next or the previous one in the workspace +//! focused one (or of the monitor on that side, at the edge of a monitor), or to the next or the +//! previous one in the workspace //! ([`WindowManager::focus_container_in_direction`], //! [`WindowManager::focus_container_in_cycle_direction`]). //! - **MoveWindow** and **CycleMoveWindow** swap the focused container with the one on one side -//! of it, or with the next or the previous one, and tile the workspace again +//! of it (or take it to the monitor on that side, at the edge of a monitor, as +//! **CrossMonitorMoveBehaviour** and **ToggleCrossMonitorMoveBehaviour** set), or with the next or +//! the previous one, and tile the workspace again //! ([`WindowManager::move_container_in_direction`], //! [`WindowManager::move_container_in_cycle_direction`]). //! - **Promote** moves the focused container to the largest tile, **PromoteSwap** swaps it with @@ -100,6 +103,15 @@ //! **WorkspaceTiling** do by index. **EnsureWorkspaces** gives a monitor workspaces up to a //! number, **NewWorkspace** adds one and shows it, and **CloseWorkspace** removes the workspace //! in front when it has no window and no name and is not the monitor's last. +//! - **FocusMonitorNumber**, **CycleFocusMonitor** and **FocusMonitorAtCursor** focus another +//! monitor ([`WindowManager::focus_monitor`]), and **FocusMonitorWorkspaceNumber** a workspace +//! of it. **MoveContainerToMonitorNumber**, **SendContainerToMonitorNumber**, their cycle and +//! monitor-workspace forms, **MoveContainerToNamedWorkspace** and +//! **SendContainerToNamedWorkspace** take the focused container to another monitor +//! ([`WindowManager::move_container_to_monitor`]); **MoveWorkspaceToMonitorNumber**, +//! **CycleMoveWorkspaceToMonitor** and **SwapWorkspacesToMonitorNumber** move workspaces +//! between monitors. **DisplayIndexPreference** gives a monitor an index, and **EagerFocus** +//! focuses the first window of an executable on any workspace of any monitor. //! - **Retile** tiles the focused workspace of every monitor again, without the resize //! adjustments, and **RetileWithResizeDimensions** with them. //! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name @@ -110,6 +122,7 @@ //! ([`notify_subscribers`]). use crate::DATA_DIR; +use crate::DISPLAY_INDEX_PREFERENCES; use crate::FLOATING_APPLICATIONS; use crate::IGNORE_IDENTIFIERS; use crate::MANAGE_IDENTIFIERS; @@ -123,6 +136,7 @@ use crate::core::ApplicationIdentifier; use crate::core::Axis; use crate::core::Layout; use crate::core::LayoutOptions; +use crate::core::MoveBehaviour; use crate::core::OperationDirection; use crate::core::Rect; use crate::core::ScrollingLayoutOptions; @@ -138,6 +152,7 @@ use crate::state::State; use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; +use crate::workspace::WorkspaceWindowLocation; use color_eyre::eyre; use color_eyre::eyre::Context; use color_eyre::eyre::OptionExt; @@ -222,6 +237,8 @@ impl WindowManager { /// `UnlockMonitorWorkspaceContainer` is not there (a container that is not there is ignored). /// - The focused window cannot be floated or put back, for one of the reasons /// [`WindowManager::toggle_float`] gives. + /// - The monitor a monitor command names is not there, or the compositor reports no window + /// with the focus to take to it ([`WindowManager::move_container_to_monitor`]). /// - The monitor or the workspace a message names by its index is not there /// (`WorkspaceName`, `WorkspaceLayout`, `WorkspaceTiling`, `EnsureWorkspaces`, /// `EnsureNamedWorkspaces`). A name no workspace has is ignored. @@ -265,6 +282,71 @@ impl WindowManager { self.focus_container_in_direction(direction)?; self.promote_container_to_front()? } + SocketMessage::EagerFocus(ref exe) => { + let focused_monitor_idx = self.focused_monitor_idx(); + let mouse_follows_focus = self.mouse_follows_focus; + + let mut window_location = None; + let mut monitor_to_focus = None; + let mut needs_workspace_loading = false; + + 'search: for (monitor_idx, monitor) in self.monitors_mut().iter_mut().enumerate() { + for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { + if let Some(location) = workspace.location_from_exe(exe) { + window_location = Some(location); + + if monitor_idx != focused_monitor_idx { + monitor_to_focus = Some(monitor_idx); + } + + // Focus workspace if it is not already the focused one, without + // loading it so that we don't give focus to the wrong window, we will + // load it later after focusing the wanted window + let focused_ws_idx = monitor.focused_workspace_idx(); + if focused_ws_idx != workspace_idx { + monitor.last_focused_workspace = Option::from(focused_ws_idx); + monitor.focus_workspace(workspace_idx)?; + needs_workspace_loading = true; + } + + break 'search; + } + } + } + + if let Some(monitor_idx) = monitor_to_focus { + self.focus_monitor(monitor_idx)?; + } + + if let Some(location) = window_location { + match location { + WorkspaceWindowLocation::Container(container_idx, window_idx) => { + let focused_container_idx = self.focused_container_idx()?; + if container_idx != focused_container_idx { + self.focused_workspace_mut()?.focus_container(container_idx); + } + + self.focus_container_window(window_idx)?; + } + WorkspaceWindowLocation::Floating(window_idx) => { + if let Some(window) = self + .focused_workspace_mut()? + .floating_windows_mut() + .get_mut(window_idx) + { + window.focus(mouse_follows_focus)?; + } + } + } + + if needs_workspace_loading { + let mouse_follows_focus = self.mouse_follows_focus; + if let Some(monitor) = self.focused_monitor_mut() { + monitor.load_focused_workspace(mouse_follows_focus)?; + } + } + } + } SocketMessage::FocusWindow(direction) => { self.focus_container_in_direction(direction)?; } @@ -299,7 +381,29 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::CycleFocusMonitor(direction) => { + let monitor_idx = direction.next_idx( + self.focused_monitor_idx(), + NonZeroUsize::new(self.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + self.focus_monitor(monitor_idx)?; + self.update_focused_workspace(self.mouse_follows_focus, true)?; + } SocketMessage::CycleFocusWorkspace(direction) => { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; let focused_workspace_idx = focused_monitor.focused_workspace_idx(); @@ -345,6 +449,15 @@ impl WindowManager { self.focus_workspace(workspace_idx)?; } } + SocketMessage::FocusMonitorNumber(monitor_idx) => { + self.focus_monitor(monitor_idx)?; + self.update_focused_workspace(self.mouse_follows_focus, true)?; + } + SocketMessage::FocusMonitorAtCursor => { + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { + self.focus_monitor(monitor_idx)?; + } + } SocketMessage::FocusLastWorkspace => { let idx = self .focused_monitor() @@ -378,6 +491,17 @@ impl WindowManager { self.focus_workspace(workspace_idx)?; } + SocketMessage::FocusMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { + let focused_monitor_idx = self.focused_monitor_idx(); + let focused_workspace_idx = self.focused_workspace_idx().unwrap_or_default(); + + let focused_pair = (focused_monitor_idx, focused_workspace_idx); + + if focused_pair != (monitor_idx, workspace_idx) { + self.focus_monitor(monitor_idx)?; + self.focus_workspace(workspace_idx)?; + } + } SocketMessage::FocusNamedWorkspace(ref name) => { if let Some((monitor_idx, workspace_idx)) = self.monitor_workspace_index_by_name(name) @@ -420,6 +544,18 @@ impl WindowManager { self.move_container_to_workspace(workspace_idx, false, None)?; } SocketMessage::MoveContainerToLastWorkspace => { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + let idx = self .focused_monitor() .ok_or_eyre("there is no monitor")? @@ -436,6 +572,18 @@ impl WindowManager { .last_focused_workspace = Option::from(idx); } SocketMessage::SendContainerToLastWorkspace => { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + let idx = self .focused_monitor() .ok_or_eyre("there is no monitor")? @@ -464,6 +612,23 @@ impl WindowManager { self.move_container_to_workspace(workspace_idx, true, None)?; } + SocketMessage::MoveContainerToMonitorNumber(monitor_idx) => { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor(monitor_idx, None, true, direction)?; + } + SocketMessage::SwapWorkspacesToMonitorNumber(monitor_idx) => { + self.swap_focused_monitor(monitor_idx)?; + } + SocketMessage::CycleMoveContainerToMonitor(direction) => { + let monitor_idx = direction.next_idx( + self.focused_monitor_idx(), + NonZeroUsize::new(self.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor(monitor_idx, None, true, direction)?; + } SocketMessage::CycleSendContainerToWorkspace(direction) => { let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; @@ -478,6 +643,95 @@ impl WindowManager { self.move_container_to_workspace(workspace_idx, false, None)?; } + SocketMessage::SendContainerToMonitorNumber(monitor_idx) => { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor(monitor_idx, None, false, direction)?; + } + SocketMessage::CycleSendContainerToMonitor(direction) => { + let monitor_idx = direction.next_idx( + self.focused_monitor_idx(), + NonZeroUsize::new(self.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor(monitor_idx, None, false, direction)?; + } + SocketMessage::SendContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor( + monitor_idx, + Option::from(workspace_idx), + false, + direction, + )?; + } + SocketMessage::MoveContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor( + monitor_idx, + Option::from(workspace_idx), + true, + direction, + )?; + } + SocketMessage::SendContainerToNamedWorkspace(ref workspace) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor( + monitor_idx, + Option::from(workspace_idx), + false, + direction, + )?; + } + } + SocketMessage::MoveContainerToNamedWorkspace(ref workspace) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor( + monitor_idx, + Option::from(workspace_idx), + true, + direction, + )?; + } + } + + SocketMessage::MoveWorkspaceToMonitorNumber(monitor_idx) => { + self.move_workspace_to_monitor(monitor_idx)?; + } + SocketMessage::CycleMoveWorkspaceToMonitor(direction) => { + let monitor_idx = direction.next_idx( + self.focused_monitor_idx(), + NonZeroUsize::new(self.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + self.move_workspace_to_monitor(monitor_idx)?; + } + SocketMessage::ToggleCrossMonitorMoveBehaviour => { + match self.cross_monitor_move_behaviour { + MoveBehaviour::Swap => { + self.cross_monitor_move_behaviour = MoveBehaviour::Insert; + } + MoveBehaviour::Insert => { + self.cross_monitor_move_behaviour = MoveBehaviour::Swap; + } + _ => {} + } + } + SocketMessage::CrossMonitorMoveBehaviour(behaviour) => { + self.cross_monitor_move_behaviour = behaviour; + } + SocketMessage::DisplayIndexPreference(index_preference, ref display) => { + let mut display_index_preferences = DISPLAY_INDEX_PREFERENCES.write(); + display_index_preferences.insert(index_preference, display.clone()); + } SocketMessage::NewWorkspace => { self.new_workspace()?; } diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index ca4e4385..794c6acf 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -159,6 +159,16 @@ impl WindowManager { // We don't have From implemented for &mut WindowManager let initial_state = State::from(self.as_ref()); + // a window can open on a monitor other than the focused one, and focus can follow + if matches!( + event, + WindowManagerEvent::FocusChange(_, _) | WindowManagerEvent::Show(_, _) + ) && let Some(monitor_idx) = self.monitor_idx_from_window(window) + && self.focused_monitor_idx() != monitor_idx + { + self.focus_monitor(monitor_idx)?; + } + match event { WindowManagerEvent::FocusChange(_, _) => { let is_known = self.known_window_ids.get(&window_id).cloned(); diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 8f3ea9ad..8161d000 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -14,6 +14,7 @@ use crate::DATA_DIR; use crate::IGNORE_IDENTIFIERS; use crate::MANAGE_IDENTIFIERS; +use crate::core::MoveBehaviour; use crate::core::OperationBehaviour; use crate::core::Rect; use crate::core::config_generation::MatchingRule; @@ -23,6 +24,7 @@ use crate::window_manager::WindowManager; use crate::workspace::Workspace; use serde::Deserialize; use serde::Serialize; +use std::collections::HashMap; use std::collections::VecDeque; use std::path::PathBuf; @@ -119,8 +121,10 @@ impl Default for GlobalState { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct State { pub monitors: Ring, + pub monitor_usr_idx_map: HashMap, pub is_paused: bool, pub resize_delta: i32, + pub cross_monitor_move_behaviour: MoveBehaviour, pub unmanaged_window_operation_behaviour: OperationBehaviour, pub work_area_offset: Option, pub mouse_follows_focus: bool, @@ -181,9 +185,11 @@ impl From<&WindowManager> for State { Self { monitors: stripped_monitors, + monitor_usr_idx_map: wm.monitor_usr_idx_map.clone(), is_paused: wm.is_paused, work_area_offset: wm.work_area_offset, resize_delta: wm.resize_delta, + cross_monitor_move_behaviour: wm.cross_monitor_move_behaviour, mouse_follows_focus: wm.mouse_follows_focus, unmanaged_window_operation_behaviour: wm.unmanaged_window_operation_behaviour, } @@ -208,6 +214,10 @@ impl State { return true; } + if self.cross_monitor_move_behaviour != new.cross_monitor_move_behaviour { + return true; + } + if self.unmanaged_window_operation_behaviour != new.unmanaged_window_operation_behaviour { return true; } diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 909167f6..c230cb70 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -240,6 +240,34 @@ impl Window { }) } + /// Moves the window from one work area to another, keeping where it is in the area and how + /// much of it it takes, in proportion: a floating window that goes to another monitor + pub fn move_to_area(&self, current_area: &Rect, target_area: &Rect) -> eyre::Result<()> { + let current_rect = self.rect()?; + let x_diff = target_area.left - current_area.left; + let y_diff = target_area.top - current_area.top; + let x_ratio = f32::abs((target_area.right as f32) / (current_area.right as f32)); + let y_ratio = f32::abs((target_area.bottom as f32) / (current_area.bottom as f32)); + let window_relative_x = current_rect.left - current_area.left; + let window_relative_y = current_rect.top - current_area.top; + let corrected_relative_x = (window_relative_x as f32 * x_ratio) as i32; + let corrected_relative_y = (window_relative_y as f32 * y_ratio) as i32; + let window_x = current_area.left + corrected_relative_x; + let window_y = current_area.top + corrected_relative_y; + let left = x_diff + window_x; + let top = y_diff + window_y; + + let corrected_width = (current_rect.right as f32 * x_ratio) as i32; + let corrected_height = (current_rect.bottom as f32 * y_ratio) as i32; + + self.set_position(&Rect { + left, + top, + right: corrected_width, + bottom: corrected_height, + }) + } + /// Whether the window is one komorebi should tile: a window that is still alive, that the /// compositor considers a normal application window, as opposed to a dialog, a splash screen, /// a utility window or a dock ([`WindowInfo::normal`](crate::backend::WindowInfo::normal)), diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index d39b54c8..f91bcb28 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -22,6 +22,11 @@ //! ([`WindowManager::set_workspace_name`]) and found by its name on any monitor //! ([`WindowManager::monitor_workspace_index_by_name`]). //! +//! With more than one monitor, the focus and a move at the edge of a monitor cross to the monitor +//! in that direction ([`WindowManager::monitor_idx_in_direction`]), and a container or a workspace +//! can be taken to another monitor ([`WindowManager::move_container_to_monitor`], +//! [`WindowManager::move_workspace_to_monitor`]). +//! //! [`listen_for_commands`]: crate::process_command::listen_for_commands use crate::DATA_DIR; @@ -32,9 +37,11 @@ use crate::backend::backend; use crate::container::Container; use crate::core::Arrangement; use crate::core::Axis; +use crate::core::CrossBoundaryBehaviour; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::MoveBehaviour; use crate::core::OperationBehaviour; use crate::core::OperationDirection; use crate::core::Rect; @@ -66,6 +73,9 @@ const MINIMUM_TILE_FRACTION: i32 = 10; #[derive(Debug)] pub struct WindowManager { pub monitors: Ring, + /// The monitor index a user's index stands for, when the indices the user gives monitors + /// (`DisplayIndexPreference`) are not the order the compositor reports them in + pub monitor_usr_idx_map: HashMap, /// The socket the daemon takes messages on, `komorebi.sock` in [`struct@DATA_DIR`] unless /// [`WindowManager::new`] was given another path pub command_listener: UnixListener, @@ -79,6 +89,13 @@ pub struct WindowManager { pub unmanaged_window_operation_behaviour: OperationBehaviour, /// How new and floated windows are placed: `ToggleFloat` reads its `toggle_float_placement` pub window_management_behaviour: WindowManagementBehaviour, + /// What a move towards a side with no container does: swap the container with the one at the + /// edge of the monitor on that side (`Swap`, the default), put it in among the containers there + /// (`Insert`), or nothing (`NoOp`) + pub cross_monitor_move_behaviour: MoveBehaviour, + /// Where a focus or a move towards a side with no container goes: the monitor on that side + /// (`Monitor`, the default), or the next workspace of the same monitor (`Workspace`) + pub cross_boundary_behaviour: CrossBoundaryBehaviour, /// Whether the pointer is moved to the window that is given the focus, which is the default pub mouse_follows_focus: bool, pub work_area_offset: Option, @@ -130,11 +147,14 @@ impl WindowManager { Ok(Self { monitors: Ring::default(), + monitor_usr_idx_map: HashMap::new(), command_listener: listener, is_paused: false, resize_delta: 50, unmanaged_window_operation_behaviour: Default::default(), window_management_behaviour: WindowManagementBehaviour::default(), + cross_monitor_move_behaviour: Default::default(), + cross_boundary_behaviour: Default::default(), mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -213,30 +233,114 @@ impl WindowManager { /// Gives the focus to the window of the container whose tile is on the `direction` side of /// the focused one, and the pointer follows it if [`WindowManager::mouse_follows_focus`] is - /// set + /// set. Where there is no such container, the focus crosses to the monitor on that side. /// /// Nothing is retiled: the focus moves, the windows stay where they are. /// /// # Errors /// - /// - There is no focused workspace, or no container on that side of the focused one. + /// - There is no focused workspace, or neither a container nor a monitor on that side of the + /// focused one. + /// - [`WindowManager::handle_unmanaged_window_behaviour`] refuses the message. /// - The backend refuses to focus the window. #[tracing::instrument(skip(self))] pub fn focus_container_in_direction( &mut self, direction: OperationDirection, ) -> eyre::Result<()> { + self.handle_unmanaged_window_behaviour()?; let mouse_follows_focus = self.mouse_follows_focus; let workspace = self.focused_workspace()?; + let workspace_idx = self.focused_workspace_idx()?; tracing::info!("focusing container"); let new_idx = workspace.new_idx_for_direction(direction); + // this is for when we are scrolling across workspaces like PaperWM + if new_idx.is_none() + && matches!( + self.cross_boundary_behaviour, + CrossBoundaryBehaviour::Workspace + ) + && matches!( + direction, + OperationDirection::Left | OperationDirection::Right + ) + { + let workspace_count = if let Some(monitor) = self.focused_monitor() { + monitor.workspaces().len() + } else { + 1 + }; + + let next_idx = match direction { + OperationDirection::Left => match workspace_idx { + 0 => workspace_count - 1, + n => n - 1, + }, + OperationDirection::Right => match workspace_idx { + n if n == workspace_count - 1 => 0, + n => n + 1, + }, + _ => workspace_idx, + }; + + self.focus_workspace(next_idx)?; + + if let Ok(focused_workspace) = self.focused_workspace_mut() { + match direction { + OperationDirection::Left => match focused_workspace.layout { + Layout::Default(layout) => { + let target_index = + layout.rightmost_index(focused_workspace.containers().len()); + focused_workspace.focus_container(target_index); + } + }, + OperationDirection::Right => match focused_workspace.layout { + Layout::Default(layout) => { + let target_index = + layout.leftmost_index(focused_workspace.containers().len()); + focused_workspace.focus_container(target_index); + } + }, + _ => {} + }; + } + + return Ok(()); + } + // if there is no container in that direction for this workspace match new_idx { - None => bail!("there is no container in this direction"), + None => { + let monitor_idx = self + .monitor_idx_in_direction(direction) + .ok_or_eyre("there is no container or monitor in this direction")?; + + self.focus_monitor(monitor_idx)?; + + if let Ok(focused_workspace) = self.focused_workspace_mut() { + match direction { + OperationDirection::Left => match focused_workspace.layout { + Layout::Default(layout) => { + let target_index = + layout.rightmost_index(focused_workspace.containers().len()); + focused_workspace.focus_container(target_index); + } + }, + OperationDirection::Right => match focused_workspace.layout { + Layout::Default(layout) => { + let target_index = + layout.leftmost_index(focused_workspace.containers().len()); + focused_workspace.focus_container(target_index); + } + }, + _ => {} + }; + } + } Some(idx) => { let workspace = self.focused_workspace_mut()?; workspace.focus_container(idx); @@ -259,26 +363,149 @@ impl WindowManager { /// The container keeps the focus, and the pointer follows it if /// [`WindowManager::mouse_follows_focus`] is set. A lock stays with its index: a container /// that is swapped onto the index of a locked one is locked in its place - /// ([`Workspace::swap_containers`]). + /// ([`Workspace::swap_containers`]). Where there is no container on that side, the container + /// goes to the monitor there as [`WindowManager::cross_monitor_move_behaviour`] says: swapped + /// with a container of that monitor, put in among them, or left where it is. /// /// # Errors /// - /// - There is no focused workspace, or no container on that side of the focused one. + /// - There is no focused workspace, or neither a container nor a monitor on that side of the + /// focused one. + /// - [`WindowManager::handle_unmanaged_window_behaviour`] refuses the message. /// - The workspace cannot be tiled, or the backend refuses to focus the window. #[tracing::instrument(skip(self))] pub fn move_container_in_direction( &mut self, direction: OperationDirection, ) -> eyre::Result<()> { + self.handle_unmanaged_window_behaviour()?; + let workspace = self.focused_workspace()?; + let workspace_idx = self.focused_workspace_idx()?; tracing::info!("moving container"); let origin_container_idx = workspace.focused_container_idx(); + let origin_monitor_idx = self.focused_monitor_idx(); let target_container_idx = workspace.new_idx_for_direction(direction); + // this is for when we are scrolling across workspaces like PaperWM + if target_container_idx.is_none() + && matches!( + self.cross_boundary_behaviour, + CrossBoundaryBehaviour::Workspace + ) + && matches!( + direction, + OperationDirection::Left | OperationDirection::Right + ) + { + let workspace_count = if let Some(monitor) = self.focused_monitor() { + monitor.workspaces().len() + } else { + 1 + }; + + let next_idx = match direction { + OperationDirection::Left => match workspace_idx { + 0 => workspace_count - 1, + n => n - 1, + }, + OperationDirection::Right => match workspace_idx { + n if n == workspace_count - 1 => 0, + n => n + 1, + }, + _ => workspace_idx, + }; + + // passing the direction here is how we handle whether to insert at the front + // or the back of the container vecdeque in the target workspace + self.move_container_to_workspace(next_idx, true, Some(direction))?; + self.update_focused_workspace(self.mouse_follows_focus, true)?; + + return Ok(()); + } + match target_container_idx { - None => bail!("there is no container in this direction"), + // If there is nowhere to move on the current workspace, try to move it onto the monitor + // in that direction if there is one + None => { + // Don't do anything if the user has set the MoveBehaviour to NoOp + if matches!(self.cross_monitor_move_behaviour, MoveBehaviour::NoOp) { + return Ok(()); + } + + let target_monitor_idx = self + .monitor_idx_in_direction(direction) + .ok_or_eyre("there is no container or monitor in this direction")?; + + { + // actually move the container to target monitor using the direction + self.move_container_to_monitor( + target_monitor_idx, + None, + true, + Some(direction), + )?; + + // focus the target monitor + self.focus_monitor(target_monitor_idx)?; + + // get a mutable ref to the focused workspace on the target monitor + let target_workspace = self.focused_workspace_mut()?; + + // if there is only one container on the target workspace after the insertion + // it means that there won't be one swapped back, so we have to decrement the + // focused position + if target_workspace.containers().len() == 1 { + let origin_workspace = + self.focused_workspace_for_monitor_idx_mut(origin_monitor_idx)?; + + origin_workspace.focus_container( + origin_workspace.focused_container_idx().saturating_sub(1), + ); + } + } + + // if our MoveBehaviour is Swap, let's try to send back the window container + // whose position which just took over + if matches!(self.cross_monitor_move_behaviour, MoveBehaviour::Swap) { + { + let target_workspace = self.focused_workspace_mut()?; + + // if the target workspace doesn't have more than one container, this means it + // was previously empty, by only doing the second part of the swap when there is + // more than one container, we can fall back to a "move" if there is nothing to + // swap with on the target monitor + if target_workspace.containers().len() > 1 { + // remove the container from the target monitor workspace + let target_container = target_workspace + // this is now focused_container_idx + 1 because we have inserted our origin container + .remove_container_by_idx( + target_workspace.focused_container_idx() + 1, + ) + .ok_or_eyre("could not remove container at given target index")?; + + let origin_workspace = + self.focused_workspace_for_monitor_idx_mut(origin_monitor_idx)?; + + // insert the container from the target monitor workspace into the origin monitor workspace + // at the same position from which our origin container was removed + origin_workspace + .insert_container_at_idx(origin_container_idx, target_container); + } + } + } + + // make sure to update the origin monitor workspace layout because it is no + // longer focused so it won't get updated at the end of this fn + let offset = self.work_area_offset; + + self.monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .update_focused_workspace(offset)?; + } Some(new_idx) => { let workspace = self.focused_workspace_mut()?; workspace.swap_containers(origin_container_idx, new_idx); @@ -384,6 +611,25 @@ impl WindowManager { .ok_or_eyre("there is no workspace") } + pub fn focused_workspace_for_monitor_idx(&self, idx: usize) -> eyre::Result<&Workspace> { + self.monitors() + .get(idx) + .ok_or_eyre("there is no monitor at this index")? + .focused_workspace() + .ok_or_eyre("there is no workspace") + } + + pub fn focused_workspace_for_monitor_idx_mut( + &mut self, + idx: usize, + ) -> eyre::Result<&mut Workspace> { + self.monitors_mut() + .get_mut(idx) + .ok_or_eyre("there is no monitor at this index")? + .focused_workspace_mut() + .ok_or_eyre("there is no workspace") + } + #[tracing::instrument(skip(self))] pub fn new_workspace(&mut self) -> eyre::Result<()> { tracing::info!("adding new workspace"); @@ -427,6 +673,13 @@ impl WindowManager { .ok_or_eyre("there is no window") } + pub fn focused_monitor_size(&self) -> eyre::Result { + Ok(self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .size) + } + pub fn focused_monitor_work_area(&self) -> eyre::Result { Ok(self .focused_monitor() @@ -1022,6 +1275,82 @@ impl WindowManager { Ok(()) } + // TODO: see if this logic is the same in macos when I have more than one monitor + pub fn monitor_idx_in_direction(&self, direction: OperationDirection) -> Option { + let current_monitor_size = self.focused_monitor_size().ok()?; + + for (idx, monitor) in self.monitors.elements().iter().enumerate() { + match direction { + OperationDirection::Left => { + if monitor.size.left + monitor.size.right == current_monitor_size.left { + return Option::from(idx); + } + } + OperationDirection::Right => { + if current_monitor_size.right + current_monitor_size.left == monitor.size.left { + return Option::from(idx); + } + } + OperationDirection::Up => { + if monitor.size.top + monitor.size.bottom == current_monitor_size.top { + return Option::from(idx); + } + } + OperationDirection::Down => { + if current_monitor_size.top + current_monitor_size.bottom == monitor.size.top { + return Option::from(idx); + } + } + } + } + + None + } + + /// The monitor a window is on: the one whose workspace holds it if it is managed, otherwise + /// the one the middle of the window is on. + /// + /// A managed window is not necessarily where its workspace is: the scrolling layout runs a + /// strip of windows past the edge of the monitor, and KWin lets them sit on the next monitor + /// over, where asking the geometry would hand focus to a monitor that does not own them. + pub fn monitor_idx_from_window(&self, window: Window) -> Option { + if let Some((monitor_idx, _)) = self.known_window_ids.get(&window.id) { + return Some(*monitor_idx); + } + + let rect = window.rect().ok()?; + let middle = (rect.left + rect.right / 2, rect.top + rect.bottom / 2); + + self.monitors() + .iter() + .position(|monitor| monitor.size.contains_point(middle)) + } + + pub fn monitor_idx_from_current_pos(&mut self) -> Option { + let (x, y) = backend().cursor_pos()?; + let monitor_id = backend().monitor_from_point(x, y)?; + + for (i, monitor) in self.monitors().iter().enumerate() { + if monitor.id == monitor_id { + return Option::from(i); + } + } + + // TODO: figure out if we need this on macOS + // // our hmonitor might be stale, so if we didn't return above, try querying via the latest + // // info taken from win32_display_data and update our hmonitor while we're at it + // if let Ok(latest) = MacosApi::monitor(monitor_id) { + // for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { + // if monitor.device_id() == latest.device_id() { + // monitor.set_id(latest.id()); + // return Option::from(i); + // } + // } + // } + + None + } + #[tracing::instrument(skip(self))] pub fn monitor_workspace_index_by_name(&mut self, name: &str) -> Option<(usize, usize)> { tracing::info!("looking up workspace by name"); @@ -1039,6 +1368,245 @@ impl WindowManager { None } + /// Calculates the direction of a move across monitors given a specific monitor index + pub fn direction_from_monitor_idx( + &self, + target_monitor_idx: usize, + ) -> Option { + let current_monitor_idx = self.focused_monitor_idx(); + if current_monitor_idx == target_monitor_idx { + return None; + } + + let current_monitor_size = self.focused_monitor_size().ok()?; + let target_monitor_size = self.monitors().get(target_monitor_idx)?.size; + + if target_monitor_size.left + target_monitor_size.right == current_monitor_size.left { + return Some(OperationDirection::Left); + } + if current_monitor_size.right + current_monitor_size.left == target_monitor_size.left { + return Some(OperationDirection::Right); + } + if target_monitor_size.top + target_monitor_size.bottom == current_monitor_size.top { + return Some(OperationDirection::Up); + } + if current_monitor_size.top + current_monitor_size.bottom == target_monitor_size.top { + return Some(OperationDirection::Down); + } + + None + } + + #[tracing::instrument(skip(self))] + pub fn move_container_to_monitor( + &mut self, + monitor_idx: usize, + workspace_idx: Option, + follow: bool, + move_direction: Option, + ) -> eyre::Result<()> { + tracing::info!("moving container"); + + let focused_monitor_idx = self.focused_monitor_idx(); + + if focused_monitor_idx == monitor_idx + && let Some(workspace_idx) = workspace_idx + { + return self.move_container_to_workspace(workspace_idx, follow, None); + } + + let offset = self.work_area_offset; + let mouse_follows_focus = self.mouse_follows_focus; + + let monitor = self + .focused_monitor_mut() + .ok_or_eyre("there is no monitor")?; + + let current_area = monitor.work_area_size; + + let workspace = monitor + .focused_workspace_mut() + .ok_or_eyre("there is no workspace")?; + + let foreground_window_id = backend() + .foreground_window() + .ok_or_eyre("no foreground window")?; + let floating_window_index = workspace + .floating_windows() + .iter() + .position(|w| w.id == foreground_window_id); + + let floating_window = + floating_window_index.and_then(|idx| workspace.floating_windows_mut().remove(idx)); + let container = if floating_window_index.is_none() { + Some( + workspace + .remove_focused_container() + .ok_or_eyre("there is no container")?, + ) + } else { + None + }; + monitor.update_focused_workspace(offset)?; + + let target_monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let target_monitor_work_area_size = target_monitor.work_area_size; + + let mut should_load_workspace = false; + if let Some(workspace_idx) = workspace_idx + && workspace_idx != target_monitor.focused_workspace_idx() + { + target_monitor.focus_workspace(workspace_idx)?; + should_load_workspace = true; + } + let target_workspace = target_monitor + .focused_workspace_mut() + .ok_or_eyre("there is no focused workspace on target monitor")?; + + if let Some(window) = floating_window { + window.move_to_area(¤t_area, &target_monitor_work_area_size)?; + target_workspace.floating_windows_mut().push_back(window); + } else if let Some(container) = container { + let _container_window_ids = + container.windows().iter().map(|w| w.id).collect::>(); + + if let Some(direction) = move_direction { + target_monitor.add_container_with_direction(container, workspace_idx, direction)?; + } else { + target_monitor.add_container(container, workspace_idx)?; + } + + if let Some(workspace) = target_monitor.focused_workspace() + && !workspace.tile + { + // TODO: figure out how to construct a Window from just an id here + // for window_id in container_window_ids { + // Window::from(window_id) + // .move_to_area(¤t_area, &target_monitor.work_area_size)?; + // } + } + } else { + eyre::bail!("failed to find a window to move"); + } + + // the moved window has to be on the target workspace's desktop before it is shown or focused + target_monitor.assign_windows_to_workspaces(); + + if should_load_workspace { + target_monitor.load_focused_workspace(mouse_follows_focus)?; + } + target_monitor.update_focused_workspace(offset)?; + + // this second one is for DPI changes when the target is another monitor + // if we don't do this the layout on the other monitor could look funny + // until it is interacted with again + target_monitor.update_focused_workspace(offset)?; + + if follow { + self.focus_monitor(monitor_idx)?; + } + + self.update_focused_workspace(self.mouse_follows_focus, true)?; + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn swap_focused_monitor(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("swapping focused monitor"); + + let focused_monitor_idx = self.focused_monitor_idx(); + let mouse_follows_focus = self.mouse_follows_focus; + + self.swap_monitor_workspaces(focused_monitor_idx, idx)?; + + self.update_focused_workspace(mouse_follows_focus, true) + } + + #[tracing::instrument(skip(self))] + pub fn swap_monitor_workspaces( + &mut self, + first_idx: usize, + second_idx: usize, + ) -> eyre::Result<()> { + tracing::info!("swaping monitors"); + if first_idx == second_idx { + return Ok(()); + } + let mouse_follows_focus = self.mouse_follows_focus; + let offset = self.work_area_offset; + let first_focused_workspace = { + let first_monitor = self + .monitors() + .get(first_idx) + .ok_or_eyre("There is no monitor")?; + first_monitor.focused_workspace_idx() + }; + + let second_focused_workspace = { + let second_monitor = self + .monitors() + .get(second_idx) + .ok_or_eyre("There is no monitor")?; + second_monitor.focused_workspace_idx() + }; + + // Swap workspaces between the first and second monitors + + let first_workspaces = self + .monitors_mut() + .get_mut(first_idx) + .ok_or_eyre("There is no monitor")? + .remove_workspaces(); + + let second_workspaces = self + .monitors_mut() + .get_mut(second_idx) + .ok_or_eyre("There is no monitor")? + .remove_workspaces(); + + self.monitors_mut() + .get_mut(first_idx) + .ok_or_eyre("There is no monitor")? + .workspaces_mut() + .extend(second_workspaces); + + self.monitors_mut() + .get_mut(second_idx) + .ok_or_eyre("There is no monitor")? + .workspaces_mut() + .extend(first_workspaces); + + // Set the focused workspaces for the first and second monitors + if let Some(first_monitor) = self.monitors_mut().get_mut(first_idx) { + first_monitor.update_workspaces_globals(offset); + first_monitor.focus_workspace(second_focused_workspace)?; + first_monitor.load_focused_workspace(mouse_follows_focus)?; + } + + if let Some(second_monitor) = self.monitors_mut().get_mut(second_idx) { + second_monitor.update_workspaces_globals(offset); + second_monitor.focus_workspace(first_focused_workspace)?; + second_monitor.load_focused_workspace(mouse_follows_focus)?; + } + + self.update_focused_workspace_by_monitor_idx(second_idx)?; + self.update_focused_workspace_by_monitor_idx(first_idx) + } + + pub fn update_focused_workspace_by_monitor_idx(&mut self, idx: usize) -> eyre::Result<()> { + let offset = self.work_area_offset; + + self.monitors_mut() + .get_mut(idx) + .ok_or_eyre("there is no monitor")? + .update_focused_workspace(offset) + } + /// Gives the focus to the window of the next (or the previous) container of the focused /// workspace, wrapping around at the ends, and the pointer follows it if /// [`WindowManager::mouse_follows_focus`] is set @@ -1098,6 +1666,35 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, true) } + /// Gives the focus to the window at `idx` in the focused container + #[tracing::instrument(skip(self))] + pub fn focus_container_window(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("focusing container window at index {idx}"); + + let mouse_follows_focus = self.mouse_follows_focus; + + let container = self.focused_container_mut()?; + + let len = NonZeroUsize::new(container.windows().len()) + .ok_or_eyre("there must be at least one window in a container")?; + + if len.get() == 1 && idx != 0 { + eyre::bail!("there is only one window in this container"); + } + + if container.windows().get(idx).is_none() { + eyre::bail!("there is no window in this container at index {idx}"); + } + + container.focus_window(idx); + + if let Some(window) = container.focused_window() { + window.focus(mouse_follows_focus)?; + } + + self.update_focused_workspace(mouse_follows_focus, true) + } + /// With [`OperationBehaviour::NoOp`], refuses a message while the window that has the focus /// in the compositor is not in a container of the focused workspace: a window komorebi does /// not manage, one the user unmanaged, or a floating window @@ -1405,6 +2002,31 @@ impl WindowManager { Ok(()) } + #[tracing::instrument(skip(self))] + pub fn move_workspace_to_monitor(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("moving workspace"); + let mouse_follows_focus = self.mouse_follows_focus; + let offset = self.work_area_offset; + let workspace = self + .remove_focused_workspace() + .ok_or_eyre("there is no workspace")?; + + { + let target_monitor: &mut Monitor = self + .monitors_mut() + .get_mut(idx) + .ok_or_eyre("there is no monitor")?; + + target_monitor.workspaces_mut().push_back(workspace); + target_monitor.update_workspaces_globals(offset); + target_monitor.focus_workspace(target_monitor.workspaces().len().saturating_sub(1))?; + target_monitor.load_focused_workspace(mouse_follows_focus)?; + } + + self.focus_monitor(idx)?; + self.update_focused_workspace(mouse_follows_focus, true) + } + pub fn remove_focused_workspace(&mut self) -> Option { let focused_monitor: &mut Monitor = self.focused_monitor_mut()?; let focused_workspace_idx = focused_monitor.focused_workspace_idx(); @@ -1460,6 +2082,177 @@ impl WindowManager { Ok(()) } + + #[tracing::instrument(skip(self))] + pub fn transfer_window( + &mut self, + origin: (usize, usize, u32), + target: (usize, usize, usize), + ) -> eyre::Result<()> { + let (origin_monitor_idx, origin_workspace_idx, window_id) = origin; + let (target_monitor_idx, target_workspace_idx, target_container_idx) = target; + + let origin_workspace = self + .monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("cannot get monitor idx")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("cannot get workspace idx")?; + + let origin_container_idx = origin_workspace + .container_for_window(window_id) + .and_then(|c| origin_workspace.containers().iter().position(|cc| cc == c)); + + if let Some(origin_container_idx) = origin_container_idx { + // Moving normal container window + self.transfer_container( + ( + origin_monitor_idx, + origin_workspace_idx, + origin_container_idx, + ), + ( + target_monitor_idx, + target_workspace_idx, + target_container_idx, + ), + )?; + } else if let Some(idx) = origin_workspace + .floating_windows() + .iter() + .position(|w| w.id == window_id) + { + // Moving floating window + // There is no need to physically move the floating window between areas with + // `move_to_area` because the user already did that, so we only need to transfer the + // window to the target `floating_windows` + if let Some(floating_window) = origin_workspace.floating_windows_mut().remove(idx) { + let target_workspace = self + .monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this idx")? + .focused_workspace_mut() + .ok_or_eyre("there is no focused workspace for this monitor")?; + + target_workspace + .floating_windows_mut() + .push_back(floating_window); + } + } + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn swap_containers( + &mut self, + origin: (usize, usize, usize), + target: (usize, usize, usize), + ) -> eyre::Result<()> { + let (origin_monitor_idx, origin_workspace_idx, origin_container_idx) = origin; + let (target_monitor_idx, target_workspace_idx, target_container_idx) = target; + + let origin_container_is_valid = self + .monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .containers() + .get(origin_container_idx) + .is_some(); + + let target_container_is_valid = self + .monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(target_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .containers() + .get(origin_container_idx) + .is_some(); + + if origin_container_is_valid && target_container_is_valid { + let origin_container = self + .monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .remove_container(origin_container_idx) + .ok_or_eyre("there is no container at this index")?; + + let target_container = self + .monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(target_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .remove_container(target_container_idx); + + self.monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(target_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .containers_mut() + .insert(target_container_idx, origin_container); + + if let Some(target_container) = target_container { + self.monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .containers_mut() + .insert(origin_container_idx, target_container); + } + } + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn transfer_container( + &mut self, + origin: (usize, usize, usize), + target: (usize, usize, usize), + ) -> eyre::Result<()> { + let (origin_monitor_idx, origin_workspace_idx, origin_container_idx) = origin; + let (target_monitor_idx, target_workspace_idx, target_container_idx) = target; + + let origin_container = self + .monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .remove_container(origin_container_idx) + .ok_or_eyre("there is no container at this index")?; + + let target_workspace = self + .monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(target_workspace_idx) + .ok_or_eyre("there is no workspace at this index")?; + + target_workspace + .containers_mut() + .insert(target_container_idx, origin_container); + + target_workspace.focus_container(target_container_idx); + + Ok(()) + } } #[cfg(test)] @@ -1649,6 +2442,157 @@ mod tests { assert_eq!(workspace_index.1, 0); } + #[test] + fn test_switch_focus_monitors() { + let (mut wm, _test_context) = setup_window_manager(); + + { + // Create a first monitor + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + assert_eq!(wm.monitors().len(), 1); + + { + // Create a second monitor + let m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + assert_eq!(wm.monitors().len(), 2); + + { + // Create a third monitor + let m = monitor::new( + 2, + Rect::default(), + Rect::default(), + "TestMonitor3".to_string(), + "TestDeviceID3".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + assert_eq!(wm.monitors().len(), 3); + + { + // Set the first monitor as focused and check if it is focused + wm.focus_monitor(0).unwrap(); + let current_monitor_idx = wm.monitors.focused_idx(); + assert_eq!(current_monitor_idx, 0); + } + + { + // Set the second monitor as focused and check if it is focused + wm.focus_monitor(1).unwrap(); + let current_monitor_idx = wm.monitors.focused_idx(); + assert_eq!(current_monitor_idx, 1); + } + + { + // Set the third monitor as focused and check if it is focused + wm.focus_monitor(2).unwrap(); + let current_monitor_idx = wm.monitors.focused_idx(); + assert_eq!(current_monitor_idx, 2); + } + + // Switch back to the first monitor + wm.focus_monitor(0).unwrap(); + let current_monitor_idx = wm.monitors.focused_idx(); + assert_eq!(current_monitor_idx, 0); + } + + #[test] + fn test_switch_focus_to_nonexistent_monitor() { + let (mut wm, _test_context) = setup_window_manager(); + + { + // Create a first monitor + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + + // Should have 1 monitor and the monitor index should be 0 + assert_eq!(wm.monitors().len(), 1); + assert_eq!(wm.focused_monitor_idx(), 0); + + // Should receive an error when trying to focus a non-existent monitor + let result = wm.focus_monitor(1); + assert!( + result.is_err(), + "Expected an error when focusing a non-existent monitor" + ); + + // Should still be focused on the first monitor + assert_eq!(wm.focused_monitor_idx(), 0); + } + + #[test] + fn test_focused_monitor_size() { + let (mut wm, _test_context) = setup_window_manager(); + + { + // Create a first monitor + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + assert_eq!(wm.monitors().len(), 1); + + { + // Set the first monitor as focused and check if it is focused + wm.focus_monitor(0).unwrap(); + let current_monitor_size = wm.focused_monitor_size().unwrap(); + assert_eq!(current_monitor_size, Rect::default()); + } + } + #[test] fn test_focus_container_in_cycle_direction() { let (mut wm, _test_context) = setup_window_manager(); @@ -1697,6 +2641,625 @@ mod tests { assert_eq!(wm.focused_container_idx().unwrap(), 0); } + #[test] + fn test_transfer_window() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(0)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + { + // Create a second monitor + let mut m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + // Should contain 2 monitors + assert_eq!(wm.monitors().len(), 2); + + { + // Monitor 0, Workspace 0, Window 0 + let origin = (0, 0, 0); + + // Monitor 1, Workspace 0, Window 0 + let target = (1, 0, 0); + + // Transfer the window from monitor 0 to monitor 1 + wm.transfer_window(origin, target).unwrap(); + + // Monitor 1 should contain 0 containers + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 0); + + // Monitor 2 should contain 2 containers + wm.focus_monitor(1).unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 2); + } + + { + // Monitor 1, Workspace 0, Window 0 + let origin = (1, 0, 0); + + // Monitor 0, Workspace 0, Window 0 + let target = (0, 0, 0); + + // Transfer the window from monitor 1 back to monitor 0 + wm.transfer_window(origin, target).unwrap(); + + // Monitor 2 should contain 1 containers + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 1); + + // Monitor 1 should contain 1 containers + wm.focus_monitor(0).unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 1); + } + } + + #[test] + fn test_transfer_window_to_nonexistent_monitor() { + // NOTE: transfer_window is primarily used when a window is being dragged by a mouse. The + // transfer_window function does return an error when the target monitor doesn't exist but + // there is a bug where the window isn't in the container after the window fails to + // transfer. The test will test for the result of the transfer_window function but not if + // the window is in the container after the transfer fails. + + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(0)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + { + // Monitor 0, Workspace 0, Window 0 + let origin = (0, 0, 0); + + // Monitor 1, Workspace 0, Window 0 + // + let target = (1, 0, 0); + + // Attempt to transfer the window from monitor 0 to a non-existent monitor + let result = wm.transfer_window(origin, target); + + // Result should be an error since the monitor doesn't exist + assert!( + result.is_err(), + "Expected an error when transferring to a non-existent monitor" + ); + + assert_eq!(wm.focused_container_idx().unwrap(), 0); + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + } + } + + #[test] + fn test_transfer_container() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(0)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + { + // Create a second monitor + let mut m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + // Should contain 2 monitors + assert_eq!(wm.monitors().len(), 2); + + { + // Monitor 0, Workspace 0, Window 0 + let origin = (0, 0, 0); + + // Monitor 1, Workspace 0, Window 0 + let target = (1, 0, 0); + + // Transfer the window from monitor 0 to monitor 1 + wm.transfer_container(origin, target).unwrap(); + + // Monitor 1 should contain 0 containers + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 0); + + // Monitor 2 should contain 2 containers + wm.focus_monitor(1).unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 2); + } + + { + // Monitor 1, Workspace 0, Window 0 + let origin = (1, 0, 0); + + // Monitor 0, Workspace 0, Window 0 + let target = (0, 0, 0); + + // Transfer the window from monitor 1 back to monitor 0 + wm.transfer_container(origin, target).unwrap(); + + // Monitor 2 should contain 1 containers + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 1); + + // Monitor 1 should contain 1 containers + wm.focus_monitor(0).unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 1); + } + } + + #[test] + fn test_swap_containers() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let mut container = Container::default(); + + // Add three windows to the container + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + + // Should have 3 windows in the container + assert_eq!(container.windows().len(), 3); + + // Add the container to the workspace + let workspace = m.focused_workspace_mut().unwrap(); + workspace.add_container_to_back(container); + + // Add monitor to the window manager + wm.monitors_mut().push_back(m); + } + + { + // Create a second monitor + let mut m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + // Should contain 2 monitors + assert_eq!(wm.monitors().len(), 2); + + // Monitor 0, Workspace 0, Window 0 + let origin = (0, 0, 0); + + // Monitor 1, Workspace 0, Window 0 + let target = (1, 0, 0); + + wm.swap_containers(origin, target).unwrap(); + + { + // Monitor 0 Workspace 0 container 0 should contain 1 container + let workspace = wm.focused_workspace_mut().unwrap(); + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 1); + } + + wm.focus_monitor(1).unwrap(); + + { + // Monitor 1 Workspace 0 container 0 should contain 3 containers + let workspace = wm.focused_workspace_mut().unwrap(); + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 3); + } + } + + // #[test] + // fn test_swap_container_with_nonexistent_container() { + // let (mut wm, _context) = setup_window_manager(); + // + // { + // // Create a first monitor + // let mut m = monitor::new( + // 0, + // Rect::default(), + // Rect::default(), + // "TestMonitor".to_string(), + // "TestDeviceID".to_string(), + // ); + // + // // Create a container + // let mut container = Container::default(); + // + // // Add three windows to the container + // for i in 0..3 { + // container.windows_mut().push_back(Window::from(i)); + // } + // + // // Should have 3 windows in the container + // assert_eq!(container.windows().len(), 3); + // + // // Add the container to the workspace + // let workspace = m.focused_workspace_mut().unwrap(); + // workspace.add_container_to_back(container); + // + // // Add monitor to the window manager + // wm.monitors_mut().push_back(m); + // } + // + // // Monitor 0, Workspace 0, Window 0 + // let origin = (0, 0, 0); + // + // // Monitor 1, Workspace 0, Window 0 + // let target = (0, 3, 0); + // + // // Should be focused on the first container + // assert_eq!(wm.focused_container_idx().unwrap(), 0); + // + // // Should return an error since there is only one container in the workspace + // let result = wm.swap_containers(origin, target); + // assert!( + // result.is_err(), + // "Expected an error when swapping with a non-existent container" + // ); + // + // // Should still be focused on the first container + // assert_eq!(wm.focused_container_idx().unwrap(), 0); + // + // { + // // Should still have 1 container in the workspace + // let workspace = wm.focused_workspace_mut().unwrap(); + // assert_eq!(workspace.containers().len(), 1); + // + // // Container should still have 3 windows + // let container = workspace.focused_container_mut().unwrap(); + // assert_eq!(container.windows().len(), 3); + // } + // } + + #[test] + fn test_swap_monitor_workspaces() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let mut container = Container::default(); + + // Add three windows to the container + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + + // Should have 3 windows in the container + assert_eq!(container.windows().len(), 3); + + // Add the container to the workspace + let workspace = m.focused_workspace_mut().unwrap(); + workspace.add_container_to_back(container); + + // Add monitor to the window manager + wm.monitors_mut().push_back(m); + } + + { + // Create a second monitor + let mut m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + // Add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + + // Swap the workspaces between Monitor 0 and Monitor 1 + wm.swap_monitor_workspaces(0, 1).ok(); + + { + // The focused workspace container in Monitor 0 should contain 3 containers + let workspace = wm.focused_workspace_mut().unwrap(); + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 1); + } + + // Switch to Monitor 1 + wm.focus_monitor(1).unwrap(); + assert_eq!(wm.focused_monitor_idx(), 1); + + { + // The focused workspace container in Monitor 1 should contain 3 containers + let workspace = wm.focused_workspace_mut().unwrap(); + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 3); + } + } + + #[test] + fn test_swap_workspace_with_nonexistent_monitor() { + let (mut wm, _context) = setup_window_manager(); + + { + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add another workspace + let new_workspace_index = m.new_workspace_idx(); + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Add monitor to window manager + wm.monitors_mut().push_back(m); + } + + // Should be an error since Monitor 1 does not exist + let result = wm.swap_monitor_workspaces(1, 0); + assert!( + result.is_err(), + "Expected an error when swapping with a non-existent monitor" + ); + + { + // Should still have 2 workspaces in Monitor 0 + let monitor = wm.monitors().front().unwrap(); + let workspaces = monitor.workspaces(); + assert_eq!( + workspaces.len(), + 2, + "Expected 2 workspaces after swap attempt" + ); + assert_eq!(wm.focused_monitor_idx(), 0); + } + } + + #[test] + fn test_move_workspace_to_monitor() { + let (mut wm, _context) = setup_window_manager(); + + { + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add another workspace + let new_workspace_index = m.new_workspace_idx(); + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Add monitor to window manager + wm.monitors_mut().push_back(m); + } + + { + let m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Should contain 1 workspace + assert_eq!(m.workspaces().len(), 1); + + // Add monitor to workspace + wm.monitors_mut().push_back(m); + } + + // Should contain 2 monitors + assert_eq!(wm.monitors().len(), 2); + + // Move a workspace from Monitor 0 to Monitor 1 + wm.move_workspace_to_monitor(1).ok(); + + { + // Should be focused on Monitor 1 + assert_eq!(wm.focused_monitor_idx(), 1); + + // Should contain 2 workspaces + let monitor = wm.focused_monitor_mut().unwrap(); + assert_eq!(monitor.workspaces().len(), 2); + } + + { + // Switch to Monitor 0 + wm.focus_monitor(0).unwrap(); + + // Should contain 1 workspace + let monitor = wm.focused_monitor_mut().unwrap(); + assert_eq!(monitor.workspaces().len(), 1); + } + } + + #[test] + fn test_move_workspace_to_nonexistent_monitor() { + let (mut wm, _context) = setup_window_manager(); + + { + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add another workspace + let new_workspace_index = m.new_workspace_idx(); + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Add monitor to window manager + wm.monitors_mut().push_back(m); + } + + // Attempt to move a workspace to a non-existent monitor + let result = wm.move_workspace_to_monitor(1); + + // Should be an error since Monitor 1 does not exist + assert!( + result.is_err(), + "Expected an error when moving to a non-existent monitor" + ); + } + #[test] fn test_toggle_tiling() { let (mut wm, _context) = setup_window_manager(); diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 7ec1771b..a5a8996b 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -76,6 +76,13 @@ impl Default for Workspace { } } +/// Where a workspace has a window of an application ([`Workspace::location_from_exe`]) +#[derive(Debug)] +pub enum WorkspaceWindowLocation { + Container(usize, usize), // container_idx, window_idx + Floating(usize), // idx in floating_windows +} + #[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq)] /// The work area a monitor gives the workspace it shows, the padding and the offset the /// workspace falls back to when it sets none of its own, and the monitor's window-based offset @@ -378,6 +385,29 @@ impl Workspace { false } + /// Where this workspace has a window of the executable `exe`, the first one in a container + /// before a floating one + pub fn location_from_exe(&self, exe: &str) -> Option { + for (container_idx, container) in self.containers().iter().enumerate() { + if let Some(window_idx) = container.idx_from_exe(exe) { + return Some(WorkspaceWindowLocation::Container( + container_idx, + window_idx, + )); + } + } + + for (window_idx, window) in self.floating_windows().iter().enumerate() { + if let Some(window_exe) = window.exe() + && exe == window_exe + { + return Some(WorkspaceWindowLocation::Floating(window_idx)); + } + } + + None + } + /// Returns true if and only if the window is in one of the containers, which leaves out the /// floating windows: the windows komorebi tiles pub fn contains_managed_window(&self, window_id: u32) -> bool { @@ -738,6 +768,12 @@ impl Workspace { Ok(()) } + + /// The container that has the window, if one of this workspace's does + pub fn container_for_window(&self, window_id: u32) -> Option<&Container> { + self.containers() + .get(self.container_idx_for_window(window_id)?) + } } impl Workspace { diff --git a/komorebi/tests/focus.rs b/komorebi/tests/focus.rs index 648616d1..6267e723 100644 --- a/komorebi/tests/focus.rs +++ b/komorebi/tests/focus.rs @@ -103,7 +103,9 @@ fn focus_towards_a_side_with_no_window_is_an_error_and_changes_nothing() { assert_eq!( result.map_err(|error| error.to_string()), - Err(String::from("there is no container in this direction")) + Err(String::from( + "there is no container or monitor in this direction" + )) ); assert_eq!(focused(&wm), 19_012); assert!(fake.commands().is_empty(), "{:?}", fake.commands()); diff --git a/komorebi/tests/monitors.rs b/komorebi/tests/monitors.rs new file mode 100644 index 00000000..1086ba37 --- /dev/null +++ b/komorebi/tests/monitors.rs @@ -0,0 +1,402 @@ +//! More than one monitor, against an in-memory desktop with two 1920x1080 monitors side by side: +//! the focus and a move that cross to the next monitor at the edge of one, the monitor commands, +//! moving workspaces between monitors, a window that opens on the monitor that is not focused, and +//! `eager-focus`. The messages go in through [`WindowManager::process_command`]; what comes out is +//! the monitors of the window manager and where the fake has the windows. +//! +//! Window ids are in the 32_000s. + +use komorebi::backend::Backend; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::CycleDirection; +use komorebi::core::MoveBehaviour; +use komorebi::core::OperationDirection; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +const LEFT: u32 = 1; +const RIGHT: u32 = 2; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +/// The bounds of the monitor on the right, which is also its work area +fn right_half() -> Rect { + Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1080, + } +} + +/// A window manager over a fake desktop with the monitor of `with_one_monitor` on the left and a +/// second one on the right +fn two_monitors() -> (Arc, WindowManager) { + let fake = FakeBackend::with_one_monitor(); + fake.add_monitor(RIGHT, "Virtual-1", right_half(), right_half()); + let fake = Arc::new(fake); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmm-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +/// Opens a window on the left monitor, or on the right one, and has the window manager show it +fn open(fake: &Arc, wm: &mut WindowManager, id: u32, on_right: bool) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + if on_right { + fake.move_window_by_user( + id, + Rect { + left: 2020, + top: 100, + right: 800, + bottom: 600, + }, + ); + } + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); +} + +fn send( + fake: &Arc, + wm: &mut WindowManager, + message: SocketMessage, +) -> color_eyre::Result<()> { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())) +} + +/// The ids of the windows of the focused workspace of each monitor +fn windows(wm: &WindowManager) -> Vec> { + wm.monitors() + .iter() + .map(|monitor| { + monitor + .focused_workspace() + .unwrap() + .containers() + .iter() + .flat_map(|container| container.windows().iter().map(|window| window.id)) + .collect() + }) + .collect() +} + +fn on_right(fake: &FakeBackend, id: u32) -> bool { + fake.rect_of(id).is_some_and(|rect| rect.left >= 1920) +} + +#[test] +fn a_window_that_opens_on_the_monitor_that_is_not_focused_focuses_it() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_001, false); + assert_eq!(wm.focused_monitor_idx(), 0); + + open(&fake, &mut wm, 32_002, true); + + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(windows(&wm), [vec![32_001], vec![32_002]]); + assert!(on_right(&fake, 32_002)); +} + +#[test] +fn the_focus_crosses_to_the_monitor_on_that_side() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_011, true); + open(&fake, &mut wm, 32_012, false); + assert_eq!(wm.focused_monitor_idx(), 0); + + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Right), + ) + .unwrap(); + + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(fake.foreground_window(), Some(32_011)); + + // and with no monitor further right, it is an error that changes nothing + let result = send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Right), + ); + assert_eq!( + result.map_err(|error| error.to_string()), + Err(String::from( + "there is no container or monitor in this direction" + )) + ); + assert_eq!(wm.focused_monitor_idx(), 1); +} + +#[test] +fn a_move_at_the_edge_of_a_monitor_swaps_with_the_window_on_the_next_one_by_default() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_021, true); + open(&fake, &mut wm, 32_022, false); + + send( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Right), + ) + .unwrap(); + + assert_eq!(windows(&wm), [vec![32_021], vec![32_022]]); + assert_eq!(wm.focused_monitor_idx(), 1); + assert!(on_right(&fake, 32_022) && !on_right(&fake, 32_021)); +} + +#[test] +fn with_insert_a_move_at_the_edge_puts_the_window_in_among_those_of_the_next_monitor() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_031, true); + open(&fake, &mut wm, 32_032, false); + send( + &fake, + &mut wm, + SocketMessage::CrossMonitorMoveBehaviour(MoveBehaviour::Insert), + ) + .unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Right), + ) + .unwrap(); + + assert!(windows(&wm)[0].is_empty()); + let mut right = windows(&wm)[1].clone(); + right.sort_unstable(); + assert_eq!(right, [32_031, 32_032]); + assert!(on_right(&fake, 32_031) && on_right(&fake, 32_032)); +} + +#[test] +fn with_no_op_a_move_at_the_edge_moves_nothing() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_041, true); + open(&fake, &mut wm, 32_042, false); + send( + &fake, + &mut wm, + SocketMessage::CrossMonitorMoveBehaviour(MoveBehaviour::NoOp), + ) + .unwrap(); + fake.clear_commands(); + + send( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Right), + ) + .unwrap(); + + assert_eq!(windows(&wm), [vec![32_042], vec![32_041]]); + assert_eq!(wm.focused_monitor_idx(), 0); +} + +#[test] +fn toggle_cross_monitor_move_behaviour_switches_between_swap_and_insert() { + let (fake, mut wm) = two_monitors(); + + send( + &fake, + &mut wm, + SocketMessage::ToggleCrossMonitorMoveBehaviour, + ) + .unwrap(); + assert_eq!(wm.cross_monitor_move_behaviour, MoveBehaviour::Insert); + send( + &fake, + &mut wm, + SocketMessage::ToggleCrossMonitorMoveBehaviour, + ) + .unwrap(); + assert_eq!(wm.cross_monitor_move_behaviour, MoveBehaviour::Swap); +} + +#[test] +fn a_monitor_is_focused_by_its_index_or_in_order() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_051, false); + open(&fake, &mut wm, 32_052, true); + + send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(0)).unwrap(); + assert_eq!(wm.focused_monitor_idx(), 0); + assert_eq!(fake.foreground_window(), Some(32_051)); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusMonitor(CycleDirection::Next), + ) + .unwrap(); + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(fake.foreground_window(), Some(32_052)); + + assert!(send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(5)).is_err()); + assert_eq!(wm.focused_monitor_idx(), 1); +} + +#[test] +fn move_to_monitor_follows_the_window_and_send_to_monitor_does_not() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_061, false); + open(&fake, &mut wm, 32_062, false); + + send( + &fake, + &mut wm, + SocketMessage::SendContainerToMonitorNumber(1), + ) + .unwrap(); + assert_eq!(wm.focused_monitor_idx(), 0); + assert_eq!(windows(&wm), [vec![32_061], vec![32_062]]); + assert!(on_right(&fake, 32_062)); + + send( + &fake, + &mut wm, + SocketMessage::MoveContainerToMonitorNumber(1), + ) + .unwrap(); + assert_eq!(wm.focused_monitor_idx(), 1); + assert!(windows(&wm)[0].is_empty()); + assert!(on_right(&fake, 32_061) && on_right(&fake, 32_062)); +} + +#[test] +fn a_window_sent_to_a_workspace_of_another_monitor_goes_on_its_desktop() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_071, false); + open(&fake, &mut wm, 32_072, false); + + send( + &fake, + &mut wm, + SocketMessage::SendContainerToMonitorWorkspaceNumber(1, 2), + ) + .unwrap(); + + assert_eq!(wm.focused_monitor_idx(), 0); + let right = &wm.monitors()[1]; + assert_eq!(right.focused_workspace_idx(), 2); + assert!(right.workspaces()[2].contains_window(32_072)); + assert_eq!(fake.workspace_of(32_072), Some(2)); +} + +#[test] +fn a_named_workspace_on_another_monitor_takes_the_window_sent_to_it() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_081, false); + open(&fake, &mut wm, 32_082, false); + send( + &fake, + &mut wm, + SocketMessage::WorkspaceName(1, 0, String::from("side")), + ) + .unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::MoveContainerToNamedWorkspace(String::from("side")), + ) + .unwrap(); + + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(windows(&wm), [vec![32_081], vec![32_082]]); +} + +#[test] +fn a_workspace_moves_to_another_monitor_and_workspaces_are_swapped_between_monitors() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_091, false); + open(&fake, &mut wm, 32_092, true); + + send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(0)).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::SwapWorkspacesToMonitorNumber(1), + ) + .unwrap(); + assert_eq!(windows(&wm), [vec![32_092], vec![32_091]]); + + send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(0)).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::MoveWorkspaceToMonitorNumber(1), + ) + .unwrap(); + assert_eq!(wm.focused_monitor_idx(), 1); + let right = &wm.monitors()[1]; + assert_eq!(right.workspaces().len(), 2); + assert!(right.focused_workspace().unwrap().contains_window(32_092)); +} + +#[test] +fn eager_focus_finds_the_window_of_an_executable_on_any_monitor_and_workspace() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_101, false); + fake.open_window(32_102, "firefox", "firefox", "a browser"); + with_backend(fake.clone(), || wm.process_event(added(32_102))).unwrap(); + // the browser on workspace 1 of the right monitor, and the focus back on the terminal + send( + &fake, + &mut wm, + SocketMessage::SendContainerToMonitorWorkspaceNumber(1, 1), + ) + .unwrap(); + with_backend(fake.clone(), || wm.process_event(activated(32_101))).unwrap(); + send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(0)).unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::EagerFocus(String::from("firefox")), + ) + .unwrap(); + + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert_eq!(fake.foreground_window(), Some(32_102)); + assert_eq!(fake.shown_workspace(RIGHT), 1); + assert_eq!(fake.shown_workspace(LEFT), 0); +} diff --git a/komorebi/tests/moving.rs b/komorebi/tests/moving.rs index 9fad1850..41d76346 100644 --- a/komorebi/tests/moving.rs +++ b/komorebi/tests/moving.rs @@ -120,7 +120,9 @@ fn move_towards_a_side_with_no_window_is_an_error_and_moves_nothing() { assert_eq!( result.map_err(|error| error.to_string()), - Err(String::from("there is no container in this direction")) + Err(String::from( + "there is no container or monitor in this direction" + )) ); assert_eq!(order(&wm), [20_011, 20_012]); assert!(fake.commands().is_empty(), "{:?}", fake.commands()); diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 54dac229..08a85caf 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -38,6 +38,15 @@ //! `move-to-last-workspace` and `send-to-last-workspace` to the one that was in front before, //! `focus-workspaces` shows a workspace on every monitor, and `new-workspace` and //! `close-workspace` add a workspace and remove an empty one. +//! - `focus-monitor`, `cycle-monitor` and `focus-monitor-at-cursor` focus another monitor, and +//! `focus-monitor-workspace` a workspace of another monitor; `move-to-monitor`, +//! `send-to-monitor`, their `cycle-` forms, `move-to-monitor-workspace`, +//! `send-to-monitor-workspace`, `move-to-named-workspace` and `send-to-named-workspace` take the +//! focused window to another monitor; `move-workspace-to-monitor`, +//! `cycle-move-workspace-to-monitor` and `swap-workspaces-with-monitor` take workspaces there; +//! `cross-monitor-move-behaviour` and `toggle-cross-monitor-move-behaviour` set what `move` does +//! at the edge of a monitor, and `display-index-preference` gives a monitor an index. +//! `eager-focus` focuses the first window of an executable, on any workspace of any monitor. //! - `workspace-name` names a workspace, which `focus-named-workspace`, `named-workspace-layout` //! and `named-workspace-tiling` find by its name; `workspace-layout` and `workspace-tiling` set //! the layout and the tiling of a workspace by its index, and `ensure-workspaces` and @@ -67,6 +76,7 @@ use komorebi_client::ApplicationIdentifier; use komorebi_client::Axis; use komorebi_client::CycleDirection; use komorebi_client::DefaultLayout; +use komorebi_client::MoveBehaviour; use komorebi_client::OperationBehaviour; use komorebi_client::OperationDirection; use komorebi_client::Rect; @@ -124,14 +134,19 @@ gen_enum_subcommand_args! { CycleMove: CycleDirection, CycleMoveToWorkspace: CycleDirection, CycleSendToWorkspace: CycleDirection, + CycleSendToMonitor: CycleDirection, + CycleMoveToMonitor: CycleDirection, + CycleMonitor: CycleDirection, CycleWorkspace: CycleDirection, CycleEmptyWorkspace: CycleDirection, + CycleMoveWorkspaceToMonitor: CycleDirection, FlipLayout: Axis, ChangeLayout: DefaultLayout, CycleLayout: CycleDirection, // WatchConfiguration: BooleanState, MouseFollowsFocus: BooleanState, Query: StateQuery, + CrossMonitorMoveBehaviour: MoveBehaviour, UnmanagedWindowOperationBehaviour: OperationBehaviour, PromoteWindow: OperationDirection, } @@ -150,10 +165,15 @@ macro_rules! gen_target_subcommand_args { } gen_target_subcommand_args! { + MoveToMonitor, MoveToWorkspace, + SendToMonitor, SendToWorkspace, + FocusMonitor, FocusWorkspace, FocusWorkspaces, + MoveWorkspaceToMonitor, + SwapWorkspacesWithMonitor, } macro_rules! gen_named_target_subcommand_args { @@ -170,6 +190,8 @@ macro_rules! gen_named_target_subcommand_args { } gen_named_target_subcommand_args! { + MoveToNamedWorkspace, + SendToNamedWorkspace, FocusNamedWorkspace, } @@ -396,6 +418,38 @@ struct WorkspaceWorkAreaOffset { bottom: i32, } +#[derive(Parser)] +struct FocusMonitorWorkspace { + /// Target monitor index (zero-indexed) + target_monitor: usize, + /// Workspace index on the target monitor (zero-indexed) + target_workspace: usize, +} + +#[derive(Parser)] +pub struct SendToMonitorWorkspace { + /// Target monitor index (zero-indexed) + target_monitor: usize, + /// Workspace index on the target monitor (zero-indexed) + target_workspace: usize, +} + +#[derive(Parser)] +pub struct MoveToMonitorWorkspace { + /// Target monitor index (zero-indexed) + target_monitor: usize, + /// Workspace index on the target monitor (zero-indexed) + target_workspace: usize, +} + +#[derive(Parser)] +struct DisplayIndexPreference { + /// Preferred monitor index (zero-indexed) + index_preference: usize, + /// Display name as identified in komorebic state + display: String, +} + #[derive(Parser)] struct EnsureWorkspaces { /// Monitor index (zero-indexed) @@ -437,6 +491,12 @@ struct LoadResize { path: PathBuf, } +#[derive(Parser)] +struct EagerFocus { + /// Case-sensitive exe identifier + exe: String, +} + #[derive(Parser)] struct ScrollingLayoutColumns { /// Desired number of visible columns @@ -550,6 +610,9 @@ enum SubCommand { /// Move the focused window in the specified cycle direction #[clap(arg_required_else_help = true)] CycleMove(CycleMove), + /// Focus the first managed window matching the given executable + #[clap(arg_required_else_help = true)] + EagerFocus(EagerFocus), /// Resize the focused window in the specified direction #[clap(arg_required_else_help = true)] #[clap(alias = "resize")] @@ -557,22 +620,51 @@ enum SubCommand { /// Resize the focused window or primary column along the specified axis #[clap(arg_required_else_help = true)] ResizeAxis(ResizeAxis), + /// Move the focused window to the specified monitor + #[clap(arg_required_else_help = true)] + MoveToMonitor(MoveToMonitor), + /// Move the focused window to the monitor in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleMoveToMonitor(CycleMoveToMonitor), /// Move the focused window to the specified workspace #[clap(arg_required_else_help = true)] MoveToWorkspace(MoveToWorkspace), + /// Move the focused window to the specified workspace + #[clap(arg_required_else_help = true)] + MoveToNamedWorkspace(MoveToNamedWorkspace), /// Move the focused window to the workspace in the given cycle direction #[clap(arg_required_else_help = true)] CycleMoveToWorkspace(CycleMoveToWorkspace), + /// Send the focused window to the specified monitor + #[clap(arg_required_else_help = true)] + SendToMonitor(SendToMonitor), + /// Send the focused window to the monitor in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleSendToMonitor(CycleSendToMonitor), /// Send the focused window to the specified workspace #[clap(arg_required_else_help = true)] SendToWorkspace(SendToWorkspace), + /// Send the focused window to the specified workspace + #[clap(arg_required_else_help = true)] + SendToNamedWorkspace(SendToNamedWorkspace), /// Send the focused window to the workspace in the given cycle direction #[clap(arg_required_else_help = true)] CycleSendToWorkspace(CycleSendToWorkspace), + /// Send the focused window to the specified monitor workspace + #[clap(arg_required_else_help = true)] + SendToMonitorWorkspace(SendToMonitorWorkspace), + /// Move the focused window to the specified monitor workspace + #[clap(arg_required_else_help = true)] + MoveToMonitorWorkspace(MoveToMonitorWorkspace), /// Send the focused window to the last focused monitor workspace SendToLastWorkspace, /// Move the focused window to the last focused monitor workspace MoveToLastWorkspace, + /// Focus the specified monitor + #[clap(arg_required_else_help = true)] + FocusMonitor(FocusMonitor), + /// Focus the monitor at the current cursor location + FocusMonitorAtCursor, /// Focus the last focused workspace on the focused monitor FocusLastWorkspace, /// Focus the specified workspace on the focused monitor @@ -581,17 +673,32 @@ enum SubCommand { /// Focus the specified workspace on all monitors #[clap(arg_required_else_help = true)] FocusWorkspaces(FocusWorkspaces), + /// Focus the specified workspace on the target monitor + #[clap(arg_required_else_help = true)] + FocusMonitorWorkspace(FocusMonitorWorkspace), /// Focus the specified workspace #[clap(arg_required_else_help = true)] FocusNamedWorkspace(FocusNamedWorkspace), /// Close the focused workspace (must be empty and unnamed) CloseWorkspace, + /// Focus the monitor in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleMonitor(CycleMonitor), /// Focus the workspace in the given cycle direction #[clap(arg_required_else_help = true)] CycleWorkspace(CycleWorkspace), /// Focus the next empty workspace in the given cycle direction (if one exists) #[clap(arg_required_else_help = true)] CycleEmptyWorkspace(CycleWorkspace), + /// Move the focused workspace to the specified monitor + #[clap(arg_required_else_help = true)] + MoveWorkspaceToMonitor(MoveWorkspaceToMonitor), + /// Move the focused workspace monitor in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleMoveWorkspaceToMonitor(CycleMoveWorkspaceToMonitor), + /// Swap focused monitor workspaces with specified monitor + #[clap(arg_required_else_help = true)] + SwapWorkspacesWithMonitor(SwapWorkspacesWithMonitor), /// Create and append a new workspace on the focused monitor NewWorkspace, /// Set the resize delta (used by resize-edge and resize-axis) @@ -651,6 +758,12 @@ enum SubCommand { PromoteWindow(PromoteWindow), /// Force the retiling of all managed windows Retile, + // /// Set the monitor index preference for a monitor identified using its size + // #[clap(arg_required_else_help = true)] + // MonitorIndexPreference(MonitorIndexPreference), + /// Set the display index preference for a monitor identified using its display name + #[clap(arg_required_else_help = true)] + DisplayIndexPreference(DisplayIndexPreference), /// Create at least this many workspaces for the specified monitor #[clap(arg_required_else_help = true)] EnsureWorkspaces(EnsureWorkspaces), @@ -698,6 +811,11 @@ enum SubCommand { Manage, /// Unmanage a window that was forcibly managed Unmanage, + /// Set the behaviour when moving windows across monitor boundaries + #[clap(arg_required_else_help = true)] + CrossMonitorMoveBehaviour(CrossMonitorMoveBehaviour), + /// Toggle the behaviour when moving windows across monitor boundaries + ToggleCrossMonitorMoveBehaviour, /// Set the operation behavior when the focused window is not managed #[clap(arg_required_else_help = true)] UnmanagedWindowOperationBehaviour(UnmanagedWindowOperationBehaviour), @@ -869,18 +987,36 @@ fn main() -> eyre::Result<()> { SubCommand::FocusWorkspace(args) => { send_message(&SocketMessage::FocusWorkspaceNumber(args.target))?; } + SubCommand::ToggleCrossMonitorMoveBehaviour => { + send_message(&SocketMessage::ToggleCrossMonitorMoveBehaviour)?; + } + SubCommand::FocusMonitor(args) => { + send_message(&SocketMessage::FocusMonitorNumber(args.target))?; + } + SubCommand::FocusMonitorAtCursor => { + send_message(&SocketMessage::FocusMonitorAtCursor)?; + } SubCommand::FocusLastWorkspace => { send_message(&SocketMessage::FocusLastWorkspace)?; } SubCommand::FocusWorkspaces(args) => { send_message(&SocketMessage::FocusWorkspaceNumbers(args.target))?; } + SubCommand::FocusMonitorWorkspace(args) => { + send_message(&SocketMessage::FocusMonitorWorkspaceNumber( + args.target_monitor, + args.target_workspace, + ))?; + } SubCommand::FocusNamedWorkspace(args) => { send_message(&SocketMessage::FocusNamedWorkspace(args.workspace))?; } SubCommand::CloseWorkspace => { send_message(&SocketMessage::CloseWorkspace)?; } + SubCommand::CycleMonitor(args) => { + send_message(&SocketMessage::CycleFocusMonitor(args.cycle_direction))?; + } SubCommand::CycleWorkspace(args) => { send_message(&SocketMessage::CycleFocusWorkspace(args.cycle_direction))?; } @@ -898,28 +1034,77 @@ fn main() -> eyre::Result<()> { SubCommand::ResizeAxis(args) => { send_message(&SocketMessage::ResizeWindowAxis(args.axis, args.sizing))?; } + SubCommand::MoveToMonitor(args) => { + send_message(&SocketMessage::MoveContainerToMonitorNumber(args.target))?; + } + SubCommand::CycleMoveToMonitor(args) => { + send_message(&SocketMessage::CycleMoveContainerToMonitor( + args.cycle_direction, + ))?; + } SubCommand::MoveToWorkspace(args) => { send_message(&SocketMessage::MoveContainerToWorkspaceNumber(args.target))?; } + SubCommand::MoveToNamedWorkspace(args) => { + send_message(&SocketMessage::MoveContainerToNamedWorkspace( + args.workspace, + ))?; + } SubCommand::CycleMoveToWorkspace(args) => { send_message(&SocketMessage::CycleMoveContainerToWorkspace( args.cycle_direction, ))?; } + SubCommand::SendToMonitor(args) => { + send_message(&SocketMessage::SendContainerToMonitorNumber(args.target))?; + } + SubCommand::CycleSendToMonitor(args) => { + send_message(&SocketMessage::CycleSendContainerToMonitor( + args.cycle_direction, + ))?; + } SubCommand::SendToWorkspace(args) => { send_message(&SocketMessage::SendContainerToWorkspaceNumber(args.target))?; } + SubCommand::SendToNamedWorkspace(args) => { + send_message(&SocketMessage::SendContainerToNamedWorkspace( + args.workspace, + ))?; + } SubCommand::CycleSendToWorkspace(args) => { send_message(&SocketMessage::CycleSendContainerToWorkspace( args.cycle_direction, ))?; } + SubCommand::SendToMonitorWorkspace(args) => { + send_message(&SocketMessage::SendContainerToMonitorWorkspaceNumber( + args.target_monitor, + args.target_workspace, + ))?; + } + SubCommand::MoveToMonitorWorkspace(args) => { + send_message(&SocketMessage::MoveContainerToMonitorWorkspaceNumber( + args.target_monitor, + args.target_workspace, + ))?; + } + SubCommand::MoveWorkspaceToMonitor(args) => { + send_message(&SocketMessage::MoveWorkspaceToMonitorNumber(args.target))?; + } + SubCommand::CycleMoveWorkspaceToMonitor(args) => { + send_message(&SocketMessage::CycleMoveWorkspaceToMonitor( + args.cycle_direction, + ))?; + } SubCommand::MoveToLastWorkspace => { send_message(&SocketMessage::MoveContainerToLastWorkspace)?; } SubCommand::SendToLastWorkspace => { send_message(&SocketMessage::SendContainerToLastWorkspace)?; } + SubCommand::SwapWorkspacesWithMonitor(args) => { + send_message(&SocketMessage::SwapWorkspacesToMonitorNumber(args.target))?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } @@ -983,6 +1168,9 @@ fn main() -> eyre::Result<()> { SubCommand::ManageRule(args) => { send_message(&SocketMessage::ManageRule(args.identifier, args.id))?; } + SubCommand::EagerFocus(args) => { + send_message(&SocketMessage::EagerFocus(args.exe))?; + } SubCommand::NewWorkspace => { send_message(&SocketMessage::NewWorkspace)?; } @@ -1099,6 +1287,17 @@ fn main() -> eyre::Result<()> { send_message(&SocketMessage::LayoutRatios(args.columns, args.rows))?; } } + SubCommand::CrossMonitorMoveBehaviour(args) => { + send_message(&SocketMessage::CrossMonitorMoveBehaviour( + args.move_behaviour, + ))?; + } + SubCommand::DisplayIndexPreference(args) => { + send_message(&SocketMessage::DisplayIndexPreference( + args.index_preference, + args.display, + ))?; + } SubCommand::EnsureWorkspaces(workspaces) => { send_message(&SocketMessage::EnsureWorkspaces( workspaces.monitor, diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 3b98916f..747317dc 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -514,6 +514,86 @@ fn the_named_workspace_subcommands_send_the_names_they_are_given() { ); } +#[test] +fn the_monitor_subcommands_send_what_they_are_given() { + sends( + &["focus-monitor", "1"], + r#"{"type":"FocusMonitorNumber","content":1}"#, + ); + sends( + &["cycle-monitor", "next"], + r#"{"type":"CycleFocusMonitor","content":"Next"}"#, + ); + sends( + &["focus-monitor-at-cursor"], + r#"{"type":"FocusMonitorAtCursor"}"#, + ); + sends( + &["focus-monitor-workspace", "1", "2"], + r#"{"type":"FocusMonitorWorkspaceNumber","content":[1,2]}"#, + ); + sends( + &["move-to-monitor", "1"], + r#"{"type":"MoveContainerToMonitorNumber","content":1}"#, + ); + sends( + &["send-to-monitor", "0"], + r#"{"type":"SendContainerToMonitorNumber","content":0}"#, + ); + sends( + &["cycle-move-to-monitor", "previous"], + r#"{"type":"CycleMoveContainerToMonitor","content":"Previous"}"#, + ); + sends( + &["cycle-send-to-monitor", "next"], + r#"{"type":"CycleSendContainerToMonitor","content":"Next"}"#, + ); + sends( + &["move-to-monitor-workspace", "1", "0"], + r#"{"type":"MoveContainerToMonitorWorkspaceNumber","content":[1,0]}"#, + ); + sends( + &["send-to-monitor-workspace", "0", "1"], + r#"{"type":"SendContainerToMonitorWorkspaceNumber","content":[0,1]}"#, + ); + sends( + &["move-to-named-workspace", "mail"], + r#"{"type":"MoveContainerToNamedWorkspace","content":"mail"}"#, + ); + sends( + &["send-to-named-workspace", "mail"], + r#"{"type":"SendContainerToNamedWorkspace","content":"mail"}"#, + ); + sends( + &["move-workspace-to-monitor", "1"], + r#"{"type":"MoveWorkspaceToMonitorNumber","content":1}"#, + ); + sends( + &["cycle-move-workspace-to-monitor", "next"], + r#"{"type":"CycleMoveWorkspaceToMonitor","content":"Next"}"#, + ); + sends( + &["swap-workspaces-with-monitor", "1"], + r#"{"type":"SwapWorkspacesToMonitorNumber","content":1}"#, + ); + sends( + &["cross-monitor-move-behaviour", "insert"], + r#"{"type":"CrossMonitorMoveBehaviour","content":"Insert"}"#, + ); + sends( + &["toggle-cross-monitor-move-behaviour"], + r#"{"type":"ToggleCrossMonitorMoveBehaviour"}"#, + ); + sends( + &["display-index-preference", "1", "DP-2"], + r#"{"type":"DisplayIndexPreference","content":[1,"DP-2"]}"#, + ); + sends( + &["eager-focus", "firefox"], + r#"{"type":"EagerFocus","content":"firefox"}"#, + ); +} + #[test] fn without_a_daemon_a_question_fails() { let runtime = Runtime::new(); @@ -562,18 +642,28 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "close.md", "completions.md", "container-padding.md", + "cross-monitor-move-behaviour.md", "cycle-empty-workspace.md", "cycle-focus.md", "cycle-layout.md", + "cycle-monitor.md", + "cycle-move-to-monitor.md", "cycle-move-to-workspace.md", + "cycle-move-workspace-to-monitor.md", "cycle-move.md", + "cycle-send-to-monitor.md", "cycle-send-to-workspace.md", "cycle-workspace.md", "data-directory.md", + "display-index-preference.md", + "eager-focus.md", "ensure-named-workspaces.md", "ensure-workspaces.md", "flip-layout.md", "focus-last-workspace.md", + "focus-monitor-at-cursor.md", + "focus-monitor-workspace.md", + "focus-monitor.md", "focus-named-workspace.md", "focus-workspace.md", "focus-workspaces.md", @@ -593,7 +683,11 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "monitor-work-area-offset.md", "mouse-follows-focus.md", "move-to-last-workspace.md", + "move-to-monitor-workspace.md", + "move-to-monitor.md", + "move-to-named-workspace.md", "move-to-workspace.md", + "move-workspace-to-monitor.md", "move.md", "named-workspace-layout.md", "named-workspace-tiling.md", @@ -613,6 +707,9 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "save-resize.md", "scrolling-layout-columns.md", "send-to-last-workspace.md", + "send-to-monitor-workspace.md", + "send-to-monitor.md", + "send-to-named-workspace.md", "send-to-workspace.md", "session-float-rule.md", "session-float-rules.md", @@ -620,6 +717,8 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "state.md", "stop.md", "subscribe-socket.md", + "swap-workspaces-with-monitor.md", + "toggle-cross-monitor-move-behaviour.md", "toggle-float.md", "toggle-lock.md", "toggle-mouse-follows-focus.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index e57dd17a..d2d3a711 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -229,6 +229,35 @@ workspace-layout 0 0 columns workspace-layout 0 0 bsp named-workspace-layout one columns named-workspace-layout one bsp +focus-monitor 1 +focus-monitor 0 +cycle-monitor next +cycle-monitor previous +focus-monitor-workspace 1 1 +focus-monitor-workspace 0 0 +focus-monitor-at-cursor +focus-monitor 0 +send-to-named-workspace two +focus-named-workspace two +move-to-named-workspace one +focus-named-workspace one +send-to-monitor 1 +focus-monitor 1 +move-to-monitor 0 +focus-monitor 0 +cycle-send-to-monitor next +focus-monitor 1 +cycle-move-to-monitor next +focus-monitor 0 +send-to-monitor-workspace 1 1 +focus-monitor-workspace 1 1 +move-to-monitor-workspace 0 0 +focus-monitor 0 +focus-workspace 0 +move-workspace-to-monitor 1 +cycle-move-workspace-to-monitor next +swap-workspaces-with-monitor 1 +swap-workspaces-with-monitor 1 global-work-area-offset 10 10 20 20 global-work-area-offset 0 0 0 0 monitor-work-area-offset 0 10 10 20 20 @@ -249,9 +278,14 @@ container-padding 0 0 12 container-padding 0 0 10 workspace-padding 0 0 12 workspace-padding 0 0 10 +cross-monitor-move-behaviour insert +cross-monitor-move-behaviour swap +toggle-cross-monitor-move-behaviour +toggle-cross-monitor-move-behaviour unmanaged-window-operation-behaviour op unmanaged-window-operation-behaviour no-op unmanaged-window-operation-behaviour op +display-index-preference 0 Virtual-0 mouse-follows-focus enable mouse-follows-focus disable toggle-mouse-follows-focus @@ -265,6 +299,7 @@ manage-rule exe nonexistent manage close retile +eager-focus foot """ for line in SWEEP.strip().splitlines(): status, out = kde.run(shlex.join(["komorebic", *line.split()])) From ac265de1e39aebd2377c8d2e59a1a2dafd51fd8a Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 03:11:38 -0700 Subject: [PATCH 032/255] feat(wm): padding for named workspaces workspace-padding and container-padding take the index of a workspace's monitor and its own index, so a script that names its workspaces still has to count them to pad one, while focus-named-workspace, named-workspace-layout and named-workspace-tiling already take the name. named-workspace-padding and named-workspace-container-padding take the name instead. They look the workspace up on every monitor the way the other named commands do, set the same padding the commands by index set, and change nothing for a name no workspace has. The tests check the messages the subcommands send, that a named workspace takes its paddings and the tile in front follows, and that a name nobody has changes nothing. The commands sweep of the VM suite sends both commands to a real session. --- docs/cli/named-workspace-container-padding.md | 17 +++++ docs/cli/named-workspace-padding.md | 17 +++++ docs/dev/ARCHITECTURE.md | 16 +++-- docs/usage/padding-and-offsets.md | 7 ++ komorebi/src/core/mod.rs | 2 + komorebi/src/process_command.rs | 24 +++++-- komorebi/tests/padding.rs | 68 +++++++++++++++++++ komorebic/src/main.rs | 48 +++++++++++-- komorebic/tests/cli.rs | 10 +++ nix/tests/vm/suites/commands/test.py | 4 ++ 10 files changed, 198 insertions(+), 15 deletions(-) create mode 100644 docs/cli/named-workspace-container-padding.md create mode 100644 docs/cli/named-workspace-padding.md diff --git a/docs/cli/named-workspace-container-padding.md b/docs/cli/named-workspace-container-padding.md new file mode 100644 index 00000000..e938ec60 --- /dev/null +++ b/docs/cli/named-workspace-container-padding.md @@ -0,0 +1,17 @@ +```text +Set the container padding for the specified workspace + +Usage: named-workspace-container-padding + +Arguments: + + Target workspace name + + + Pixels to pad with as an integer + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/named-workspace-padding.md b/docs/cli/named-workspace-padding.md new file mode 100644 index 00000000..dce5962a --- /dev/null +++ b/docs/cli/named-workspace-padding.md @@ -0,0 +1,17 @@ +```text +Set the workspace padding for the specified workspace + +Usage: named-workspace-padding + +Arguments: + + Target workspace name + + + Pixels to pad with as an integer + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 07dc1607..d5a8442e 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -405,13 +405,15 @@ focused is in no container of the focused workspace ([`WindowManager::handle_unmanaged_window_behaviour`]). `WorkspacePadding`, `ContainerPadding` and their `FocusedWorkspace` forms set a workspace's own -padding, and `AdjustWorkspacePadding` and `AdjustContainerPadding` change the focused -workspace's by a number of pixels, which needs a padding of its own to change -([`WindowManager::adjust_workspace_padding`]). `WorkAreaOffset`, `MonitorWorkAreaOffset` and -`WorkspaceWorkAreaOffset` set the offset of the window manager, of a monitor or of a workspace, -and `ToggleWindowBasedWorkAreaOffset` sets whether the focused workspace takes its monitor's -window-based offset ([`Workspace::apply_window_based_work_area_offset`]). Each tiles the -workspace in front again, or every monitor. +padding, and `NamedWorkspacePadding` and `NamedWorkspaceContainerPadding` do the same for the +workspace with a name, which they look up like `NamedWorkspaceLayout` does +([`WindowManager::monitor_workspace_index_by_name`]). `AdjustWorkspacePadding` and +`AdjustContainerPadding` change the focused workspace's by a number of pixels, which needs a padding +of its own to change ([`WindowManager::adjust_workspace_padding`]). `WorkAreaOffset`, +`MonitorWorkAreaOffset` and `WorkspaceWorkAreaOffset` set the offset of the window manager, of a +monitor or of a workspace, and `ToggleWindowBasedWorkAreaOffset` sets whether the focused workspace +takes its monitor's window-based offset ([`Workspace::apply_window_based_work_area_offset`]). Each +tiles the workspace in front again, or every monitor. `ResizeWindowEdge` and `ResizeWindowAxis` resize the focused container ([`WindowManager::resize_window`]). A resize is an adjustment of the container's tile, kept in diff --git a/docs/usage/padding-and-offsets.md b/docs/usage/padding-and-offsets.md index a058c9a6..77e1cdd2 100644 --- a/docs/usage/padding-and-offsets.md +++ b/docs/usage/padding-and-offsets.md @@ -21,11 +21,18 @@ set the paddings of the focused workspace, and [`komorebic container-padding`](../cli/container-padding.md) those of a workspace given by the index of its monitor and its own, counted from 0. +[`komorebic named-workspace-padding`](../cli/named-workspace-padding.md) and +[`komorebic named-workspace-container-padding`](../cli/named-workspace-container-padding.md) find +the workspace by the [name](workspaces.md#names) it was given instead, on whichever monitor has +it. A name no workspace has changes nothing. + ```sh komorebic focused-workspace-padding 20 komorebic focused-workspace-container-padding 10 komorebic workspace-padding 0 1 0 komorebic container-padding 0 1 0 +komorebic named-workspace-padding mail 0 +komorebic named-workspace-container-padding mail 0 ``` [`komorebic adjust-workspace-padding`](../cli/adjust-workspace-padding.md) and diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index f33eae60..2e6b1622 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -419,8 +419,10 @@ pub enum SocketMessage { FocusMonitorWorkspaceNumber(usize, usize), FocusNamedWorkspace(String), ContainerPadding(usize, usize, i32), + NamedWorkspaceContainerPadding(String, i32), FocusedWorkspaceContainerPadding(i32), WorkspacePadding(usize, usize, i32), + NamedWorkspacePadding(String, i32), FocusedWorkspacePadding(i32), WorkspaceTiling(usize, usize, bool), NamedWorkspaceTiling(String, bool), diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 08b3624a..5e242d99 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -53,10 +53,12 @@ //! workspace, which komorebi does not move, or puts a floating window back //! ([`WindowManager::toggle_float`]). //! - **WorkspacePadding** and **ContainerPadding** set the paddings of a workspace given by the -//! index of its monitor and its own, **FocusedWorkspacePadding** and -//! **FocusedWorkspaceContainerPadding** those of the focused workspace, and -//! **AdjustWorkspacePadding** and **AdjustContainerPadding** make the focused workspace's larger -//! or smaller ([`WindowManager::set_workspace_padding`], +//! index of its monitor and its own, **NamedWorkspacePadding** and +//! **NamedWorkspaceContainerPadding** those of the workspace with a name +//! ([`WindowManager::monitor_workspace_index_by_name`]; a name no workspace has changes +//! nothing), **FocusedWorkspacePadding** and **FocusedWorkspaceContainerPadding** those of the +//! focused workspace, and **AdjustWorkspacePadding** and **AdjustContainerPadding** make the +//! focused workspace's larger or smaller ([`WindowManager::set_workspace_padding`], //! [`WindowManager::set_container_padding`], [`WindowManager::adjust_workspace_padding`], //! [`WindowManager::adjust_container_padding`]). //! - **WorkAreaOffset**, **MonitorWorkAreaOffset** and **WorkspaceWorkAreaOffset** set the work @@ -1140,9 +1142,23 @@ impl WindowManager { SocketMessage::ContainerPadding(monitor_idx, workspace_idx, size) => { self.set_container_padding(monitor_idx, workspace_idx, size)?; } + SocketMessage::NamedWorkspaceContainerPadding(ref workspace, size) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + self.set_container_padding(monitor_idx, workspace_idx, size)?; + } + } SocketMessage::WorkspacePadding(monitor_idx, workspace_idx, size) => { self.set_workspace_padding(monitor_idx, workspace_idx, size)?; } + SocketMessage::NamedWorkspacePadding(ref workspace, size) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + self.set_workspace_padding(monitor_idx, workspace_idx, size)?; + } + } SocketMessage::FocusedWorkspaceContainerPadding(adjustment) => { let focused_monitor_idx = self.focused_monitor_idx(); diff --git a/komorebi/tests/padding.rs b/komorebi/tests/padding.rs index 92c5c936..3abf9d4f 100644 --- a/komorebi/tests/padding.rs +++ b/komorebi/tests/padding.rs @@ -88,6 +88,17 @@ fn one_window_without_padding(id: u32) -> (Arc, WindowManager) { (fake, wm) } +/// The workspace padding and the container padding each workspace of the focused monitor has of +/// its own +fn paddings(wm: &WindowManager) -> Vec<(Option, Option)> { + wm.focused_monitor() + .unwrap() + .workspaces() + .iter() + .map(|workspace| (workspace.workspace_padding, workspace.container_padding)) + .collect() +} + #[test] fn the_paddings_of_the_focused_workspace_are_set_and_adjusted() { let (fake, mut wm) = desktop_with(&[28_001]); @@ -156,6 +167,63 @@ fn the_paddings_of_a_workspace_are_set_by_its_indices() { ); } +#[test] +fn the_paddings_of_a_workspace_are_set_by_its_name_and_a_name_nobody_has_changes_nothing() { + let (fake, mut wm) = desktop_with(&[28_041]); + send( + &fake, + &mut wm, + SocketMessage::EnsureNamedWorkspaces(0, vec![String::from("main"), String::from("side")]), + ) + .unwrap(); + + // the workspace in front is tiled again at once + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspacePadding(String::from("main"), 20), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_041), Some(rect(25, 25, 1870, 1000))); + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspaceContainerPadding(String::from("main"), 0), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_041), Some(rect(20, 20, 1880, 1010))); + + // another workspace takes its own paddings, and the one in front keeps its tile + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspacePadding(String::from("side"), 7), + ) + .unwrap(); + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspaceContainerPadding(String::from("side"), 3), + ) + .unwrap(); + assert_eq!(fake.rect_of(28_041), Some(rect(20, 20, 1880, 1010))); + assert_eq!(paddings(&wm), [(Some(20), Some(0)), (Some(7), Some(3))]); + + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspacePadding(String::from("nowhere"), 99), + ) + .unwrap(); + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspaceContainerPadding(String::from("nowhere"), 99), + ) + .unwrap(); + assert_eq!(paddings(&wm), [(Some(20), Some(0)), (Some(7), Some(3))]); +} + #[test] fn the_workspaces_offset_wins_over_the_monitors_which_wins_over_the_global_one() { let (fake, mut wm) = one_window_without_padding(28_021); diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 08a85caf..082a3529 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -47,10 +47,11 @@ //! `cross-monitor-move-behaviour` and `toggle-cross-monitor-move-behaviour` set what `move` does //! at the edge of a monitor, and `display-index-preference` gives a monitor an index. //! `eager-focus` focuses the first window of an executable, on any workspace of any monitor. -//! - `workspace-name` names a workspace, which `focus-named-workspace`, `named-workspace-layout` -//! and `named-workspace-tiling` find by its name; `workspace-layout` and `workspace-tiling` set -//! the layout and the tiling of a workspace by its index, and `ensure-workspaces` and -//! `ensure-named-workspaces` give a monitor workspaces up to a number, or with names. +//! - `workspace-name` names a workspace, which `focus-named-workspace`, `named-workspace-layout`, +//! `named-workspace-tiling`, `named-workspace-padding` and `named-workspace-container-padding` +//! find by its name; `workspace-layout` and `workspace-tiling` set the layout and the tiling of +//! a workspace by its index, and `ensure-workspaces` and `ensure-named-workspaces` give a +//! monitor workspaces up to a number, or with names. //! //! `ignore-rule` and `manage-rule` add a rule that keeps an application out of the layout or //! always in it, `session-float-rule` floats the focused window and every window like it until the @@ -297,6 +298,27 @@ gen_padding_subcommand_args! { WorkspacePadding, } +macro_rules! gen_named_padding_subcommand_args { + // SubCommand Pattern + ( $( $name:ident ),+ $(,)? ) => { + $( + #[derive(clap::Parser)] + pub struct $name { + /// Target workspace name + workspace: String, + + /// Pixels to pad with as an integer + size: i32, + } + )+ + }; +} + +gen_named_padding_subcommand_args! { + NamedWorkspaceContainerPadding, + NamedWorkspacePadding, +} + macro_rules! gen_padding_adjustment_subcommand_args { // SubCommand Pattern ( $( $name:ident ),+ $(,)? ) => { @@ -773,9 +795,15 @@ enum SubCommand { /// Set the container padding for the specified workspace #[clap(arg_required_else_help = true)] ContainerPadding(ContainerPadding), + /// Set the container padding for the specified workspace + #[clap(arg_required_else_help = true)] + NamedWorkspaceContainerPadding(NamedWorkspaceContainerPadding), /// Set the workspace padding for the specified workspace #[clap(arg_required_else_help = true)] WorkspacePadding(WorkspacePadding), + /// Set the workspace padding for the specified workspace + #[clap(arg_required_else_help = true)] + NamedWorkspacePadding(NamedWorkspacePadding), /// Set the layout for the specified workspace #[clap(arg_required_else_help = true)] WorkspaceLayout(WorkspaceLayout), @@ -1223,6 +1251,12 @@ fn main() -> eyre::Result<()> { args.size, ))?; } + SubCommand::NamedWorkspaceContainerPadding(args) => { + send_message(&SocketMessage::NamedWorkspaceContainerPadding( + args.workspace, + args.size, + ))?; + } SubCommand::WorkspacePadding(args) => { send_message(&SocketMessage::WorkspacePadding( args.monitor, @@ -1230,6 +1264,12 @@ fn main() -> eyre::Result<()> { args.size, ))?; } + SubCommand::NamedWorkspacePadding(args) => { + send_message(&SocketMessage::NamedWorkspacePadding( + args.workspace, + args.size, + ))?; + } SubCommand::FocusedWorkspacePadding(args) => { send_message(&SocketMessage::FocusedWorkspacePadding(args.size))?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 747317dc..e2ce00c2 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -315,6 +315,14 @@ fn the_padding_subcommands_send_the_workspace_and_the_pixels_they_are_given() { &["container-padding", "1", "0", "8"], r#"{"type":"ContainerPadding","content":[1,0,8]}"#, ); + sends( + &["named-workspace-padding", "mail", "12"], + r#"{"type":"NamedWorkspacePadding","content":["mail",12]}"#, + ); + sends( + &["named-workspace-container-padding", "mail", "8"], + r#"{"type":"NamedWorkspaceContainerPadding","content":["mail",8]}"#, + ); sends( &["adjust-workspace-padding", "increase", "5"], r#"{"type":"AdjustWorkspacePadding","content":["Increase",5]}"#, @@ -689,7 +697,9 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "move-to-workspace.md", "move-workspace-to-monitor.md", "move.md", + "named-workspace-container-padding.md", "named-workspace-layout.md", + "named-workspace-padding.md", "named-workspace-tiling.md", "new-workspace.md", "preselect-direction.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index d2d3a711..64960b8a 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -278,6 +278,10 @@ container-padding 0 0 12 container-padding 0 0 10 workspace-padding 0 0 12 workspace-padding 0 0 10 +named-workspace-container-padding one 12 +named-workspace-container-padding one 10 +named-workspace-padding one 12 +named-workspace-padding one 10 cross-monitor-move-behaviour insert cross-monitor-move-behaviour swap toggle-cross-monitor-move-behaviour From 331db681e27b0a4d26cd432fc94bba20d0ecf8c3 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 19:03:55 -0700 Subject: [PATCH 033/255] feat(wm): stack out of sight on a parking desktop A container has one tile, so the windows of a stack that are not in front have to be out of sight. KWin has nothing a script can set to hide a window except a virtual desktop nobody looks at, which the first spike measured to cost no focus change where minimizing a window cost two. Backend::hide takes a window out of sight and Backend::restore brings it back; the KWin backend parks the window on a desktop named komorebi-park, which the table keeps out of the workspaces, and remembers where each hidden window came from so that it is still on its workspace. KWin saves a desktop in kwinrc as soon as it is made, so komorebi removes the parking desktop when it stops, after the windows are back, and the first snapshot of the next run finds one a killed run left, sends its windows home and removes it. The windows komorebi hid are recorded, so that a minimize the compositor reports for one is not mistaken for the user's. komorebic stack, unstack, stack-all and unstack-all stack and unstack windows. The window container behavior and the float override decide whether a window that opens joins the focused container or floats, for every workspace or for one. vm-stacks stacks windows in a headless KWin, shows a workspace and goes back, stops, and kills the daemon with a window parked. --- README.md | 13 +- docs/cli/stack-all.md | 10 + docs/cli/stack.md | 14 + docs/cli/toggle-float-override.md | 10 + docs/cli/toggle-window-container-behaviour.md | 10 + docs/cli/toggle-workspace-float-override.md | 12 + ...le-workspace-window-container-behaviour.md | 11 + docs/cli/unstack-all.md | 10 + docs/cli/unstack.md | 10 + docs/dev/ARCHITECTURE.md | 145 ++++- docs/dev/DESIGN.md | 37 ++ docs/dev/PLATFORM.md | 59 +- docs/dev/vm-tests.md | 15 +- docs/index.md | 2 + docs/usage/floating-windows.md | 17 + docs/usage/running-komorebi.md | 7 +- docs/usage/stacking-windows.md | 81 +++ komorebi-client/src/lib.rs | 4 +- komorebi/src/backend/fake.rs | 64 ++- komorebi/src/backend/mod.rs | 35 ++ komorebi/src/container.rs | 133 +++++ komorebi/src/core/mod.rs | 9 + komorebi/src/kwin/mod.rs | 184 ++++++- komorebi/src/kwin/state.rs | 503 +++++++++++++++++- komorebi/src/lib.rs | 8 +- komorebi/src/main.rs | 10 +- komorebi/src/process_command.rs | 85 ++- komorebi/src/process_event.rs | 53 +- komorebi/src/state.rs | 20 +- komorebi/src/window.rs | 66 +++ komorebi/src/window_manager.rs | 424 ++++++++++++++- komorebi/src/workspace.rs | 366 ++++++++++++- komorebi/tests/stacks.rs | 481 +++++++++++++++++ komorebi/tests/workspaces.rs | 13 +- komorebic/src/main.rs | 66 ++- komorebic/tests/cli.rs | 55 ++ nix/tests/vm/lib/komorebi_vm/kde.py | 36 ++ nix/tests/vm/lib/tests/test_kde.py | 51 ++ nix/tests/vm/suites/commands/test.py | 12 + nix/tests/vm/suites/stacks/default.nix | 5 + nix/tests/vm/suites/stacks/test.py | 182 +++++++ 41 files changed, 3234 insertions(+), 94 deletions(-) create mode 100644 docs/cli/stack-all.md create mode 100644 docs/cli/stack.md create mode 100644 docs/cli/toggle-float-override.md create mode 100644 docs/cli/toggle-window-container-behaviour.md create mode 100644 docs/cli/toggle-workspace-float-override.md create mode 100644 docs/cli/toggle-workspace-window-container-behaviour.md create mode 100644 docs/cli/unstack-all.md create mode 100644 docs/cli/unstack.md create mode 100644 docs/usage/stacking-windows.md create mode 100644 komorebi/tests/stacks.rs create mode 100644 nix/tests/vm/suites/stacks/default.nix create mode 100644 nix/tests/vm/suites/stacks/test.py diff --git a/README.md b/README.md index 0f402fe3..6e25d65d 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,8 @@ without a checkout of the toolchain. the vocabulary the window manager is written in (`core`), the `Backend` trait through which it reaches a compositor and the in-memory desktop the tests use (`backend`), the backend that reaches KWin through a script it runs and edits - the one setting of KWin's it needs in the user's `kwinrc` (`kwin`), + the one setting of KWin's it needs in the user's `kwinrc` and the parking desktop + it hides the back of a stack on (`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 @@ -139,6 +140,12 @@ reports that a window was shown, closed, focused, minimized or restored, and tiles the workspace in front again. A window open at startup goes to the workspace whose desktop it is on. +A container with more than one window is a stack: the layout gives it one tile, +and the window in front is in sight. The others are hidden, which on KWin means +moved to one more virtual desktop, `komorebi-park`, that nobody looks at and that +is not a workspace. The daemon makes it when it first needs it, removes it when +it stops, and removes one that a run that did not stop left behind. + Everything else reaches the daemon as a message on its socket: one JSON `SocketMessage` per line, handled one at a time with the window manager locked. A message that asks a question is answered on the same connection. A @@ -171,6 +178,10 @@ the previous or the last workspace, `workspace-name` names a workspace for At the edge of a monitor, `focus` and `move` cross to the monitor on that side; `focus-monitor`, `move-to-monitor`, `send-to-monitor` and their kind work on the monitors, and `eager-focus` finds the window of an application wherever it is. +`stack` puts the focused window and the one next to it in one stack, `unstack` +takes it out again, and `stack-all` and `unstack-all` do it for a whole +workspace. `toggle-window-container-behaviour` makes a window that opens join +the focused stack, and `toggle-float-override` makes it float. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/stack-all.md b/docs/cli/stack-all.md new file mode 100644 index 00000000..cf67c6cf --- /dev/null +++ b/docs/cli/stack-all.md @@ -0,0 +1,10 @@ +```text +Stack all windows on the focused workspace + +Usage: stack-all + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/stack.md b/docs/cli/stack.md new file mode 100644 index 00000000..bd145d4f --- /dev/null +++ b/docs/cli/stack.md @@ -0,0 +1,14 @@ +```text +Stack the focused window in the specified direction + +Usage: stack + +Arguments: + + [possible values: left, right, up, down] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-float-override.md b/docs/cli/toggle-float-override.md new file mode 100644 index 00000000..d0b7d4cf --- /dev/null +++ b/docs/cli/toggle-float-override.md @@ -0,0 +1,10 @@ +```text +Enable or disable float override, which makes it so every new window opens in floating mode + +Usage: toggle-float-override + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-window-container-behaviour.md b/docs/cli/toggle-window-container-behaviour.md new file mode 100644 index 00000000..6e4fe4c7 --- /dev/null +++ b/docs/cli/toggle-window-container-behaviour.md @@ -0,0 +1,10 @@ +```text +Toggle the behavior for new windows (stacking or dynamic tiling) + +Usage: toggle-window-container-behaviour + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-workspace-float-override.md b/docs/cli/toggle-workspace-float-override.md new file mode 100644 index 00000000..c48293aa --- /dev/null +++ b/docs/cli/toggle-workspace-float-override.md @@ -0,0 +1,12 @@ +```text +Enable or disable float override, which makes it so every new window opens in floating mode, for the +currently focused workspace. If there was no override value set for the workspace previously it +takes the opposite of the global value + +Usage: toggle-workspace-float-override + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-workspace-window-container-behaviour.md b/docs/cli/toggle-workspace-window-container-behaviour.md new file mode 100644 index 00000000..4d0999c9 --- /dev/null +++ b/docs/cli/toggle-workspace-window-container-behaviour.md @@ -0,0 +1,11 @@ +```text +Toggle the behavior for new windows (stacking or dynamic tiling) for currently focused workspace. If +there was no behavior set for the workspace previously it takes the opposite of the global value + +Usage: toggle-workspace-window-container-behaviour + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/unstack-all.md b/docs/cli/unstack-all.md new file mode 100644 index 00000000..fe35e003 --- /dev/null +++ b/docs/cli/unstack-all.md @@ -0,0 +1,10 @@ +```text +Unstack all windows in the focused container + +Usage: unstack-all + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/unstack.md b/docs/cli/unstack.md new file mode 100644 index 00000000..c559ebf5 --- /dev/null +++ b/docs/cli/unstack.md @@ -0,0 +1,10 @@ +```text +Unstack the focused window + +Usage: unstack + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index d5a8442e..56c35060 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -8,9 +8,9 @@ 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, the backend that reaches KWin, how an event about a window becomes a tile, how workspaces are the compositor's desktops, how -a message on the daemon's socket is answered, how subscribers are notified of both, what the -orders a message gives do, and how the NixOS module runs the daemon. It grows with the code: -each part of the daemon that is added has its place here. +a stack hides its windows, how a message on the daemon's socket is answered, how subscribers +are notified of both, what the orders a message gives do, and how the NixOS module runs the +daemon. It grows with the code: each part of the daemon that is added has its place here. ## Vocabulary @@ -27,6 +27,13 @@ each part of the daemon that is added has its place here. desktop of its own. - **Container**: what a layout places. It gets one tile, and every window in it is put on that tile. +- **Stack**: a container with more than one window. It has one tile, and the window in front + (the container's focused window) is in sight; the others are hidden. +- **Hidden window**: a window of a stack that is not in front, which komorebi has taken out of + sight ([`Backend::hide`]) and recorded in [`HIDDEN_WINDOWS`]. It is alive, not minimized, and + on its workspace. +- **Parking desktop**: the virtual desktop, named `komorebi-park`, that the KWin backend hides + windows on. It is not a workspace. - **Layout**: the arrangement (BSP, columns, rows, ...) that turns a work area and a number of containers into one rectangle, a **tile**, for each container. - **Event**: what the compositor reports about a window: it was shown, destroyed, given @@ -87,9 +94,9 @@ The desktop, as the window manager sees it, is two lists and a pointer: - **The pointer**, a position if the compositor says where it is, and the **focus**, the id of the window that has it. -A command is one of: move and resize a window, focus it, raise it, minimize it or bring it -back, close it, put the pointer in the middle of a rectangle, make desktops for the -workspaces, show a workspace on a monitor, and put a window on a workspace. The workspace a +A command is one of: move and resize a window, focus it, raise it, hide it or restore it, +minimize it or bring it back, close it, put the pointer in the middle of a rectangle, make +desktops for the workspaces, show a workspace on a monitor, and put a window on a workspace. The workspace a window is on, and the one each monitor shows, are queries. The window manager tiles a tree of four levels, each level a [`Ring`]: a list with one @@ -103,8 +110,10 @@ the same thing at every level. own, whether it takes the monitor's window-based offset, its containers, in order, and its floating windows, which are in no container and which the layout does not tile. - A **container** ([`Container`]) has its windows. A new window gets a container of its - own. A container can be locked, which keeps it at its index while others are inserted, - removed or swapped around it. + own, unless the window container behavior says to put it in the focused one. With more than + one window it is a stack: the focused window is in front and the others are hidden. A + container can be locked, which keeps it at its index while others are inserted, removed or + swapped around it. - A **window** ([`Window`]) is a `Copy` handle that carries only the compositor's id. Everything else about the window, and every change to it, goes through the backend. @@ -224,6 +233,54 @@ window put on another desktop by something else (the window menu's "Move to Desk and move come back from KWin as the same reports; the table records them when the command is sent ([`Table::switch_commands`], [`Table::window_workspace_commands`]), so they raise nothing. +## Stacks + +A container has one tile, so when it has more than one window the others have to be out of +sight, and out of the way of the pointer and the focus: the window manager hides them +([`Window::hide`]). Minimizing them would not do. KWin reports a minimize as the user's, and +the windows would be taken for ones the user does not want tiled. What komorebi uses is the one +thing KWin has that hides a window and leaves it alone: a virtual desktop nobody looks at, the +parking desktop. The reasons are in +[DESIGN.md](DESIGN.md#why-are-the-windows-behind-the-front-one-of-a-stack-moved-to-a-parking-desktop). + +A container keeps its front window in sync with what is in sight ([`Container::add_window`], +[`Container::load_focused_window`]): the window that is added or focused is shown, and every +other one is hidden. Operations that change which window is in front, or which container a +window is in, end with that call: stacking and unstacking ([`Workspace::move_window_to_container`], +[`Workspace::new_container_for_focused_window`]), a window that closes +([`Workspace::remove_window`], which brings the next one forward and focuses it), a window that +is floated, and a focus change to a window that is behind ([`Workspace::focus_container_by_window`]). + +[`Window::hide`] puts the window's id in [`HIDDEN_WINDOWS`] before it asks the backend, and +[`Window::restore`] takes it out, so that when the compositor reports something about the window +because of the hide the window manager knows who did it. A `Minimize` for a window in the set is +not the user's and changes nothing. On the way out, [`WindowManager::stop`] and the daemon's +`SIGINT` and `SIGTERM` handler restore every window in the set before the backend shuts down +([`WindowManager::restore_all_windows`]). + +The KWin backend hides a window by putting it on the parking desktop. The table keeps for each +window whether it is parked and the desktop it came from ([`Table::hide_commands`], +[`Table::restore_commands`]): a hidden window is still on its workspace for every query +([`Table::window_workspace`]), a window put on another workspace while it is hidden is hidden +still and comes back there ([`Table::window_workspace_commands`]), and KWin's report that the +window moved to the parking desktop is not a `WorkspaceMove`. The parking desktop is made the +first time it is needed ([`NeedsPark`], `create_park_desktop` in [`kwin`]), by position, so +that it stays after the workspaces' desktops. The table checks that KWin still lists it before it +sends a window there, and asks for a new one when somebody removed it. + +An application that raises a hidden window, or a click on it in the task manager, makes KWin +switch that monitor to the parking desktop. The table notices that a monitor shows it, sends the +monitor back to the desktop it showed before, and raises no `WorkspaceChange`; the window's own +`FocusChange` then brings it to the front of its stack. + +KWin keeps its virtual desktops in `kwinrc` as soon as one is made, so a parking desktop that +komorebi does not remove stays for every later session. The backend removes it in `shutdown`, +after the restoring commands have reached the bridge. A daemon that was killed leaves it, with +windows on it: the first snapshot the next daemon gets lists a desktop with that name, which the +table treats as stale ([`Table::stale_park`]). It is never the parking desktop of the new run. +The snapshot sends the windows on it to the first workspace's desktop, and half a second later +the backend removes it (`sweep_stale_park`). + ## The command socket The daemon takes messages on a Unix socket, `komorebi.sock` in [`DATA_DIR`] @@ -363,6 +420,24 @@ any other, so its events find it, and [`Workspace::update`] leaves it where it i floated window goes is [`WindowManagementBehaviour::toggle_float_placement`]: by default it stays where it is. +`StackWindow` puts the focused window and the window of the container in a direction in one +container ([`WindowManager::add_window_to_container`]): the focused window goes to the front of +that container, or, when the focused container is a stack and the other is not, the other +container's window goes into the stack. `UnstackWindow` takes the front window out of a stack +into a container of its own after it ([`WindowManager::remove_window_from_container`]), `StackAll` +puts every window of the workspace in one container ([`WindowManager::stack_all`]), and +`UnstackAll` takes them out again ([`WindowManager::unstack_all`]). Each ends with the workspace +tiled again, and the window that was in front has the focus. + +A window that opens gets the behavior [`WindowManager::window_management_behaviour`] says for +its workspace: a container of its own (`Create`, the default), or a place in the focused +container (`Append`), and a floating window with the float override on. A workspace's own +[`Workspace::window_container_behaviour`] and [`Workspace::float_override`] win over the window +manager's, and `Append` on an empty workspace is `Create`. `ToggleWindowContainerBehaviour` and +`ToggleFloatOverride` flip the window manager's, and `ToggleWorkspaceWindowContainerBehaviour` and +`ToggleWorkspaceFloatOverride` the focused workspace's, which starts from the opposite of the +window manager's value the first time. + `ToggleLock` locks the focused container, or unlocks it ([`WindowManager::toggle_lock`]), and `LockMonitorWorkspaceContainer` and `UnlockMonitorWorkspaceContainer` do the same for a container given by its indices. A lock changes nothing until containers are inserted, removed or @@ -522,10 +597,10 @@ module's unit. operations on it (tile the workspace in front, tile every monitor, take a minimized window out, move the focus, move the focused container, change the layout, resize or promote the focused container, float a window, lock a container, set the padding of a - workspace, manage and unmanage a window, show a workspace, move a container to another - workspace, follow a workspace switch made by something else, name a workspace and find - it by its name, set the layout of a workspace that is not in front, focus another monitor, - and move containers and workspaces between monitors). + workspace, manage and unmanage a window, stack and unstack windows, show a workspace, move a + container to another workspace, follow a workspace switch made by something else, name a + workspace and find it by its name, set the layout of a workspace that is not in front, focus + another monitor, and move containers and workspaces between monitors). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -537,7 +612,8 @@ module's unit. - [`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; [`kwin::kwinrc`](../../komorebi/src/kwin/kwinrc.rs), the editor of the user's `kwinrc`, which - keeps the values it changes and puts them back; and + keeps the values it changes and puts them back; the parking desktop is made, swept and removed + in `kwin` and tracked in `kwin::state`; and [`bridge.js`](../../komorebi/src/kwin/bridge.js), the bridge. - [`process_command`](../../komorebi/src/process_command.rs): the thread that listens on the socket, and what the window manager does with each message. @@ -583,6 +659,10 @@ the fake. The window manager is its only caller, through [`backend`]. The contra backend asked for a workspace that has no desktop makes the desktops up to it (`ensure_workspaces`). The compositor shows and hides the windows of the desktops, and a backend reports a switch or a move it did not make as an event. +- A hidden window (`hide`) is out of sight, alive, not minimized, and on the workspace it was + on until `restore`: `window_workspace` still names that workspace, and + `set_window_workspace` changes where it comes back to, not where it is hidden. Only the back of + a stack is hidden: nothing is hidden to leave a workspace. - `shutdown`, `is_window`, `window_rect` and `monitor_from_point` have defaults, written in terms of the queries. An implementor should not need to override them, except `shutdown` when it created something in the compositor that has to be given up. @@ -595,7 +675,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A backend can be shared between threads | type system: `Backend: Send + Sync + 'static` | `compile_fail,E0277` on [`Backend`] | none | | The window manager asks for a backend that was never installed | runtime error: [`backend`] panics, naming [`set_backend`] and [`with_backend`] | `# Panics` on [`backend`] | none | | A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none | -| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none | +| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error`, `a_command_about_a_closed_window_is_an_error` and `hiding_or_restoring_a_window_nobody_opened_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none | | A locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window`, `test_locked_containers_remove_window`, `a_window_that_opens_does_not_push_a_locked_container_from_its_index` | `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`, `an_ignore_rule_keeps_a_window_unmanaged` | `ManageRule` | | A window the user unmanaged stays out of the layout until it is managed again | framework path: `handle_event` checks the list of unmanaged windows before it acts on any event but a removal | `unmanage_takes_the_focused_window_out_until_manage_takes_it_back` | none | @@ -630,6 +710,15 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A workspace is closed only when it has no window and no name and is not the monitor's last | framework path: the `CloseWorkspace` arm of [`WindowManager::process_command`] checks all three | `new_workspace_adds_one_and_close_workspace_removes_it_when_it_is_empty_and_unnamed` | none | | The focus and a move at the edge of a monitor go to the monitor on that side, and fail only when there is none | framework path: the `None` arms of [`WindowManager::focus_container_in_direction`] and [`WindowManager::move_container_in_direction`] | `the_focus_crosses_to_the_monitor_on_that_side`, `a_move_at_the_edge_of_a_monitor_swaps_with_the_window_on_the_next_one_by_default`, `focus_towards_a_side_with_no_window_is_an_error_and_changes_nothing` | `NoOp` keeps a move on its monitor | | A window shown or focused on another monitor focuses that monitor, and nothing else does | framework path: `handle_event` focuses the monitor of a `Show` or `FocusChange` before it acts on it | `a_window_that_opens_on_the_monitor_that_is_not_focused_focuses_it`, `a_scrolling_strip_on_the_next_monitor_over_does_not_take_focus_with_it` | none | +| Only the window in front of a stack is in sight | framework path: [`Container::add_window`] and [`Container::load_focused_window`] hide every window of the container but the focused one, and every operation that changes the front ends with the call | `a_window_added_to_a_container_is_in_front_and_the_others_are_hidden`, `loading_the_focused_window_shows_it_and_hides_the_rest`, `stacking_puts_two_windows_in_one_container_and_hides_the_one_behind`, `vm-stacks` ("exactly one window is on it") | none | +| A hidden window is still on its workspace, and is not reported as moved | framework path: the table keeps the desktop a window came from, and a move to the parking desktop is its own | `parking_a_window_hides_it_without_unmanaging_it`, `komorebis_own_move_and_its_park_and_restore_raise_nothing_new`, `a_window_is_put_on_a_workspace_by_putting_it_on_its_desktop` | none | +| What the compositor reports about a window komorebi hid is not taken for the user's doing | framework path: [`Window::hide`] records the window in [`HIDDEN_WINDOWS`] before it asks the backend, and the `Minimize` arm of `handle_event` checks it | `a_minimize_komorebi_asked_for_is_not_mistaken_for_the_user`, `a_minimize_the_user_asked_for_takes_the_window_out_of_the_layout` | none | +| Closing the window in front of a stack brings the next one forward | framework path: [`Workspace::remove_window`] shows the container's new front window and focuses it | `closing_the_window_in_front_of_a_stack_brings_the_next_one_forward`, `vm-stacks` ("closing the window in view") | none | +| The back of a stack stays hidden when its workspace is shown again | framework path: [`Workspace::restore`] restores the front window of each container and no other | `the_back_of_a_stack_stays_hidden_across_a_workspace_round_trip`, `vm-stacks` ("a workspace round trip") | none | +| A window is never sent to a parking desktop that is not there | framework path: [`Table::hide_commands`] asks for a new one unless KWin lists the one it made | `a_parking_desktop_that_has_gone_is_made_again_not_sent_windows` | none | +| A monitor raised onto the parking desktop is sent back | framework path: the table sends the monitor back to the desktop it showed before | `following_a_hidden_window_to_the_parking_desktop_sends_that_output_back` | none | +| A clean stop leaves no window hidden and no parking desktop | framework path: [`WindowManager::stop`] and the signal handler restore every hidden window, and the backend's `shutdown` removes the desktop after the restoring commands have gone out | `restoring_every_window_brings_back_the_hidden_ones_unless_it_is_told_to_ignore_that`, `vm-stacks` ("a clean stop puts every window back") | `SIGKILL`, and `StopIgnoreRestore`, which restores nothing | +| A parking desktop a dead daemon left is swept by the next one, and its windows go home | startup check: the first snapshot marks it stale, sends its windows to the first workspace's desktop, and the backend removes it | `a_parking_desktop_left_by_a_crashed_run_is_swept`, `a_stale_parking_desktop_is_not_the_one_windows_are_hidden_on`, `vm-stacks` ("a crash leaves a parking desktop") | none | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | 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 | @@ -767,6 +856,10 @@ A window is shown, and ends up on a tile: [`komorebi/tests/monitors.rs`](../../komorebi/tests/monitors.rs), two monitors: crossing from one to the other, the monitor commands and `EagerFocus`; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the `kwinrc` editor and its tests. +- [`komorebi/tests/stacks.rs`](../../komorebi/tests/stacks.rs): stacking, unstacking and the windows + a stack hides, the behavior of new windows and the float override, against the fake; + [`nix/tests/vm/suites/stacks`](../../nix/tests/vm/suites/stacks/test.py), the same in a real + KWin, with the parking desktop, a crash and a stop. - [`nix/tests/vm/suites/workspace-switch`](../../nix/tests/vm/suites/workspace-switch/test.py): workspaces as a real KWin's desktops, switched by `komorebic` and by KWin; [`nix/tests/vm/suites/kwin-contract`](../../nix/tests/vm/suites/kwin-contract/test.py), the @@ -798,6 +891,30 @@ A window is shown, and ends up on a tile: [`MatchingRule`]: ../../komorebi/src/core/config_generation.rs [`ApplicationIdentifier`]: ../../komorebi/src/core/mod.rs [`Window::set_position`]: ../../komorebi/src/window.rs +[`Window::hide`]: ../../komorebi/src/window.rs +[`Window::restore`]: ../../komorebi/src/window.rs +[`HIDDEN_WINDOWS`]: ../../komorebi/src/lib.rs +[`Container::add_window`]: ../../komorebi/src/container.rs +[`Container::load_focused_window`]: ../../komorebi/src/container.rs +[`Workspace::move_window_to_container`]: ../../komorebi/src/workspace.rs +[`Workspace::new_container_for_focused_window`]: ../../komorebi/src/workspace.rs +[`Workspace::remove_window`]: ../../komorebi/src/workspace.rs +[`Workspace::focus_container_by_window`]: ../../komorebi/src/workspace.rs +[`Workspace::restore`]: ../../komorebi/src/workspace.rs +[`Workspace::window_container_behaviour`]: ../../komorebi/src/workspace.rs +[`Workspace::float_override`]: ../../komorebi/src/workspace.rs +[`WindowManager::add_window_to_container`]: ../../komorebi/src/window_manager.rs +[`WindowManager::remove_window_from_container`]: ../../komorebi/src/window_manager.rs +[`WindowManager::stack_all`]: ../../komorebi/src/window_manager.rs +[`WindowManager::unstack_all`]: ../../komorebi/src/window_manager.rs +[`WindowManager::restore_all_windows`]: ../../komorebi/src/window_manager.rs +[`WindowManager::window_management_behaviour`]: ../../komorebi/src/window_manager.rs +[`Backend::hide`]: ../../komorebi/src/backend/mod.rs +[`Table::hide_commands`]: ../../komorebi/src/kwin/state.rs +[`Table::restore_commands`]: ../../komorebi/src/kwin/state.rs +[`Table::window_workspace`]: ../../komorebi/src/kwin/state.rs +[`Table::stale_park`]: ../../komorebi/src/kwin/state.rs +[`NeedsPark`]: ../../komorebi/src/kwin/state.rs [`Workspace::new_container_for_window`]: ../../komorebi/src/workspace.rs [`WindowManager`]: ../../komorebi/src/window_manager.rs [`WindowManager::process_event`]: ../../komorebi/src/process_event.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 34f6536d..5ae2b583 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -259,3 +259,40 @@ plain ini, which komorebi changes line by line, and asks KWin to reload its conf It is the user's setting, so the value komorebi found is kept in a backup file and put back when komorebi stops; a backup a crash left behind keeps the value from before the first run, and the next run puts it back. + +## Why are the windows behind the front one of a stack moved to a parking desktop? + +Because a container has one tile, so the windows of a stack that are not in front have to be out +of sight, and a virtual desktop nobody looks at was the one way to do that which the spikes found +to cost no focus change. The first spike hid six tiled windows and showed them again three ways. +Minimizing +them gave the geometry back exactly, but KWin picked a new active window as each one minimized, +two focus events nobody asked for. Moving them to a virtual desktop of their own gave no focus +event and the geometry back exactly. Moving them off the screen worked too, since KWin does not +clamp a scripted move, but the windows stay mapped on the current desktop, in the window switcher, +the overview and the task manager, so it was not offered. KWin has nothing else: `Window.hidden` +cannot be set by a script. The spike's source reading, KWin 6.8.1, is in +[PLATFORM.md](PLATFORM.md#the-parking-desktop). The other platforms have a setting that chooses +how windows are hidden; on KDE there is one way, and so no such setting. + +The cost is that KWin keeps a virtual desktop in `kwinrc` as soon as it is made. A run that failed +after making the parking desktop left it there for every later session. So komorebi removes the +desktop when it stops, after the commands that bring the windows back have reached the bridge, and +the first snapshot of the next run finds a leftover, sends the windows on it to the first +workspace's desktop and removes it. A leftover is never used as the parking desktop of the new +run, since it is about to be removed and anything parked on it would go with it; the new run makes +its own the first time it needs one. Before each hide the table also checks that the desktop it +made is still listed, because somebody can remove it in System Settings, and a window sent to a +desktop that is not there has nowhere to go and nothing says so. + +Activating a window that is on another desktop makes KWin switch that output to the window's +desktop (see [PLATFORM.md](PLATFORM.md#per-output-virtual-desktops)), so a click on a hidden +window in the task manager would leave the monitor showing the parking desktop, which has nothing +on it but hidden windows. The table sends the monitor straight back to the desktop it showed +before, and the window's own focus change then brings it to the front of its stack. + +komorebi keeps a table of the windows it hid, [`HIDDEN_WINDOWS`](../../komorebi/src/lib.rs), and +records a window in it before it asks the backend to hide it. What the compositor reports about a +hidden window (a minimize, a move to another desktop) is the echo of a command komorebi sent, and +the window manager has to be able to tell that from the user's own: a window that the user +minimizes leaves the layout, and one komorebi hid does not. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index efa56ec5..50e5ba32 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -21,6 +21,8 @@ was measured with KWin 6.8.1, Plasma 6.8.1 and Qt 6.12.0 from nixpkgs `d3b13ad` - **Output**: KWin's name for a monitor. - **Desktop**: one of KWin's virtual desktops. Each output shows one; komorebi's workspace `i` is desktop `i`. +- **Parking desktop**: the desktop named `komorebi-park`, which komorebi makes to hide the back of + a stack on. It is not a workspace. - **Headless KWin**: `kwin_wayland --virtual`, a KWin with virtual outputs and no display, which the VM tests run ([vm-tests.md](vm-tests.md)). @@ -58,6 +60,29 @@ outputs: - Desktops are global: every output has the same desktops, with the same names, and each output shows one of them. The ids of the desktops are UUIDs; the bridge names them by id. +### The parking desktop + +Why komorebi hides windows on a desktop of its own is in +[DESIGN.md](DESIGN.md#why-are-the-windows-behind-the-front-one-of-a-stack-moved-to-a-parking-desktop). +What it relies on KWin for, at time of writing (2026-10-27), measured by the spikes on KWin +6.8.1 (nixpkgs `d3b13ad`, 2026-10-24) unless it says otherwise. The VM test `vm-stacks` runs +komorebi's use of them in a headless KWin: + +- A window on another desktop of its output is out of sight, and moving it there and back gives + its frame back exactly. Hiding six windows this way raised no `activated` event; minimizing + them raised two. +- KWin saves a virtual desktop in `kwinrc` as soon as it is made. A desktop that komorebi made + and did not remove, because it was killed, is in every later session. +- Activating a window that is on another desktop of its output switches that output to the + window's desktop (see [Per-output virtual desktops](#per-output-virtual-desktops)), which for a + hidden window is the parking desktop. +- `Window.hidden` is read-only to a script, and the only thing in KWin's 6.8.1 sources that sets + it is a layer-shell window (an auto-hide panel). This is a reading of the sources, not a + measurement. +- A window on the parking desktop is still a window of the session. Whether Plasma's task manager + lists it depends on the task manager's setting for showing the windows of the current desktop + only; the VM tests have no panel, so this is not measured. + ### Wayland komorebi runs in a Plasma Wayland session. There is no X11 session of Plasma 6.8 to run it in. @@ -107,8 +132,15 @@ reload its configuration. If a workspace has no desktop, it creates the missing `org.kde.KWin.VirtualDesktopManager`, named "Workspace 1", "Workspace 2" and so on. A desktop that is already there keeps its name. -Every command of the window manager (move and resize, focus, raise, minimize, bring back or -close a window, show a workspace on an output, put a window on a workspace) is queued for the +When a stack hides a window for the first time, it makes one more desktop, named `komorebi-park`, +after the desktops of the workspaces (the missing workspace desktops are made by position, so that +it stays last), and moves the window there. The desktop is not a workspace: komorebi counts the +workspaces without it, and a window on it is on the workspace it will come back to. It checks that +KWin still lists the desktop before it sends another window there. + +Every command of the window manager (move and resize, focus, raise, hide or restore, minimize, +bring back or close a window, show a workspace on an output, put a window on a workspace) is +queued for the bridge, which gets the queue as the answer to its held call and carries the commands out in KWin, in order. The script API cannot move the pointer, so when the pointer follows the focus komorebi invokes KWin's own "Move Mouse to Focus" shortcut, @@ -128,15 +160,20 @@ an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a runnin #### What komorebi leaves behind -When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it puts back -the value `PerOutputVirtualDesktops` had in `kwinrc` (or removes the key, when the user had -none) and asks KWin to reload its configuration, asks KWin to unload the script, closes an -empty connection to each subscriber, and removes the socket. The desktops it created stay: -they are the user's desktops from then on. The file `bridge.js` stays in the runtime +When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it brings back +the windows it hid, waits until the commands that do so have reached the bridge, removes the +parking desktop, puts back the value `PerOutputVirtualDesktops` had in `kwinrc` (or removes the +key, when the user had none) and asks KWin to reload its configuration, asks KWin to unload the +script, closes an empty connection to each subscriber, and removes the socket. The desktops it +created for workspaces stay: they are the user's desktops from then on. A `StopIgnoreRestore` +message stops it the same way, except that it does not bring the windows back: the parking desktop +is removed all the same. 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, the socket file in the runtime directory, and per-output desktops -on, until the next start replaces the script and the socket, and its stop puts the setting -back (the backup in the runtime directory keeps the user's value), or the session ends. +KWin, reporting to nobody, the socket file in the runtime directory, per-output desktops +on, and the parking desktop with the hidden windows on it, until the next start replaces the +script and the socket, sends the windows on the parking desktop to the first workspace's desktop +and removes the desktop, and its stop puts the setting back (the backup in the runtime +directory keeps the user's value), or the session ends. ### A headless KWin @@ -182,7 +219,7 @@ What komorebi calls: | `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `AddMatch(s)`, for the signal `NameOwnerChanged` | at start, to see KWin leave the bus and come back | | `org.kde.kglobalaccel` | `/component/kwin` | `org.kde.kglobalaccel.Component` | `invokeShortcut(s)`, with `MoveMouseToFocus` | when the pointer follows the focus | | `org.kde.KWin` | `/KWin` | `org.kde.KWin` | `reconfigure()` | after komorebi changed `kwinrc`, at start and at exit | -| `org.kde.KWin` | `/VirtualDesktopManager` | `org.kde.KWin.VirtualDesktopManager` | the property `desktops`, `createDesktop(us)`, `setDesktopName(ss)` | when a workspace has no desktop, and at start | +| `org.kde.KWin` | `/VirtualDesktopManager` | `org.kde.KWin.VirtualDesktopManager` | the properties `desktops` and `count`, `createDesktop(us)`, `setDesktopName(ss)`, `removeDesktop(s)` | when a workspace has no desktop, and at start; `createDesktop` also for the parking desktop, the first time a window is hidden, and `removeDesktop` for it when komorebi stops and for one a killed run left | The property `desktops` is introspected as `a(iss)`, a position, an id and a name for each desktop, and the value on the wire is `a(uss)`: komorebi reads it as that. It is read uncached, diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index 28e1a8a3..425e5403 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -118,17 +118,18 @@ the run. clients. - `start_komorebi(*args)` starts the daemon in the session, with the module's `execStart` and `args` after it (not `--log-level`, which `execStart` has), - `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. + `stop_komorebi()` stops it with `SIGTERM`, `kill_komorebi()` kills it with + `SIGKILL`, as a crash does, `komorebi_log()` returns its log since it was + last started, and `script_loaded()` asks KWin whether it runs the bridge. `restart_kwin()` stops the session's KWin and starts a new one on the same bus, as when the compositor of a running session crashes, and waits for it. - `komorebic(*args)` runs `komorebic` in the session and returns what it printed, failing the test if it fails. `state()` is the daemon's state as `komorebic state` prints it, `managed(workspace)` the number of windows the daemon has on a workspace of the first monitor, `managed_all()` the number it - has on every workspace of every monitor (floating windows too), and - `focused_title(workspace)` the title of the window it has focused there. + has on every workspace of every monitor (floating windows too), + `containers(workspace)` the titles of the windows of each of its containers, + and `focused_title(workspace)` the title of the window it has focused there. - `daemon` reads the daemon's view of the desktop from that log, at the debug level the nodes set: `daemon.events(log)` lists the window events it handled, in order, `daemon.window_ids(log)` maps a window's title to the daemon's id @@ -136,7 +137,9 @@ the run. for, for each window. - `desk(wid)` is the number of the desktop a window is on and `shown()` the one KWin shows, both counted from 1 as `kdotool` counts, `desktops()` how many - desktops KWin has, and `kwinrc(group, key)` a value of the user's `kwinrc`. + desktops KWin has, `desktop_names()` their names in order (the parking desktop + of a stack is the one named `komorebi-park`), and `kwinrc(group, key)` a value + of the user's `kwinrc`. - `kwin_script(name, source, keep=)` runs a KWin script and returns the lines it reported: the script calls `report(...)`, which `print`s a line marked with `name` to KWin's log, and ends with `report("done")`. A script that is kept diff --git a/docs/index.md b/docs/index.md index 8ee8224b..e1449e3c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -34,6 +34,8 @@ anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to sta daemon, ask it what it is doing and read its log. [Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window, [Moving windows](usage/moving-windows.md) how to move the focused window to another tile, +[Stacking windows](usage/stacking-windows.md) how to put windows on one tile and have the others +wait out of sight, [Layouts](usage/layouts.md) how to change the arrangement of the tiles, [Resizing windows](usage/resizing-windows.md) how to change the size of one, [Floating windows](usage/floating-windows.md) how to take a window out of the layout, diff --git a/docs/usage/floating-windows.md b/docs/usage/floating-windows.md index 83b44797..fecad0d6 100644 --- a/docs/usage/floating-windows.md +++ b/docs/usage/floating-windows.md @@ -13,3 +13,20 @@ komorebic toggle-float A floated window keeps its size and position by default. The floating windows of a workspace are in the daemon's state as `floating_windows`, next to its containers. + +## Windows that open floating + +With the float override on, every window that opens floats instead of getting a tile. +[`komorebic toggle-float-override`](../cli/toggle-float-override.md) turns it on and off for every +workspace, and +[`komorebic toggle-workspace-float-override`](../cli/toggle-workspace-float-override.md) for the +focused workspace only: the first time it takes the opposite of what every workspace has, and from +then on it follows its own setting. + +```sh +komorebic toggle-float-override +komorebic toggle-workspace-float-override +``` + +The override is in the daemon's state, as `float_override` for every workspace and in each +workspace that has one of its own. diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md index cf0e8020..c9b74700 100644 --- a/docs/usage/running-komorebi.md +++ b/docs/usage/running-komorebi.md @@ -45,9 +45,10 @@ komorebic start -- --log-level debug komorebic start -- --fake-backend ``` -[`komorebic stop`](../cli/stop.md) tells the daemon to stop. It asks KWin to unload its -script, removes its socket and exits. Stopping the process with `SIGINT` or `SIGTERM` does -the same. +[`komorebic stop`](../cli/stop.md) tells the daemon to stop. It brings back the windows it hid +(the back of a stack, [stacking windows](stacking-windows.md)), removes the desktop they were +hidden on, asks KWin to unload its script, removes its socket and exits. Stopping the process with +`SIGINT` or `SIGTERM` does the same. ## Asking komorebi what it is doing diff --git a/docs/usage/stacking-windows.md b/docs/usage/stacking-windows.md new file mode 100644 index 00000000..630aefc6 --- /dev/null +++ b/docs/usage/stacking-windows.md @@ -0,0 +1,81 @@ +# Stacking windows + +A stack is a container with more than one window. The windows share one tile of the layout, and +one of them, the window in front, is in sight: the others are out of the way. Stacking puts two +windows on one tile, so the layout has one tile fewer to give out. + +## Putting windows in a stack + +[`komorebic stack`](../cli/stack.md) puts the focused window and the window on one side of it in +one stack: `left`, `right`, `up` or `down`. As with +[`komorebic focus`](focusing-windows.md#in-a-direction), the layout decides which tile is on which +side. The focused window ends up in front, and it keeps the focus. Where the layout has no tile on +that side, nothing happens. + +```sh +komorebic stack left +komorebic stack down +``` + +[`komorebic unstack`](../cli/unstack.md) takes the window in front out of its stack and puts it +in a tile of its own after the stack, and the next window of the stack is in front again. A +window that is alone on its tile cannot be unstacked, and the daemon logs "a container must have +at least one window". + +```sh +komorebic unstack +``` + +[`komorebic stack-all`](../cli/stack-all.md) puts every window of the focused workspace in one +stack, in the order they had, with the focused window in front. +[`komorebic unstack-all`](../cli/unstack-all.md) takes every window out of the focused stack, +each onto a tile of its own, and the window that had the focus keeps it. + +```sh +komorebic stack-all +komorebic unstack-all +``` + +A stack moves as one: moving it with [`komorebic move`](moving-windows.md#in-a-direction) or to +another workspace takes every window in it. When the window in front closes, the next window of +the stack comes to the front and has the focus. + +## Windows that open into a stack + +By default a window that opens gets a tile of its own. With the window container behavior set to +`append`, a window that opens joins the focused stack instead, in front, and a workspace with no +window still gives it a tile of its own, since there is nothing to join. +[`komorebic toggle-window-container-behaviour`](../cli/toggle-window-container-behaviour.md) +switches every workspace between the two. +[`komorebic toggle-workspace-window-container-behaviour`](../cli/toggle-workspace-window-container-behaviour.md) +does it for the focused workspace only: the first time, it takes the opposite of what every +workspace has, and from then on it follows its own setting. + +```sh +komorebic toggle-window-container-behaviour +komorebic toggle-workspace-window-container-behaviour +``` + +The setting is in the daemon's state, as `new_window_behaviour` for every workspace and as +`window_container_behaviour` in each workspace that has one of its own. + +## Where the windows behind go + +komorebi does not minimize the windows behind the front one: it moves them to a virtual desktop +that nobody looks at, which it makes when it first needs it and calls `komorebi-park`. A window +there is still open, still on its workspace as far as komorebi is concerned, and still in the +stack, and it comes back to the desktop of its workspace when it is brought to the front, when it +is unstacked, and when komorebi stops. The parking desktop is the last desktop, after the ones +that are workspaces, and is not one of them. + +KWin keeps its virtual desktops in its configuration as soon as one is made, so the parking +desktop would be there in the next session if komorebi did not remove it. It does when it stops. +If komorebi did not get to stop (it was killed, or the session ended under it), the next komorebi +finds the parking desktop in KWin's list, sends the windows on it back to the first workspace's +desktop, and removes it. If the parking desktop is removed while komorebi runs, the next hide +makes a new one. + +A window on the parking desktop can still be reached by something else. Raising one, with a +click in the task manager, makes KWin show the parking desktop on that monitor, and komorebi +sends the monitor straight back to the workspace it was showing. The window that was raised +becomes the front of its stack when komorebi handles its focus change. diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index a0c037b7..b155a4ba 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -198,7 +198,7 @@ where /// # let daemon = std::thread::spawn(move || -> std::io::Result<()> { /// # let (mut stream, _) = listener.accept()?; /// # BufReader::new(stream.try_clone()?).read_line(&mut String::new())?; -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// # stream.write_all(state.as_bytes()) /// # }); /// use komorebi_client::SocketMessage; @@ -260,7 +260,7 @@ pub fn send_query(message: &SocketMessage) -> std::io::Result { /// # let mut message = String::new(); /// # BufReader::new(stream).read_line(&mut message)?; /// # let subscriber = komorebi_client::DATA_DIR.join("bar.sock"); -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// # let notification = format!(r#"{{"event":{message},"state":{state}}}"#); /// # std::os::unix::net::UnixStream::connect(subscriber)?.write_all(notification.as_bytes())?; /// # Ok(message) diff --git a/komorebi/src/backend/fake.rs b/komorebi/src/backend/fake.rs index 2c2c52c6..04b9f248 100644 --- a/komorebi/src/backend/fake.rs +++ b/komorebi/src/backend/fake.rs @@ -44,6 +44,10 @@ pub enum Command { Focus(u32, bool), /// [`Backend::raise`]. Raise(u32), + /// [`Backend::hide`]. + Hide(u32), + /// [`Backend::restore`]. + Restore(u32), /// [`Backend::minimize`]. Minimize(u32), /// [`Backend::unminimize`]. @@ -66,6 +70,8 @@ struct State { /// [`FakeBackend::permissive`]). permissive: bool, windows: HashMap, + /// the windows that are hidden, in the order they were + hidden: Vec, min_sizes: HashMap, monitors: Vec, foreground: Option, @@ -252,8 +258,14 @@ impl FakeBackend { self.state.lock().windows.get(&id).map(|w| w.rect) } - /// Returns true if and only if the window can be seen: it is alive, not minimized, and on the - /// workspace its monitor shows. This is what the compositor does with desktops. + /// Returns true if and only if the window is hidden ([`Backend::hide`]), as opposed to being + /// on a workspace that is not showing. + pub fn is_hidden(&self, id: u32) -> bool { + self.state.lock().hidden.contains(&id) + } + + /// Returns true if and only if the window can be seen: it is alive, not minimized, not hidden + /// and on the workspace its monitor shows. This is what the compositor does with desktops. pub fn on_screen(&self, id: u32) -> bool { let state = self.state.lock(); let Some(window) = state.windows.get(&id) else { @@ -264,7 +276,10 @@ impl FakeBackend { .and_then(|m| state.shown.get(&m)) .copied() .unwrap_or(0); - window.alive && !window.minimized && state.window_ws.get(&id).copied().unwrap_or(0) == shown + window.alive + && !window.minimized + && !state.hidden.contains(&id) + && state.window_ws.get(&id).copied().unwrap_or(0) == shown } /// Returns the workspace a window is on, if it was ever opened. @@ -398,6 +413,20 @@ impl Backend for FakeBackend { self.record(id, Command::Raise(id), |_| ()) } + fn hide(&self, id: u32) -> eyre::Result<()> { + self.record(id, Command::Hide(id), |state| { + if !state.hidden.contains(&id) { + state.hidden.push(id); + } + }) + } + + fn restore(&self, id: u32) -> eyre::Result<()> { + self.record(id, Command::Restore(id), |state| { + state.hidden.retain(|h| *h != id); + }) + } + fn minimize(&self, id: u32) -> eyre::Result<()> { self.record(id, Command::Minimize(id), |state| { if let Some(w) = state.windows.get_mut(&id) { @@ -680,6 +709,35 @@ mod tests { Ok(()) } + #[test] + fn a_hidden_window_is_out_of_sight_on_its_workspace_until_it_is_restored() -> eyre::Result<()> { + let fake = fake_with(&[1]); + + fake.hide(1)?; + fake.hide(1)?; + + assert!(fake.is_hidden(1) && !fake.on_screen(1)); + assert_eq!(fake.window_workspace(1), Some(0)); + assert!(fake.window(1).is_some_and(|w| w.alive && !w.minimized)); + + fake.restore(1)?; + + assert!(!fake.is_hidden(1) && fake.on_screen(1)); + assert_eq!( + fake.commands(), + [Command::Hide(1), Command::Hide(1), Command::Restore(1)] + ); + Ok(()) + } + + #[test] + fn hiding_or_restoring_a_window_nobody_opened_is_an_error() { + let fake = fake_with(&[1]); + + assert!(fake.hide(9).is_err()); + assert!(fake.restore(9).is_err()); + } + #[test] fn putting_a_window_nobody_opened_on_a_workspace_is_an_error() { let fake = fake_with(&[1]); diff --git a/komorebi/src/backend/mod.rs b/komorebi/src/backend/mod.rs index 7050c43b..e74612a4 100644 --- a/komorebi/src/backend/mod.rs +++ b/komorebi/src/backend/mod.rs @@ -28,6 +28,14 @@ //! to be put on workspace `i` ([`Backend::set_window_workspace`]), and the compositor does the //! showing, the hiding and the focusing. When something else changes what a monitor shows, the //! backend raises an event and the window manager follows it. +//! +//! # Hiding +//! +//! The one thing the window manager hides itself is the back of a stack: a container tiles one +//! window, so the others in it are taken out of sight ([`Backend::hide`]) and brought back +//! ([`Backend::restore`]) when they are given the tile. A hidden window stays alive, stays on its +//! workspace and is not minimized, so what the compositor reports about it is not taken for the +//! user's doing (the window manager keeps a table of the windows it has hidden). #![deny(missing_docs)] @@ -101,6 +109,9 @@ pub struct MonitorInfo { /// one of them at a time ([`Backend::switch_workspace`]). The compositor shows the windows of the /// workspace in front and hides the others; the window manager never hides a window to leave a /// workspace. +/// - A hidden window ([`Backend::hide`]) is still alive and still on its workspace: it is out of +/// sight until [`Backend::restore`], and [`Backend::window_workspace`] names the workspace it +/// comes back to. /// - A backend asked to show a workspace, or to put a window on one, that has no desktop yet makes /// the desktops up to it first. /// @@ -133,6 +144,8 @@ pub struct MonitorInfo { /// # fn set_rect(&self, _: u32, _: &Rect) -> eyre::Result<()> { Ok(()) } /// # fn focus(&self, _: u32, _: bool) -> eyre::Result<()> { Ok(()) } /// # fn raise(&self, _: u32) -> eyre::Result<()> { Ok(()) } +/// # fn hide(&self, _: u32) -> eyre::Result<()> { Ok(()) } +/// # fn restore(&self, _: u32) -> eyre::Result<()> { Ok(()) } /// # fn minimize(&self, _: u32) -> eyre::Result<()> { Ok(()) } /// # fn unminimize(&self, _: u32) -> eyre::Result<()> { Ok(()) } /// # fn close(&self, _: u32) -> eyre::Result<()> { Ok(()) } @@ -192,6 +205,28 @@ pub trait Backend: Send + Sync + 'static { /// When the window does not exist or is no longer alive. fn raise(&self, id: u32) -> eyre::Result<()>; + /// Takes the window out of sight without closing or minimizing it, which is how the window + /// manager keeps the back of a stack out of the way. On KWin it goes to a virtual desktop that + /// nobody looks at. + /// + /// The window stays on its workspace ([`Backend::window_workspace`]), and + /// [`Backend::set_window_workspace`] changes the workspace it comes back to, not where it is + /// hidden. A window that is hidden already is left as it is. + /// + /// # Errors + /// + /// When the window does not exist or is no longer alive, or the compositor cannot make the + /// place the window is hidden in. + fn hide(&self, id: u32) -> eyre::Result<()>; + + /// Brings a hidden window back, to the workspace it is on. A window that is not hidden is left + /// as it is. + /// + /// # Errors + /// + /// When the window does not exist or is no longer alive. + fn restore(&self, id: u32) -> eyre::Result<()>; + /// Minimizes the window. /// /// # Errors diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs index e35450ee..9104284a 100644 --- a/komorebi/src/container.rs +++ b/komorebi/src/container.rs @@ -4,6 +4,10 @@ //! the container is put on that tile. A new window gets a container of its own //! ([`Workspace::new_container_for_window`](crate::workspace::Workspace::new_container_for_window)). //! +//! A container with more than one window is a stack: the focused window is the one in front, and +//! the others are hidden ([`Window::hide`]) until they are given the tile +//! ([`Container::load_focused_window`]). +//! //! A container can be locked ([`Lockable`]): a locked container keeps its index in the workspace //! while others are inserted, removed or swapped around it. @@ -100,10 +104,22 @@ impl Container { self.remove_window_by_idx(focused_idx) } + /// Puts a window at the back of the container and gives it the front, hiding every other + /// window of the container ([`Window::hide`]) + /// + /// It never fails; the result is there so that callers can use `?`. pub fn add_window(&mut self, window: &Window) -> eyre::Result<()> { self.windows_mut().push_back(*window); self.focus_window(self.windows().len().saturating_sub(1)); + let focused_window_idx = self.focused_window_idx(); + + for (i, window) in self.windows_mut().iter_mut().enumerate() { + if i != focused_window_idx { + window.hide(); + } + } + Ok(()) } @@ -113,17 +129,73 @@ impl Container { self.windows.focus(idx); } + /// Hides the unfocused windows of the container and restores the focused one. This function + /// is used to make sure we update the window that should be shown on a stack. If the container + /// isn't a stack this function won't change anything. + /// + /// It never fails; the result is there so that callers can use `?`. + pub fn load_focused_window(&mut self) -> eyre::Result<()> { + let focused_idx = self.focused_window_idx(); + + for (i, window) in self.windows_mut().iter_mut().enumerate() { + if i == focused_idx { + window.restore(); + } else { + window.hide(); + } + } + + Ok(()) + } + pub fn remove_window_by_idx(&mut self, idx: usize) -> Option { let window = self.windows_mut().remove(idx); self.focus_window(idx.saturating_sub(1)); window } + + /// Hides every window of the container but `omit`, or every window when it is `None` + /// + /// It never fails; the result is there so that callers can use `?`. + pub fn hide(&mut self, omit: Option) -> eyre::Result<()> { + for window in self.windows_mut().iter_mut().rev() { + let mut should_hide = omit.is_none(); + + if !should_hide + && let Some(omit) = omit + && omit != window.id + { + should_hide = true + } + + if should_hide { + window.hide(); + } + } + + Ok(()) + } + + /// Restores the focused window of the container, which is the one that is in front when the + /// container is a stack + /// + /// It never fails; the result is there so that callers can use `?`. + pub fn restore(&mut self) -> eyre::Result<()> { + if let Some(window) = self.focused_window_mut() { + window.restore(); + } + + Ok(()) + } } #[cfg(test)] mod tests { use super::*; + use crate::backend::fake::FakeBackend; + use crate::backend::with_backend; use serde_json; + use std::sync::Arc; #[test] fn test_contains_window() { @@ -243,4 +315,65 @@ mod tests { assert!(deserialized.locked); assert_eq!(deserialized.id, container.id); } + + /// A container of the windows 701.. on a fake desktop, with the window at `focus` in front + fn stack_of( + fake: &Arc, + ids: std::ops::RangeInclusive, + focus: usize, + ) -> Container { + let mut container = Container::default(); + for id in ids { + fake.open_window(id, "foot", "foot", &format!("window {id}")); + container.add_window(&Window::from(id)).unwrap(); + } + container.focus_window(focus); + container + } + + #[test] + fn a_window_added_to_a_container_is_in_front_and_the_others_are_hidden() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + + with_backend(fake.clone(), || { + let container = stack_of(&fake, 701..=703, 2); + + assert_eq!(container.focused_window().map(|w| w.id), Some(703)); + assert!(fake.is_hidden(701) && fake.is_hidden(702)); + assert!(!fake.is_hidden(703)); + }); + } + + #[test] + fn loading_the_focused_window_shows_it_and_hides_the_rest() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + + with_backend(fake.clone(), || { + let mut container = stack_of(&fake, 704..=706, 0); + + container.load_focused_window().unwrap(); + + assert!(!fake.is_hidden(704)); + assert!(fake.is_hidden(705) && fake.is_hidden(706)); + }); + } + + #[test] + fn hiding_a_container_leaves_out_the_window_it_is_told_to_and_restoring_shows_the_focused_one() + { + let fake = Arc::new(FakeBackend::with_one_monitor()); + + with_backend(fake.clone(), || { + let mut container = stack_of(&fake, 707..=709, 1); + + container.hide(Some(709)).unwrap(); + assert!(fake.is_hidden(707) && fake.is_hidden(708) && !fake.is_hidden(709)); + + container.hide(None).unwrap(); + assert!(fake.is_hidden(709)); + + container.restore().unwrap(); + assert!(fake.is_hidden(707) && !fake.is_hidden(708) && fake.is_hidden(709)); + }); + } } diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 2e6b1622..66b2731d 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -347,6 +347,10 @@ pub enum SocketMessage { CancelPreselect, CycleFocusWindow(CycleDirection), CycleMoveWindow(CycleDirection), + StackWindow(OperationDirection), + UnstackWindow, + StackAll, + UnstackAll, ResizeWindowEdge(OperationDirection, Sizing), ResizeWindowAxis(Axis, Sizing), MoveContainerToLastWorkspace, @@ -378,6 +382,8 @@ pub enum SocketMessage { UnlockMonitorWorkspaceContainer(usize, usize, usize), ToggleLock, ToggleFloat, + ToggleWindowContainerBehaviour, + ToggleFloatOverride, ToggleCrossMonitorMoveBehaviour, CrossMonitorMoveBehaviour(MoveBehaviour), UnmanagedWindowOperationBehaviour(OperationBehaviour), @@ -392,6 +398,8 @@ pub enum SocketMessage { LayoutRatios(Option>, Option>), // ChangeLayoutCustom(#[serde_as(as = "ResolvedPathBuf")] PathBuf), FlipLayout(Axis), + ToggleWorkspaceWindowContainerBehaviour, + ToggleWorkspaceFloatOverride, // Monitor and Workspace Commands // MonitorIndexPreference(usize, i32, i32, i32, i32), DisplayIndexPreference(usize, String), @@ -400,6 +408,7 @@ pub enum SocketMessage { NewWorkspace, ToggleTiling, Stop, + StopIgnoreRestore, TogglePause, Retile, RetileWithResizeDimensions, diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index 3825d6d7..e8ed0811 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -42,6 +42,13 @@ //! When something other than komorebi does either, the script reports it, and the table turns it //! into a [`WorkspaceChange`] or a [`WorkspaceMove`] for the window manager to follow. //! +//! Hiding a window ([`Backend::hide`]) moves it to one more desktop, `komorebi-park`, that nobody +//! looks at and that is not a workspace; [`Backend::restore`] moves it back to the desktop of its +//! workspace. KWin saves its desktops in `kwinrc` as soon as one is made, so a desktop that +//! komorebi made and did not remove would be there for every later session: komorebi removes it +//! when it stops, and one that an earlier run left (it was killed, or the session was torn down +//! under it) is found in the first snapshot, its windows are sent home and it is removed. +//! //! [`WorkspaceChange`]: crate::window_manager_event::WindowManagerEvent::WorkspaceChange //! [`WorkspaceMove`]: crate::window_manager_event::WindowManagerEvent::WorkspaceMove //! @@ -67,7 +74,9 @@ use parking_lot::Mutex; use serde_json::Value; use serde_json::json; use state::NeedsDesktops; +use state::NeedsPark; use state::Output; +use state::PARK_DESKTOP_NAME; use state::Table; use std::collections::HashMap; use std::collections::VecDeque; @@ -142,6 +151,7 @@ impl Shared { for output in outputs { match output { Output::Event(event) => window_manager_event_listener::send_notification(event), + Output::Command(command) => self.push(command), Output::Cursor { token, x, y } => { if let Some(waiter) = self.cursor_waiters.lock().remove(&token) { let _ = waiter.send((x, y)); @@ -188,6 +198,9 @@ impl Events { if is_snapshot { self.shared.mark_ready(); + // a parking desktop in a snapshot is one nobody is using: from an earlier run, or one + // that KWin kept in its configuration when it restarted under this one + sweep_stale_park(&self.shared); } } } @@ -526,6 +539,23 @@ async fn supervise(shared: Arc) { } } +/// Removes the parking desktop an earlier run left behind, once its windows have moved home: the +/// snapshot that found it sent them, and they take a moment to get there +fn sweep_stale_park(shared: &Arc) { + let Some(stale) = shared.table.lock().stale_park().map(String::from) else { + return; + }; + + let shared = shared.clone(); + shared.handle.clone().spawn(async move { + tokio::time::sleep(Duration::from_millis(500)).await; + if let Err(error) = remove_desktop(&shared, &stale).await { + tracing::warn!("could not remove the stale parking desktop: {error}"); + } + shared.table.lock().clear_stale_park(); + }); +} + async fn desktop_manager(shared: &Shared) -> eyre::Result> { let connection = shared.connection().await?; // uncached: a property read right after createDesktop must not return the list from before it @@ -543,6 +573,33 @@ async fn desktops(manager: &Proxy<'static>) -> eyre::Result