diff --git a/Cargo.lock b/Cargo.lock index 5bc70386..1c172eec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -71,7 +71,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -82,7 +82,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -359,7 +359,7 @@ checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162" dependencies = [ "dispatch2", "nix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -454,7 +454,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -526,7 +526,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -566,6 +566,25 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "file-id" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13be71e6ca82e91bc0cb862bebaac0b2d1924a5a1d970c822b2f98b63fda8c3" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -596,6 +615,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "fsevent-sys" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" +dependencies = [ + "libc", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -716,6 +744,17 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hotwatch" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9140219159163c92eb58c37955a0cc57c5814c3c44521955aae376064c668756" +dependencies = [ + "log", + "notify", + "notify-debouncer-full", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -879,6 +918,26 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inotify" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8069d3ec154eb856955c1c0fbffefbf5f3c40a104ec912d4797314c1801abff" +dependencies = [ + "bitflags 1.3.2", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + [[package]] name = "is_debug" version = "1.1.0" @@ -982,6 +1041,7 @@ dependencies = [ "ctrlc", "dirs", "futures-util", + "hotwatch", "komorebi-layouts", "lazy_static", "nanoid", @@ -1034,8 +1094,10 @@ dependencies = [ "clap", "clap_complete", "color-eyre", + "dirs", "fs-tail", "komorebi-client", + "lazy_static", "pastey", "sysinfo", "version", @@ -1056,6 +1118,26 @@ version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" +[[package]] +name = "kqueue" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags 2.13.2", + "libc", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1161,6 +1243,18 @@ dependencies = [ "adler2", ] +[[package]] +name = "mio" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.48.0", +] + [[package]] name = "mio" version = "1.2.4" @@ -1169,7 +1263,7 @@ checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1193,6 +1287,38 @@ dependencies = [ "libc", ] +[[package]] +name = "notify" +version = "6.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6205bd8bb1e454ad2e27422015fb5e4f2bcc7e08fa8f27058670d208324a4d2d" +dependencies = [ + "bitflags 2.13.2", + "crossbeam-channel", + "filetime", + "fsevent-sys", + "inotify", + "kqueue", + "libc", + "log", + "mio 0.8.11", + "walkdir", + "windows-sys 0.48.0", +] + +[[package]] +name = "notify-debouncer-full" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4812c1eb49be776fb8df4961623bdc01ec9dfdc1abe8211ceb09150a2e64219" +dependencies = [ + "crossbeam-channel", + "file-id", + "notify", + "parking_lot", + "walkdir", +] + [[package]] name = "ntapi" version = "0.4.3" @@ -1208,7 +1334,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1563,7 +1689,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1578,6 +1704,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "schemars" version = "0.9.0" @@ -1802,7 +1937,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1901,7 +2036,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1911,7 +2046,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" dependencies = [ "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1999,12 +2134,12 @@ checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", - "mio", + "mio 1.2.4", "pin-project-lite", "signal-hook-registry", "socket2", "tracing", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2155,7 +2290,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2231,6 +2366,16 @@ dependencies = [ "shadow-rs", ] +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2298,6 +2443,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" @@ -2405,6 +2559,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -2414,6 +2577,21 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + [[package]] name = "windows-threading" version = "0.2.1" @@ -2423,6 +2601,48 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "winnow" version = "1.0.4" @@ -2484,7 +2704,7 @@ dependencies = [ "tracing", "uds_windows", "uuid", - "windows-sys", + "windows-sys 0.61.2", "winnow", "zbus_macros", "zbus_names", diff --git a/Cargo.toml b/Cargo.toml index fc6dfd52..7987e630 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ clap = { version = "4", features = ["derive", "wrap_help"] } color-eyre = "0.6" crossbeam-channel = "0.5" dirs = "6" +hotwatch = "0.5" lazy_static = "1" pastey = "0.2" schemars = "1.1" diff --git a/README.md b/README.md index 724f2c32..d5761b0f 100644 --- a/README.md +++ b/README.md @@ -76,14 +76,15 @@ without a checkout of the toolchain. `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`), shows its state (`state`), - and sends its subscribers a notification of each event and message it handles - (`notify_subscribers`). + sends its subscribers a notification of each event and message it handles + (`notify_subscribers`), and is configured by a `komorebi.json` that it reads + and reads again when it changes (`static_config`). - [`komorebi-client`](komorebi-client): a library that sends messages to the daemon, reads its answers, subscribes to its notifications, and re-exports the types they are made of. - [`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. + of the daemon is one message on its socket; `start`, `configuration`, `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 @@ -190,6 +191,19 @@ stack to the front, and `cycle-stack-index` moves the front one along it. `toggle-window-container-behaviour` makes a window that opens join the focused stack, and `toggle-float-override` makes it float. +The daemon is configured by `komorebi.json`: the file `--config` names, or the +one in `~/.config/komorebi`. It reads the file when it starts, once it has the +monitors, and gives each monitor the workspaces the file lists for it, with their +names, layouts, paddings and rules. It watches the file, and when it changes +applies it again to the windows it has. It also sets what a window that opens +gets (`window_container_behaviour`, `float_override`, `floating_layer_behaviour`, +for a workspace or for all of them) and what focusing does in monocle +(`monocle_focus_behaviour`). A key that komorebi for KDE does not read +is ignored, so one file serves every platform. `workspace-layout-rule` makes a +workspace change layout with the number of windows it has, as the file's +`layout_rules` do, and `generate-static-config` prints the settings the daemon +has as a `komorebi.json`. + 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 @@ -203,6 +217,8 @@ starts it again if it fails. The user guide starts at [`docs/index.md`](docs/index.md), [`docs/installation.md`](docs/installation.md) says how to install komorebi, +[`docs/usage/configuration.md`](docs/usage/configuration.md) explains `komorebi.json`, +[`docs/example-configurations.md`](docs/example-configurations.md) has an example of it, 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. diff --git a/deny.toml b/deny.toml index 267bda37..4530dfd5 100644 --- a/deny.toml +++ b/deny.toml @@ -21,6 +21,8 @@ ignore = [ [licenses] allow = [ "Apache-2.0", + "CC0-1.0", + "ISC", "MIT", "MPL-2.0", "Unicode-3.0", diff --git a/docs/cli/clear-named-workspace-layout-rules.md b/docs/cli/clear-named-workspace-layout-rules.md new file mode 100644 index 00000000..44ff275c --- /dev/null +++ b/docs/cli/clear-named-workspace-layout-rules.md @@ -0,0 +1,14 @@ +```text +Clear all dynamic layout rules for the specified workspace + +Usage: clear-named-workspace-layout-rules + +Arguments: + + Target workspace name + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/clear-workspace-layout-rules.md b/docs/cli/clear-workspace-layout-rules.md new file mode 100644 index 00000000..5381e9dd --- /dev/null +++ b/docs/cli/clear-workspace-layout-rules.md @@ -0,0 +1,17 @@ +```text +Clear all dynamic layout rules for the specified workspace + +Usage: clear-workspace-layout-rules + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/configuration.md b/docs/cli/configuration.md new file mode 100644 index 00000000..e30c973c --- /dev/null +++ b/docs/cli/configuration.md @@ -0,0 +1,10 @@ +```text +Show the path to komorebi.json + +Usage: configuration + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/generate-static-config.md b/docs/cli/generate-static-config.md new file mode 100644 index 00000000..805af3da --- /dev/null +++ b/docs/cli/generate-static-config.md @@ -0,0 +1,10 @@ +```text +Generates a static configuration JSON file based on the current window manager state + +Usage: generate-static-config + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/named-workspace-layout-rule.md b/docs/cli/named-workspace-layout-rule.md new file mode 100644 index 00000000..71340da3 --- /dev/null +++ b/docs/cli/named-workspace-layout-rule.md @@ -0,0 +1,29 @@ +```text +Add a dynamic layout rule for the specified workspace + +Usage: named-workspace-layout-rule + +Arguments: + + Target workspace name + + + The number of window containers on-screen required to trigger this layout rule + + + 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/start.md b/docs/cli/start.md index af684bd8..e214f928 100644 --- a/docs/cli/start.md +++ b/docs/cli/start.md @@ -1,13 +1,16 @@ ```text Start komorebi as a background process -Usage: start [-- ...] +Usage: start [OPTIONS] [-- ...] Arguments: [KOMOREBI_ARGS]... Arguments to pass to komorebi, after a `--`: `komorebic start -- --log-level debug` Options: + -c, --config + Path to a static configuration JSON file + -h, --help Print help diff --git a/docs/cli/workspace-layout-rule.md b/docs/cli/workspace-layout-rule.md new file mode 100644 index 00000000..b6aa1fc1 --- /dev/null +++ b/docs/cli/workspace-layout-rule.md @@ -0,0 +1,32 @@ +```text +Add a dynamic layout rule for the specified workspace + +Usage: workspace-layout-rule + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + + + The number of window containers on-screen required to trigger this layout rule + + + 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/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index d89b2512..55b34cc9 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -9,8 +9,9 @@ This page describes that trait, who implements and calls it, where each of its r enforced, the model of the desktop the window manager tiles, the backend that reaches KWin, how an event about a window becomes a tile, how workspaces are the compositor's desktops, how a stack hides its windows, how a message on the daemon's socket is answered, how subscribers -are notified of both, what the orders a message gives do, and how the NixOS module runs the -daemon. It grows with the code: each part of the daemon that is added has its place here. +are notified of both, what the orders a message gives do, how `komorebi.json` configures the +daemon, and how the NixOS module runs the daemon. It grows with the code: each part of the +daemon that is added has its place here. ## Vocabulary @@ -51,6 +52,9 @@ daemon. It grows with the code: each part of the daemon that is added has its pl - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order (focus a window, move it, change the layout, resize it, show a workspace, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). +- **Configuration**: `komorebi.json`, which the daemon reads when it starts and again when it + changes ([`StaticConfig`]). It lives in the **config home**, [`HOME_DIR`], unless `--config` + names another. - **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). @@ -638,14 +642,69 @@ gives a tile, and [`Workspace::new_container_for_window`] puts the next window i `CancelPreselect` removes it. A workspace reserves one place at a time, and the grid layout none. +## Configuration + +The daemon is configured by `komorebi.json`, which [`StaticConfig`] reads. `main.rs` takes the +file `--config` names, or else `komorebi.json` in [`HOME_DIR`] (`$KOMOREBI_CONFIG_HOME`, or +`~/.config/komorebi`) if there is one; without a file, the daemon runs on its defaults. Loading +has three steps, because the monitors are known only after the backend is asked: + +1. [`StaticConfig::preload`] reads the file, applies the settings that are process-wide (the + default paddings, [`LAYOUT_DEFAULTS`], the indices of the monitors, and the rules in + [`IGNORE_IDENTIFIERS`], [`MANAGE_IDENTIFIERS`] and [`FLOATING_APPLICATIONS`]) and makes the + [`WindowManager`], with the settings that are its own. It starts a watcher on the file. +2. [`WindowManager::init`] loads the monitors and the windows from the backend, in the order the + indices of the monitors give. +3. [`StaticConfig::postload`] gives each monitor the entry of the file that is its own, and each + workspace of the monitor the entry of its place ([`Workspace::load_static_config`]). A monitor + takes the entry at the index `display_index_preferences` gives its serial number id, or else + the first entry that no preference names and no monitor has taken. `main.rs` then asks the + backend for a desktop for each workspace ([`WindowManager::sync_workspace_desktops`]), and + tiles. + +When the file changes, the watcher (a [`hotwatch`] watcher, which waits two seconds for a file +to settle) writes `ReloadStaticConfiguration` to the daemon's own socket, and the message is +handled like any other, with the window manager locked: [`StaticConfig::reload`] reads the file +first and applies it only when it parsed, so a file that is half written changes nothing. It does +for the window manager that is running what the three steps do for one that starts, and tiles +every monitor again. + +Three kinds of key reach the model. A **setting** of the window manager is a field of it +([`WindowManager::resize_delta`] and the others). A **default** is a process-wide static that a +monitor or a workspace falls back to when it has no value of its own: the paddings, the layout +defaults. A **rule** is an entry of one of the process-wide lists. A workspace's own +`layout_rules`, `work_area_offset_rules` and `window_container_behaviour_rules` are fields of the +[`Workspace`], which [`Workspace::update`] reads each time it tiles. + +One `komorebi.json` is meant for every platform komorebi runs on, so [`StaticConfig`] has no +`deny_unknown_fields`: a key it does not read is dropped, and the keys of other platforms that +mean nothing on KDE Plasma are fields that nothing reads. `StaticConfig::from(&WindowManager)` +goes the other way, for `GenerateStaticConfig`. + +| Rule | Enforced by | Proof | Escape hatch | +|---|---|---|---| +| A key komorebi does not read does not stop a configuration from loading | serde: [`StaticConfig`] ignores unknown keys, and a key of another platform is a field nothing reads | `the_keys_that_do_nothing_on_kde_are_accepted_and_ignored`, `fixtures_load_round_trip_and_only_lose_windows_only_keys` | none | +| The keys the parity test ignores are keys `StaticConfig` does not read | test: the ignore lists are compared with the schema of [`StaticConfig`] | `the_lists_name_no_key_that_is_read` | none | +| The example in the docs is the example file, which loads | test | `the_example_in_the_docs_is_the_example_file`, `fixtures_load_round_trip_and_only_lose_windows_only_keys` | none | +| A file that cannot be read changes nothing | framework path: [`StaticConfig::reload`] reads and parses the file before it applies anything | `a_configuration_that_cannot_be_read_changes_nothing`, `the_daemon_follows_the_file_it_is_given_when_the_file_changes` | none | +| The daemon applies a change to its file, written in place or replaced by a rename | framework path: the watcher sends `ReloadStaticConfiguration` to the daemon's own socket | `the_daemon_follows_the_file_it_is_given_when_the_file_changes`, `vm-module` | none: the file has to be the one the daemon was started with | +| A monitor takes the entry its display index preference gives it, else the first nobody has | framework path: [`StaticConfig::postload`] and [`StaticConfig::reload`] choose the entry by serial number id first | `a_monitor_takes_the_configuration_its_display_index_preference_gives_it` | none | +| A workspace that names no layout and does not say it tiles moves no window | framework path: [`Workspace::load_static_config`] sets [`Workspace::tile`] | `a_workspace_with_no_layout_does_not_tile`, `a_workspace_tiles_when_it_has_a_layout_or_is_told_to` | `"tile": true` | +| A workspace's own layout options replace the defaults of its layout, whole | framework path: [`Workspace::update`] takes the workspace's options and rules when it has either, and else those of `layout_defaults` | `layout_options_of_a_workspace_replace_the_defaults_of_its_layout` | none | +| The highest of the rules a count of containers reaches decides the layout, the offset and the container behavior | framework path: [`Workspace::update`] reads the rules, kept in the order of their thresholds | `layout_rules_change_the_layout_with_the_number_of_windows`, `work_area_offset_rules_change_the_offset_with_the_number_of_windows`, `window_container_behaviour_rules_change_the_behaviour_with_the_number_of_containers` | none | +| A workspace's own container behavior and float override come before the one for every workspace, and its floating layer behavior before its monitor's, which comes before the one for every workspace | framework path: [`WindowManager::window_management_behaviour`] reads the workspace, then (for the floating layer) the monitor, then the window manager | `the_behaviour_of_a_workspace_comes_before_the_one_for_every_workspace`, `the_float_override_of_a_workspace_comes_before_the_one_for_every_workspace`, `the_floating_layer_behaviour_of_a_workspace_comes_before_a_monitors_and_that_before_the_default` | none | +| The configuration the daemon generates loads and says the same | test | `a_configuration_comes_out_again_as_the_settings_of_the_window_manager` | none | +| The daemon reads the file it is given or the one in the config home, not both | startup order: `main.rs` takes `--config` before the config home | `the_daemon_follows_the_file_it_is_given_when_the_file_changes`, `the_daemon_reads_komorebi_json_from_the_config_home` | none | + ## The 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: +`enable`, `package` (by default `pkgs.komorebi-full`, from the overlay), `logLevel`, +`configFile`, and `execStart`, which is read-only: the module sets it to `bin/komorebi` of the +package with `--log-level`, and `--config` with `configFile` when that is set. 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 @@ -666,6 +725,7 @@ module's unit. | 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 | +| The daemon is configured by `configFile` when it is set | framework path: `execStart` passes it as `--config`, which comes before the config home | `nixos-module-eval` ("configFile reaches execStart and the unit as --config"), `vm-module` | none: with no `configFile` the daemon reads the file of the config home | | `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 | @@ -710,6 +770,8 @@ module's unit. 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. +- [`static_config`](../../komorebi/src/static_config.rs): `komorebi.json`, [`StaticConfig`], and + how it is loaded, reloaded and generated. - [`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, @@ -724,8 +786,8 @@ module's unit. 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 + fake with `--fake-backend`, makes the window manager from `komorebi.json` when there is one, + which binds the socket, loads the desktop, gives the monitors their configuration and tiles, starts the threads that listen on the socket and handle events, and waits to be stopped. - [`nixos-module.nix`]: the NixOS module, which installs komorebi and runs the daemon as a systemd user unit of every Plasma session. @@ -919,6 +981,13 @@ A window is shown, and ends up on a tile: `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/static_config.rs`](../../komorebi/src/static_config.rs): `komorebi.json`. + [`komorebi/tests/config.rs`](../../komorebi/tests/config.rs) loads files over the fake + desktop, [`komorebi/tests/config_displays.rs`](../../komorebi/tests/config_displays.rs) one + with several monitors, [`komorebi/tests/hot_reload.rs`](../../komorebi/tests/hot_reload.rs) the + daemon following a file, and + [`komorebi/tests/config_parity.rs`](../../komorebi/tests/config_parity.rs) the files of other + platforms and the example, which load. - [`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 @@ -996,6 +1065,18 @@ A window is shown, and ends up on a tile: a Plasma session in which the module's unit runs the daemon. [`nixos-module.nix`]: ../../nix/nixos-module.nix +[`StaticConfig`]: ../../komorebi/src/static_config.rs +[`StaticConfig::preload`]: ../../komorebi/src/static_config.rs +[`StaticConfig::postload`]: ../../komorebi/src/static_config.rs +[`StaticConfig::reload`]: ../../komorebi/src/static_config.rs +[`Workspace::load_static_config`]: ../../komorebi/src/workspace.rs +[`HOME_DIR`]: ../../komorebi/src/lib.rs +[`LAYOUT_DEFAULTS`]: ../../komorebi/src/lib.rs +[`IGNORE_IDENTIFIERS`]: ../../komorebi/src/lib.rs +[`MANAGE_IDENTIFIERS`]: ../../komorebi/src/lib.rs +[`FLOATING_APPLICATIONS`]: ../../komorebi/src/lib.rs +[`hotwatch`]: https://crates.io/crates/hotwatch +[`WindowManager::init`]: ../../komorebi/src/window_manager.rs [`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 8cdb624e..28cd6457 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -328,3 +328,22 @@ the window cannot be a container: a layout would give it a tile, less the paddin that index in a container of its own. It is restored before it is tiled again, because "it is its tile's size that it has to get back, not the compositor's idea of its old size" (the comment in `reintegrate_maximized_window`). + +## Why does one `komorebi.json` work on every platform? + +Spike 8 asked whether it could, and it can. With the `StaticConfig` of komorebi for Mac, the +example of komorebi for Windows loaded and read back, and so did a file with every key that only +Windows has, a real file of komorebi for Mac, and this repository's example; what serde dropped +was the keys that mean nothing outside their platform. So a key that does nothing on KDE Plasma is accepted and +ignored, and `config_parity` checks that the keys it ignores are the Windows-only ones and, until +the features are in, the ones of features that are not. Where the Mac struct had no key that the +native mapping needs (`focus_follows_mouse`, `transparency`), the KDE struct has the Windows one. + +## Why does komorebi reload its configuration when the file changes? + +It does what komorebi for Mac does: it watches `komorebi.json` and reloads it after about two +seconds. On Windows, `watch-configuration` is about the legacy AutoHotkey and PowerShell files, +which do not exist here. The watcher is `hotwatch`, whose default is to wait two seconds for the events of an +editor to settle. An editor either writes a file in place or replaces it with a new one, so the +daemon reloads on a modification and on a removal, and the test that follows a real daemon +through both of them is `the_daemon_follows_the_file_it_is_given_when_the_file_changes`. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index a217230c..99a188bb 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -232,6 +232,7 @@ since a read right after `createDesktop` has to see the new desktop. | Path | What | Lifetime | |---|---|---| +| `$KOMOREBI_CONFIG_HOME/komorebi.json` (`~/.config/komorebi/komorebi.json`) | komorebi's configuration, which komorebi never writes: read when the daemon starts, and again when it changes. `--config` names another file | the user's | | `$XDG_CONFIG_HOME/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 | @@ -251,6 +252,13 @@ The address of the session bus. If it is not set, komorebi uses `$XDG_RUNTIME_DI 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). +### `KOMOREBI_CONFIG_HOME` + +The config home, where komorebi looks for `komorebi.json`: a directory, in which `komorebic +configuration` and the daemon look for the file. Without it the config home is +`~/.config/komorebi`, whatever `XDG_CONFIG_HOME` is. When it is set and is not a directory, the +daemon and `komorebic` panic when they first need the config home, and say so. + ### `XDG_RUNTIME_DIR` The runtime directory of the user, normally `/run/user/`: komorebi writes the bridge to @@ -292,6 +300,15 @@ When set to anything but the empty string, the log the daemon prints on its stan 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. +## Watching the configuration + +The daemon watches `komorebi.json` with `hotwatch` 0.5, over `notify` 6.1, which on Linux is +inotify. At time of writing (2026-10-27) a change to the file reaches the daemon about two +seconds later, the delay of `hotwatch`'s debouncer, whether an editor wrote the file in place or +renamed a new file over it: `the_daemon_follows_the_file_it_is_given_when_the_file_changes` does +both, on aarch64 Linux. A file the daemon cannot read after a change is logged and leaves the +configuration it has. + ## The bridge's environment What the KWin scripting API offers a script, and what it does not, at time of writing diff --git a/docs/example-configurations.md b/docs/example-configurations.md new file mode 100644 index 00000000..f77a1e1a --- /dev/null +++ b/docs/example-configurations.md @@ -0,0 +1,176 @@ +# Example configurations + +`komorebi`, and tiling window managers in general, are very complex pieces of software. To make +starting out easier, the repository has an example configuration, +[`docs/komorebi.example.json`](komorebi.example.json), which is kept working: a test loads it with +every change. + +## komorebi.json + +The example sets some defaults and gives the first monitor eight workspaces, each with a +different layout. This page has the file as it is: + +```json +{ + "cross_monitor_move_behaviour": "Insert", + "default_workspace_padding": 15, + "default_container_padding": 15, + "floating_window_aspect_ratio": "Widescreen", + "floating_layer_behaviour": "Float", + "resize_delta": 100, + "ignore_rules": [], + "floating_applications": [], + "manage_rules": [], + "monitors": [ + { + "workspaces": [ + { + "name": "I", + "layout": "BSP" + }, + { + "name": "II", + "layout": "VerticalStack" + }, + { + "name": "III", + "layout": "HorizontalStack" + }, + { + "name": "IV", + "layout": "UltrawideVerticalStack" + }, + { + "name": "V", + "layout": "Rows" + }, + { + "name": "VI", + "layout": "Grid" + }, + { + "name": "VII", + "layout": "RightMainVerticalStack" + }, + { + "name": "VIII", + "layout": "Scrolling" + } + ] + } + ] +} +``` + +Put it where the daemon looks for it, `~/.config/komorebi/komorebi.json`, or give it to the daemon +with `komorebic start --config`. [Configuration](usage/configuration.md) explains every key and +where the daemon looks. The settings of a monitor with more than one entry in `monitors`, and of +each workspace, are there too. + +### Padding + +While you can set the workspace padding (the space between the outer edges of the windows and +the edge of the monitor) and the container padding (the space between each of the tiled windows) +for each workspace on its own, you can also set a default for both of these values that applies +to all workspaces, using `default_workspace_padding` and `default_container_padding`. + +### The floating layer + +`floating_layer_behaviour` is `Float` in the example: a window that opens while a workspace is on +its floating layer floats, centered, where the default is to tile it. A window that opens while the +workspace is on its tiling layer is tiled either way. + +### Layouts + +#### BSP + +```text ++-------+-----+ +| | | +| +--+--+ +| | |--| ++-------+--+--+ +``` + +#### Vertical Stack + +```text ++-------+-----+ +| | | +| +-----+ +| | | ++-------+-----+ +``` + +#### RightMainVerticalStack + +```text ++-----+-------+ +| | | ++-----+ | +| | | ++-----+-------+ +``` + +#### Horizontal Stack + +```text ++------+------+ +| | +|------+------+ +| | | ++------+------+ +``` + +#### Columns + +```text ++--+--+--+--+ +| | | | | +| | | | | +| | | | | ++--+--+--+--+ +``` + +#### Rows + +If you have a vertical monitor, I recommend using this layout. + +```text ++-----------+ +|-----------| +|-----------| +|-----------| ++-----------+ +``` + +#### Ultrawide Vertical Stack + +If you have an ultrawide monitor, I recommend using this layout. + +```text ++-----+-----------+-----+ +| | | | +| | +-----+ +| | | | +| | +-----+ +| | | | ++-----+-----------+-----+ +``` + +#### Grid + +If you like the `grid` layout in [LeftWM](https://github.com/leftwm/leftwm-layouts) this is almost exactly the same! + +The `grid` layout does not support resizing windows tiles. + +```text ++-----+-----+ +---+---+---+ +---+---+---+ +---+---+---+ +| | | | | | | | | | | | | | | +| | | | | | | | | | | | | +---+ ++-----+-----+ | +---+---+ +---+---+---+ +---+---| | +| | | | | | | | | | | | | +---+ +| | | | | | | | | | | | | | | ++-----+-----+ +---+---+---+ +---+---+---+ +---+---+---+ + 4 windows 5 windows 6 windows 7 windows +``` diff --git a/docs/index.md b/docs/index.md index 24d47203..fc1301e5 100644 --- a/docs/index.md +++ b/docs/index.md @@ -50,6 +50,9 @@ and keep parts of a monitor free of them. 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. +[Configuration](usage/configuration.md) explains `komorebi.json`, where komorebi looks for it and +how it is reloaded when it changes, and [Example configurations](example-configurations.md) has +one to start from. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/installation.md b/docs/installation.md index 58063c83..75e8bd2f 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -72,7 +72,20 @@ the repository's `rust-toolchain.toml` selects, whatever nixpkgs your system use | `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. | +| `services.komorebi.configFile` | `null` | A `komorebi.json` for the daemon. The unit passes it to komorebi as `--config`, so the daemon reads it and not the `komorebi.json` of `~/.config/komorebi`. The file is in the Nix store: komorebi reads a new one when it starts again. | +| `services.komorebi.execStart` | read only | The command line the unit starts komorebi with, built from `package`, `logLevel` and `configFile`. A unit of your own that runs komorebi uses it to start komorebi the same way. | + +The file for `configFile` is written like any other `komorebi.json` +([Configuration](usage/configuration.md)): + +```nix +{ + services.komorebi = { + enable = true; + configFile = ./komorebi.json; + }; +} +``` ### Running it diff --git a/docs/komorebi.example.json b/docs/komorebi.example.json new file mode 100644 index 00000000..aee89caf --- /dev/null +++ b/docs/komorebi.example.json @@ -0,0 +1,49 @@ +{ + "cross_monitor_move_behaviour": "Insert", + "default_workspace_padding": 15, + "default_container_padding": 15, + "floating_window_aspect_ratio": "Widescreen", + "floating_layer_behaviour": "Float", + "resize_delta": 100, + "ignore_rules": [], + "floating_applications": [], + "manage_rules": [], + "monitors": [ + { + "workspaces": [ + { + "name": "I", + "layout": "BSP" + }, + { + "name": "II", + "layout": "VerticalStack" + }, + { + "name": "III", + "layout": "HorizontalStack" + }, + { + "name": "IV", + "layout": "UltrawideVerticalStack" + }, + { + "name": "V", + "layout": "Rows" + }, + { + "name": "VI", + "layout": "Grid" + }, + { + "name": "VII", + "layout": "RightMainVerticalStack" + }, + { + "name": "VIII", + "layout": "Scrolling" + } + ] + } + ] +} diff --git a/docs/usage/configuration.md b/docs/usage/configuration.md new file mode 100644 index 00000000..f1301cfd --- /dev/null +++ b/docs/usage/configuration.md @@ -0,0 +1,188 @@ +# Configuration + +komorebi is configured by one file, `komorebi.json`. Many of its settings can also be changed +while the daemon runs, with a `komorebic` command, but the file is where the settings that should +be there every time komorebi starts belong: the workspaces of each monitor and their layouts, the +padding around the tiles, the rules that decide which windows are tiled. + +[Example configurations](../example-configurations.md) has a file to start from. + +## Where the file is + +The daemon reads, in this order: + +1. the file `--config` names: `komorebi --config ~/mine.json`, or `komorebic start --config + ~/mine.json`. Environment variables in the path, such as `$HOME`, are replaced; +2. `komorebi.json` in the config home, which is `$KOMOREBI_CONFIG_HOME` when that is set (it has + to be a directory) and `~/.config/komorebi` when it is not. + +With neither, komorebi runs on its defaults, which are what every setting below says it is when +the file leaves it out. [`komorebic configuration`](../cli/configuration.md) (or `komorebic +config`) prints the path of the file in the config home, when there is one. + +On NixOS, [the module's `configFile`](../installation.md#options) gives the daemon a file the +same way `--config` does. + +## Changing the file + +The daemon watches the file it read. When the file changes, about two seconds later it reads it +again and applies it to the windows it has: it sets the settings, gives each monitor the +workspaces the file lists for it, and tiles every monitor again. The windows stay in the +workspaces they are in. An editor that writes the file in place and one that writes a new file +and renames it over the old one are both followed. + +A file that cannot be read, or that has a value of the wrong kind, changes nothing: the daemon +logs the error and keeps what it has. The file is written as JSON that may have comments and +trailing commas. + +Reading the file again sets every setting of the daemon from it, and a key the file leaves out is +the default of the setting: a `resize-delta` given with a command is gone when the file changes. +Three things stay as they were when the file leaves them out: `default_workspace_padding`, +`default_container_padding` and `display_index_preferences`. The rules add up, as +[Rules](#rules) says. A workspace the file lists gets its name, padding, offsets and rules from +its entry, and its layout when the entry names one; a workspace the file does not list is left as +it is. + +[`komorebic generate-static-config`](../cli/generate-static-config.md) prints the settings the +daemon has now as a `komorebi.json`: a way to start a file from a setup arrived at with commands. +The rules (`ignore_rules`, `manage_rules` and `floating_applications`) are not in what it prints. + +## One file for every platform + +komorebi for Windows and komorebi for Mac have their own keys, and one `komorebi.json` can serve +all of them. A key that komorebi for KDE does not read is ignored, and so is a key it does not +know: loading never fails because of one. Keys that mean nothing on Plasma, because they are about +how another platform draws or hides windows, are accepted: `titleless_applications`, +`tabbed_applications`, `window_hiding_position` of a monitor, and the keys that only Windows has +(`window_hiding_behaviour`, `border_style`, `stackbar`, and the others of the Windows file). + +## The keys + +### Settings of the daemon + +| Key | Default | What it does | +|---|---|---| +| `resize_delta` | `50` | How many pixels `resize-edge` and `resize-axis` resize by | +| `mouse_follows_focus` | `true` | Whether the pointer goes to the window that is given the focus | +| `cross_monitor_move_behaviour` | `Swap` | What `move` does at the edge of a monitor: `Swap`, `Insert` or `NoOp` | +| `cross_boundary_behaviour` | `Monitor` | Where `focus` and `move` go at the edge of a monitor: to the next `Monitor` or the next `Workspace` | +| `unmanaged_window_operation_behaviour` | `Op` | Whether a command is carried out while the focused window is not tiled: `Op` or `NoOp` | +| `window_container_behaviour` | `Create` | What a window that opens gets: a tile of its own (`Create`) or a place in the focused stack (`Append`) | +| `float_override` | `false` | Whether every window that opens floats | +| `float_override_placement` | `None` | What is done to a window the override floats: `None`, `Center` or `CenterAndResize` | +| `floating_layer_behaviour` | `Tile` | What a window that opens while a workspace is on its floating layer gets: `Tile` or `Float` | +| `floating_layer_placement` | `Center` | What is done to a window that `floating_layer_behaviour` floats | +| `monocle_focus_behaviour` | `NoOp` | What `focus` does while a container is in monocle: `NoOp` or `Cycle` | +| `toggle_float_placement` | `CenterAndResize` | What `toggle-float` does to the window it floats: `None`, `Center` or `CenterAndResize` | +| `float_rule_placement` | `None` | The same, for a window that opens and matches `floating_applications` | +| `floating_window_aspect_ratio` | `Standard` | The aspect ratio `CenterAndResize` gives the window: `Standard` (4:3), `Widescreen` (16:9), `Ultrawide` (21:9) or `[width, height]` | + +### Padding and offsets + +| Key | Default | What it does | +|---|---|---| +| `default_workspace_padding` | `5` | The gap, in pixels, between the edge of the work area and the tiles | +| `default_container_padding` | `5` | The gap around each tile | +| `global_work_area_offset` | none | The part of every monitor's work area that tiles stay out of: `left`, `top`, `right` and `bottom`. `left` and `top` move the edge in; `right` and `bottom` make the area narrower and shorter by that much | + +[Padding and work area offsets](padding-and-offsets.md) explains how the three nest. A monitor +(`container_padding`, `workspace_padding`, `work_area_offset`) and a workspace (the same three) +can have values of their own, which come before the default. + +### Rules + +| Key | What it does | +|---|---| +| `ignore_rules` | Windows komorebi leaves alone (`float_rules` is the same key under its old name) | +| `manage_rules` | Windows komorebi tiles whatever the ignore rules say | +| `floating_applications` | Windows that open floating | + +Each is a list of rules, which [Rules](rules.md) explains. A rule is an object with `kind` (`Exe`, +`Class`, `Title` or `Path`), `id` and `matching_strategy` (`Equals`, `StartsWith`, `EndsWith`, +`Contains`, `Regex`, or one of the four that negate them: `DoesNotEqual`, `DoesNotStartWith`, +`DoesNotEndWith` and `DoesNotContain`), or a list of such objects, all of which have to match. +Rules in the file add to the ones the daemon has: a rule that is taken out of the file stays +until the daemon restarts. + +### Monitors and workspaces + +`monitors` is a list with one entry for each monitor, each with its `workspaces`. The first entry +is for the first monitor, the second for the second, and so on. A monitor that has no entry keeps +what it has. + +`display_index_preferences` puts an entry on a monitor by what the monitor is called instead +of by its place: `{ "0": "DP-1", "1": "HDMI-A-1" }` says that the entry at index 0 is for the +monitor `DP-1`. `komorebic monitor-information` shows the names. +A monitor that has no preference takes the first entry nobody's preference names and that no +other monitor has taken. + +A monitor entry can also have a `floating_layer_behaviour`, which is the one its workspaces take +unless they have their own, and which comes before the one for every monitor. + +A monitor takes as many workspaces as its entry lists, and KWin gets a virtual desktop for each, +named for it. A workspace has these keys: + +| Key | Default | What it does | +|---|---|---| +| `name` | required | The name `focus-named-workspace` and the other named commands find it by | +| `layout` | none | The layout: `BSP`, `Columns`, `Rows`, `VerticalStack`, `RightMainVerticalStack`, `HorizontalStack`, `UltrawideVerticalStack`, `Grid` or `Scrolling` | +| `tile` | see below | Whether the workspace tiles its windows | +| `layout_flip` | none | The axis the layout is mirrored on: `Horizontal`, `Vertical` or `HorizontalAndVertical` | +| `layout_options` | none | Options of the layout, such as `column_ratios` and `scrolling` | +| `layout_rules` | none | `{ "3": "Columns" }`: the layout the workspace has once it has 3 containers or more | +| `layout_options_rules` | none | The same, for the layout options | +| `container_padding`, `workspace_padding` | the default | The padding of this workspace | +| `work_area_offset` | none | The offset of this workspace | +| `work_area_offset_rules` | none | `{ "2": { "left": 100, "top": 0, "right": 200, "bottom": 0 } }`: the offset the workspace has once it has 2 containers or more | +| `apply_window_based_work_area_offset` | `true` | Whether the workspace takes its monitor's window-based offset | +| `window_container_behaviour` | the default | What a window that opens on this workspace gets: `Create` or `Append` | +| `window_container_behaviour_rules` | none | `{ "2": "Append" }`: the behavior the workspace has once it has 2 containers or more | +| `float_override` | the default | Whether every window that opens on this workspace floats | +| `floating_layer_behaviour` | the default | What a window that opens while this workspace is on its floating layer gets: `Tile` or `Float` | + +A workspace that names no `layout` and does not say `"tile": true` does not tile: its windows +stay where they open. A workspace with `layout_rules` tiles. Otherwise a workspace tiles. + +The highest of the rules that the number of containers reaches wins. A layout rule changes the +layout of the workspace and leaves it there when the number falls below the threshold again, so a +rule at 1 is how to say what the layout is when there is one window; the offset and the layout +options of a rule are the ones the workspace has while it has that many containers. + +The window container behavior rules are the exception: while the workspace has fewer containers +than the lowest threshold it has no behavior of its own and takes the one for every workspace, +and a workspace that has rules takes its behavior from them alone, so +`toggle-workspace-window-container-behaviour` does not outlast the next time it is tiled. + +### Layout options for every workspace + +`layout_defaults` gives the layout options and the layout options rules of a layout to every +workspace that has that layout and sets neither `layout_options` nor `layout_options_rules`: + +```json +{ + "layout_defaults": { + "Columns": { "layout_options": { "column_ratios": [0.6] } }, + "Scrolling": { "layout_options": { "scrolling": { "columns": 2 } } } + } +} +``` + +A workspace that sets either of its own has none of the defaults of its layout, not even for the +setting it leaves out. + +## Layout rules from the command line + +The layout rules of a workspace can be added and taken away while the daemon runs: + +```sh +komorebic workspace-layout-rule 0 1 3 columns +komorebic named-workspace-layout-rule mail 2 rows +komorebic clear-workspace-layout-rules 0 1 +komorebic clear-named-workspace-layout-rules mail +``` + +[`workspace-layout-rule`](../cli/workspace-layout-rule.md) takes the index of the monitor, the +index of the workspace, the number of containers and the layout; +[`named-workspace-layout-rule`](../cli/named-workspace-layout-rule.md) takes the name of the +workspace instead. A rule for a count that has one replaces it. The clear commands take every +rule of the workspace away and leave it with the layout it has. diff --git a/docs/usage/floating-windows.md b/docs/usage/floating-windows.md index d286896a..8ab55a4d 100644 --- a/docs/usage/floating-windows.md +++ b/docs/usage/floating-windows.md @@ -31,6 +31,12 @@ 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. +In `komorebi.json` it is `float_override`, for every workspace and in the entry of a workspace. +`float_override_placement` says what is done to the window the override floats: `None` leaves it +where KWin put it, `Center` centers it in the work area and `CenterAndResize` also makes it half +as tall as the work area, with the aspect ratio `floating_window_aspect_ratio` names. A window is +centered only on a workspace that tiles. + ## The two layers A workspace is on one of two layers: its tiles, or its floating windows. Which one decides what @@ -68,3 +74,10 @@ On the floating layer: there, and when it is restored it is a tile, not a floating window. The layer is `layer` in the state of each workspace, `Tiling` or `Floating`. + +What a window that opens while a workspace is on its floating layer gets is +`floating_layer_behaviour` in `komorebi.json`: `Tile`, the default, gives it a tile, and `Float` +floats it, centered in the work area as `floating_layer_placement` says (`Center` by default; the +values are those of `float_override_placement`). The entry of a monitor and the entry of a +workspace can have a `floating_layer_behaviour` of their own: the workspace's comes before the +monitor's, which comes before the one for every monitor. diff --git a/docs/usage/monocle.md b/docs/usage/monocle.md index 9daf4d77..3add84d7 100644 --- a/docs/usage/monocle.md +++ b/docs/usage/monocle.md @@ -36,8 +36,9 @@ does meanwhile is set with `right` or `up` the next one. [`komorebic toggle-monocle-focus-behaviour`](../cli/toggle-monocle-focus-behaviour.md) switches -between the two. [`komorebic cycle-focus`](../cli/cycle-focus.md) always carries the monocle to -the next or the previous container, whatever the behavior is. +between the two, and `monocle_focus_behaviour` in `komorebi.json` (`NoOp` or `Cycle`) sets it from +the file. [`komorebic cycle-focus`](../cli/cycle-focus.md) always carries the monocle to the next or +the previous container, whatever the behavior is. ```sh komorebic monocle-focus-behaviour cycle diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md index 5673ef0c..b037b6b4 100644 --- a/docs/usage/running-komorebi.md +++ b/docs/usage/running-komorebi.md @@ -35,6 +35,13 @@ to KWin on the session bus and loads a script into it, so start it from a termin session. Outside a Plasma session it exits with an error that says what is missing, which `komorebic start` prints. +`--config` gives the daemon the `komorebi.json` to read +([Configuration](configuration.md) says where it looks otherwise): + +```sh +komorebic start --config ~/mine.json +``` + 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: diff --git a/docs/usage/stacking-windows.md b/docs/usage/stacking-windows.md index 80eaf8b8..cc69716d 100644 --- a/docs/usage/stacking-windows.md +++ b/docs/usage/stacking-windows.md @@ -93,6 +93,18 @@ 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. +In `komorebi.json`, `window_container_behaviour` is the setting for every workspace, `Create` or +`Append`, and the entry of a workspace can have its own. The entry of a workspace can also have +`window_container_behaviour_rules`, which give the behavior by the number of containers: + +```json +{ "name": "chat", "layout": "Columns", "window_container_behaviour_rules": { "2": "Append" } } +``` + +A window opens in a tile of its own until the workspace has two containers, and joins the focused +stack from then on. The [configuration](configuration.md) page says how the rules and the toggle +for one workspace go together. + ## Where the windows behind go komorebi does not minimize the windows behind the front one: it moves them to a virtual desktop diff --git a/docs/usage/subscribing-to-notifications.md b/docs/usage/subscribing-to-notifications.md index 79f34b8c..22b8480f 100644 --- a/docs/usage/subscribing-to-notifications.md +++ b/docs/usage/subscribing-to-notifications.md @@ -49,8 +49,8 @@ sent. 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 +window that is shown, of every new subscription, so it receives the state as soon as it +subscribes, and of every reload of `komorebi.json`. `komorebic subscribe-socket` has no option for it; a program writes the message on the daemon's socket itself: ```sh diff --git a/flake.nix b/flake.nix index f8d1cee1..8a55e303 100644 --- a/flake.nix +++ b/flake.nix @@ -47,8 +47,12 @@ (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); + # the messages the tests of the bridge and of the daemon share, the configurations + # the tests load, and the schemas + || (pkgs.lib.hasSuffix ".json" path) + # the page of the docs that shows the example configuration, which a test compares + # with the example file + || (pkgs.lib.hasSuffix "docs/example-configurations.md" path); }; commonArgs = { diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index 6c5ed652..3f8e0a1b 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -77,6 +77,7 @@ 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::static_config::StaticConfig; pub use komorebi::window::Window; pub use komorebi::workspace::Workspace; pub use komorebi::workspace::WorkspaceLayer; @@ -315,7 +316,8 @@ pub fn subscribe(name: &str) -> std::io::Result { /// 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. +/// changed the [`State`], and always when a window is shown, when a subscriber is added and when +/// the configuration is reloaded. /// /// # Errors /// diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index fe19b180..bb3fda84 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -13,6 +13,7 @@ color-eyre = { workspace = true } crossbeam-channel = { workspace = true } ctrlc = { version = "3", features = ["termination"] } dirs = { workspace = true } +hotwatch = { workspace = true } lazy_static = { workspace = true } nanoid = "0.4" parking_lot = "0.12" diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 124149f9..4f6cc053 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -285,8 +285,9 @@ pub enum StateQuery { /// 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. +/// [`State`](crate::state::State), and always when a window is shown, when a subscriber is added +/// (so a new subscriber receives the state as soon as it subscribes) and when the configuration is +/// reloaded. /// /// # Example /// @@ -448,7 +449,24 @@ pub enum SocketMessage { NamedWorkspaceLayout(String, DefaultLayout), // WorkspaceLayoutCustom(usize, usize, #[serde_as(as = "ResolvedPathBuf")] PathBuf), // NamedWorkspaceLayoutCustom(String, #[serde_as(as = "ResolvedPathBuf")] PathBuf), + WorkspaceLayoutRule(usize, usize, usize, DefaultLayout), + NamedWorkspaceLayoutRule(String, usize, DefaultLayout), + // WorkspaceLayoutCustomRule( + // usize, + // usize, + // usize, + // #[serde_as(as = "ResolvedPathBuf")] PathBuf, + // ), + // NamedWorkspaceLayoutCustomRule(String, usize, #[serde_as(as = "ResolvedPathBuf")] PathBuf), + ClearWorkspaceLayoutRules(usize, usize), + ClearNamedWorkspaceLayoutRules(String), ToggleWorkspaceLayer, + // Configuration + // ReloadConfiguration, + ReloadStaticConfiguration(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + // WatchConfiguration(bool), + // CompleteConfiguration, + // AltFocusHack(bool), WorkAreaOffset(Rect), MonitorWorkAreaOffset(usize, Rect), WorkspaceWorkAreaOffset(usize, usize, Rect), @@ -477,6 +495,7 @@ pub enum SocketMessage { RemoveSubscriberSocket(String), // AddSubscriberPipe(String), // RemoveSubscriberPipe(String), + GenerateStaticConfig, DebugWindow(u32), } diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 7d003424..a8381b3e 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -22,6 +22,8 @@ //! [`notify_subscribers`] sends every subscriber a [`Notification`] of it, with the state. use crate::core::ApplicationIdentifier; +use crate::core::DefaultLayout; +use crate::core::LayoutDefaultEntry; use crate::core::SocketMessage; use crate::core::SubscribeOptions; use crate::core::config_generation::IdWithIdentifier; @@ -32,6 +34,7 @@ use crate::window::AspectRatio; use crate::window::PredefinedAspectRatio; use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; +use core::pathext::PathExt; use lazy_static::lazy_static; use parking_lot::Mutex; use parking_lot::RwLock; @@ -59,6 +62,7 @@ pub mod monitor; pub mod process_command; pub mod process_event; pub mod state; +pub mod static_config; pub mod window; pub mod window_manager; pub mod window_manager_event; @@ -70,6 +74,32 @@ pub mod workspace; pub type LibraryError = eyre::Report; lazy_static! { + /// Where komorebi looks for `komorebi.json` and the files next to it: `$KOMOREBI_CONFIG_HOME` + /// if that is set, else `~/.config/komorebi` + /// + /// # Panics + /// + /// `$KOMOREBI_CONFIG_HOME` is set and is not a directory, or there is no home directory. + pub static ref HOME_DIR: PathBuf = { + std::env::var("KOMOREBI_CONFIG_HOME").map_or_else( + |_| { + dirs::home_dir() + .expect("there is no home directory") + .join(".config") + .join("komorebi") + }, + |home_path| { + let home = home_path.replace_env(); + + assert!( + home.is_dir(), + "$KOMOREBI_CONFIG_HOME is set to \"{home_path}\", which is not a valid directory" + ); + + home + }, + ) + }; /// Where komorebi keeps the files it needs while it runs, such as the script it loads into /// 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 @@ -138,6 +168,10 @@ lazy_static! { /// The windows komorebi took out of sight (the back of a stack, on the parking desktop), so /// that what the compositor reports about them is not mistaken for something the user did pub static ref HIDDEN_WINDOWS: Arc>> = Arc::new(Mutex::new(HashSet::new())); + /// The layout options and the layout options rules that `layout_defaults` in `komorebi.json` + /// gives each layout, for a workspace that sets neither of its own + pub static ref LAYOUT_DEFAULTS: 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 @@ -146,6 +180,12 @@ 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); +/// How many pixels `ResizeWindowEdge` and `ResizeWindowAxis` resize by, when `komorebi.json` does +/// not say +pub static DEFAULT_RESIZE_DELTA: i32 = 50; +/// Whether the pointer goes to the window that is given the focus, when `komorebi.json` does not +/// say +pub static DEFAULT_MOUSE_FOLLOWS_FOCUS: bool = true; /// The event or the message a [`Notification`] is about /// @@ -209,8 +249,8 @@ pub struct Notification { /// /// 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. +/// only if `state_has_been_modified`, or if the notification is about a window being shown, a +/// subscriber being added or the configuration being reloaded. /// /// 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 @@ -270,6 +310,7 @@ pub fn notify_subscribers( notification.event, NotificationEvent::Socket(SocketMessage::AddSubscriberSocket(_)) | NotificationEvent::Socket(SocketMessage::AddSubscriberSocketWithOptions(_, _)) + | NotificationEvent::Socket(SocketMessage::ReloadStaticConfiguration(_)) | NotificationEvent::WindowManager(WindowManagerEvent::Show(_, _)) ); diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index e00fde4b..ee15ef6b 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -5,8 +5,12 @@ //! //! 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, listens for +//! with an in-memory desktop with one monitor and no windows, for development and testing. +//! +//! The daemon starts from `komorebi.json`: the file `--config` names, or else the one in +//! [`struct@HOME_DIR`] when there is one ([`komorebi::static_config`]), which it reloads whenever +//! it changes. Without a file it runs on its defaults. It loads the monitors and the windows +//! that are open, gives each monitor the configuration the file has for it, tiles them, listens for //! messages on `komorebi.sock` in [`struct@DATA_DIR`], handles the events the backend reports on //! a thread of their own, and runs until it is stopped, with `SIGINT`, `SIGTERM` or a `Stop` //! message. @@ -23,17 +27,21 @@ use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; use komorebi::DATA_DIR; +use komorebi::HOME_DIR; use komorebi::LOG_DIR; use komorebi::backend; use komorebi::backend::fake::FakeBackend; +use komorebi::core::pathext::replace_env_in_path; use komorebi::process_command::listen_for_commands; use komorebi::process_event::listen_for_events; +use komorebi::static_config::StaticConfig; 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::path::PathBuf; use std::sync::Arc; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::EnvFilter; @@ -150,6 +158,10 @@ struct Opts { /// Level of log output verbosity #[clap(long, value_enum, default_value_t=LogLevel::Info)] log_level: LogLevel, + /// Path to a static configuration JSON file + #[clap(short, long)] + #[clap(value_parser = replace_env_in_path)] + config: Option, /// 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)] @@ -175,12 +187,46 @@ fn main() -> eyre::Result<()> { #[cfg(feature = "deadlock_detection")] detect_deadlocks(); - let wm = Arc::new(Mutex::new(WindowManager::new( - window_manager_event_listener::event_rx(), - None, - )?)); + let static_config = opts.config.map_or_else( + || { + let komorebi_json = HOME_DIR.join("komorebi.json"); + if komorebi_json.is_file() { + Option::from(komorebi_json) + } else { + None + } + }, + Option::from, + ); + + let wm = if let Some(config) = &static_config { + tracing::info!( + "creating window manager from static configuration file: {}", + config.display() + ); + + Arc::new(Mutex::new(StaticConfig::preload( + config, + window_manager_event_listener::event_rx(), + None, + )?)) + } else { + Arc::new(Mutex::new(WindowManager::new( + window_manager_event_listener::event_rx(), + None, + )?)) + }; wm.lock().init()?; + + if let Some(config) = &static_config { + StaticConfig::postload(config, &wm)?; + } + + // the configuration may have given monitors more workspaces than they started with (and named + // them): the compositor needs a desktop for each + wm.lock().sync_workspace_desktops(); + wm.lock().retile_all(false)?; listen_for_commands(wm.clone()); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index e337a0ad..3e6c0fd8 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -14,6 +14,8 @@ //! - **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. +//! - **GenerateStaticConfig**: the window manager's settings as a `komorebi.json` +//! ([`StaticConfig`]), as JSON. //! //! The others answer nothing: //! @@ -61,6 +63,14 @@ //! - **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. +//! - **WorkspaceLayoutRule** and **NamedWorkspaceLayoutRule** make a workspace change to a layout +//! once it has so many containers, and **ClearWorkspaceLayoutRules** and +//! **ClearNamedWorkspaceLayoutRules** take its rules away +//! ([`WindowManager::add_workspace_layout_default_rule`], +//! [`WindowManager::clear_workspace_layout_rules`]). +//! - **ReloadStaticConfiguration** applies a `komorebi.json` to the window manager +//! ([`WindowManager::reload_static_configuration`]). The daemon sends itself this message when +//! the file it was started with changes. //! - **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. @@ -189,6 +199,7 @@ use crate::monitor::MonitorInformation; use crate::notify_subscribers; use crate::state::GlobalState; use crate::state::State; +use crate::static_config::StaticConfig; use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; @@ -885,6 +896,9 @@ impl WindowManager { self.move_workspace_to_monitor(monitor_idx)?; } + SocketMessage::ReloadStaticConfiguration(ref pathbuf) => { + self.reload_static_configuration(pathbuf)?; + } SocketMessage::ToggleCrossMonitorMoveBehaviour => { match self.cross_monitor_move_behaviour { MoveBehaviour::Swap => { @@ -912,6 +926,19 @@ impl WindowManager { SocketMessage::WorkspaceLayout(monitor_idx, workspace_idx, layout) => { self.set_workspace_layout_default(monitor_idx, workspace_idx, layout)?; } + SocketMessage::WorkspaceLayoutRule( + monitor_idx, + workspace_idx, + at_container_count, + layout, + ) => { + self.add_workspace_layout_default_rule( + monitor_idx, + workspace_idx, + at_container_count, + layout, + )?; + } SocketMessage::NamedWorkspaceTiling(ref workspace, tile) => { if let Some((monitor_idx, workspace_idx)) = self.monitor_workspace_index_by_name(workspace) @@ -929,6 +956,9 @@ impl WindowManager { self.set_workspace_layout_default(monitor_idx, workspace_idx, layout)?; } } + SocketMessage::ClearWorkspaceLayoutRules(monitor_idx, workspace_idx) => { + self.clear_workspace_layout_rules(monitor_idx, workspace_idx)?; + } SocketMessage::EnsureWorkspaces(monitor_idx, workspace_count) => { self.ensure_workspaces_for_monitor(monitor_idx, workspace_count)?; } @@ -1558,6 +1588,25 @@ impl WindowManager { focused_workspace.layout_options = Some(options); self.update_focused_workspace(false, false)?; } + SocketMessage::NamedWorkspaceLayoutRule(ref workspace, at_container_count, layout) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + self.add_workspace_layout_default_rule( + monitor_idx, + workspace_idx, + at_container_count, + layout, + )?; + } + } + SocketMessage::ClearNamedWorkspaceLayoutRules(ref workspace) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + self.clear_workspace_layout_rules(monitor_idx, workspace_idx)?; + } + } SocketMessage::MouseFollowsFocus(enable) => { self.mouse_follows_focus = enable; } @@ -1599,6 +1648,11 @@ impl WindowManager { SocketMessage::StopIgnoreRestore => { self.stop(true)?; } + SocketMessage::GenerateStaticConfig => { + let config = serde_json::to_string_pretty(&StaticConfig::from(&*self))?; + + reply.write_all(config.as_bytes())?; + } SocketMessage::QuickSave => { let workspace = self.focused_workspace()?; let resize = &workspace.resize_dimensions; diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 72de5ce7..ae6d0504 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -12,6 +12,8 @@ //! [`Notification`]: crate::Notification use crate::DATA_DIR; +use crate::DISPLAY_INDEX_PREFERENCES; +use crate::HOME_DIR; use crate::IGNORE_IDENTIFIERS; use crate::MANAGE_IDENTIFIERS; use crate::core::MonocleFocusBehaviour; @@ -32,7 +34,7 @@ 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 +/// rules, the indices the user gave the monitors, and the configuration and the data directories /// /// # Example /// @@ -44,6 +46,8 @@ use std::path::PathBuf; /// 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!(state.display_index_preferences.is_empty()); +/// assert_eq!(state.configuration_dir, *komorebi::HOME_DIR); /// assert_eq!(state.data_dir, *komorebi::DATA_DIR); /// /// # Ok::<(), Box>(()) @@ -71,8 +75,10 @@ pub struct GlobalState { // pub tray_and_multi_window_identifiers: Vec, // pub name_change_on_launch_identifiers: Vec, // pub monitor_index_preferences: HashMap, + pub display_index_preferences: HashMap, // pub ignored_duplicate_monitor_serial_ids: Vec, // pub window_hiding_behaviour: HidingBehaviour, + pub configuration_dir: PathBuf, pub data_dir: PathBuf, // pub custom_ffm: bool, } @@ -82,6 +88,8 @@ impl Default for GlobalState { Self { ignore_identifiers: IGNORE_IDENTIFIERS.lock().clone(), manage_identifiers: MANAGE_IDENTIFIERS.lock().clone(), + display_index_preferences: DISPLAY_INDEX_PREFERENCES.read().clone(), + configuration_dir: HOME_DIR.clone(), data_dir: DATA_DIR.clone(), } } @@ -167,6 +175,9 @@ impl From<&WindowManager> for State { floating_windows: workspace.floating_windows.clone(), layout: workspace.layout.clone(), layout_options: workspace.layout_options, + layout_rules: workspace.layout_rules.clone(), + layout_options_rules: workspace.layout_options_rules.clone(), + layout_defaults_cache: workspace.layout_defaults_cache.clone(), layout_flip: workspace.layout_flip, workspace_padding: workspace.workspace_padding, container_padding: workspace.container_padding, @@ -174,9 +185,13 @@ impl From<&WindowManager> for State { resize_dimensions: workspace.resize_dimensions.clone(), tile: workspace.tile, work_area_offset: workspace.work_area_offset, + work_area_offset_rules: workspace.work_area_offset_rules.clone(), apply_window_based_work_area_offset: workspace .apply_window_based_work_area_offset, window_container_behaviour: workspace.window_container_behaviour, + window_container_behaviour_rules: workspace + .window_container_behaviour_rules + .clone(), float_override: workspace.float_override, layer: workspace.layer, floating_layer_behaviour: workspace.floating_layer_behaviour, diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs new file mode 100644 index 00000000..e2c92dc8 --- /dev/null +++ b/komorebi/src/static_config.rs @@ -0,0 +1,1162 @@ +//! `komorebi.json`, the static configuration: [`StaticConfig`] and the [`MonitorConfig`] and +//! [`WorkspaceConfig`] it holds. +//! +//! The daemon reads the file when it starts: [`StaticConfig::preload`] makes the window manager +//! from it and starts watching the file, [`StaticConfig::postload`] gives each monitor and +//! workspace the configuration of its place once the monitors are known. When the file changes, +//! the watcher sends the daemon a `ReloadStaticConfiguration` message on its own socket, and +//! [`StaticConfig::reload`] applies the file to the window manager that is running. The other way +//! round, `StaticConfig::from(&WindowManager)` writes the window manager's settings as a +//! configuration, which is what `komorebic generate-static-config` prints. +//! +//! One `komorebi.json` is meant to work on every platform komorebi runs on, so a key that does +//! nothing on KDE Plasma is accepted and ignored, and a key that is not known at all is ignored +//! too, as serde does. +//! +//! Settings that have no key are left to their defaults ([`DEFAULT_RESIZE_DELTA`], +//! [`DEFAULT_WORKSPACE_PADDING`] and the others in [`crate`]), and an optional key set to `null` +//! is the same as one that is left out. + +use crate::DATA_DIR; +use crate::DEFAULT_CONTAINER_PADDING; +use crate::DEFAULT_MOUSE_FOLLOWS_FOCUS; +use crate::DEFAULT_RESIZE_DELTA; +use crate::DEFAULT_WORKSPACE_PADDING; +use crate::DISPLAY_INDEX_PREFERENCES; +use crate::FLOATING_APPLICATIONS; +use crate::FLOATING_WINDOW_TOGGLE_ASPECT_RATIO; +use crate::IGNORE_IDENTIFIERS; +use crate::LAYOUT_DEFAULTS; +use crate::MANAGE_IDENTIFIERS; +use crate::REGEX_IDENTIFIERS; +use crate::core::Axis; +use crate::core::CrossBoundaryBehaviour; +use crate::core::DefaultLayout; +use crate::core::FloatingLayerBehaviour; +use crate::core::Layout; +use crate::core::LayoutDefaultEntry; +use crate::core::LayoutOptions; +use crate::core::MonocleFocusBehaviour; +use crate::core::MoveBehaviour; +use crate::core::OperationBehaviour; +use crate::core::Placement; +use crate::core::Rect; +use crate::core::SocketMessage; +use crate::core::WindowContainerBehaviour; +use crate::core::WindowHidingPosition; +use crate::core::WindowManagementBehaviour; +use crate::core::config_generation::MatchingRule; +use crate::core::config_generation::MatchingStrategy; +use crate::monitor::Monitor; +use crate::ring::Ring; +use crate::window::AspectRatio; +use crate::window::PredefinedAspectRatio; +use crate::window_manager::WindowManager; +use crate::window_manager_event::WindowManagerEvent; +use crate::workspace::Workspace; +use color_eyre::eyre; +use crossbeam_channel::Receiver; +use hotwatch::EventKind; +use hotwatch::Hotwatch; +use parking_lot::Mutex; +use regex::Regex; +use serde::Deserialize; +use serde::Serialize; +use std::collections::HashMap; +use std::io::ErrorKind; +use std::io::Write; +use std::os::unix::net::UnixListener; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +// serde_as must be before derive +#[serde_with::serde_as] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Workspace configuration +pub struct WorkspaceConfig { + /// Name + pub name: String, + /// Layout + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = DefaultLayout::BSP)))] + pub layout: Option, + /// Layout-specific options + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_options: Option, + /// Threshold-based layout options rules in the format of threshold => options. + /// When container count >= threshold, the highest matching threshold's options + /// fully replace the base `layout_options`. + /// This follows the same threshold logic as `layout_rules`. + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_options_rules: Option>, + // /// END OF LIFE FEATURE: Custom Layout (default: None) + // #[serde(skip_serializing_if = "Option::is_none")] + // #[serde_as(as = "Option")] + // pub custom_layout: Option, + /// Layout rules in the format of threshold => layout + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_rules: Option>, + /// Container padding (default: global) + #[serde(skip_serializing_if = "Option::is_none")] + pub container_padding: Option, + /// Workspace padding (default: global) + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_padding: Option, + /// Work area offset rules in the format of threshold => Rect (default: None) + #[serde(skip_serializing_if = "Option::is_none")] + pub work_area_offset_rules: Option>, + /// Workspace specific work area offset + #[serde(skip_serializing_if = "Option::is_none")] + pub work_area_offset: Option, + /// Apply this monitor's window-based work area offset + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] + pub apply_window_based_work_area_offset: Option, + /// Determine what happens when a new window is opened + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] + pub window_container_behaviour: Option, + /// Window container behavior rules in the format of threshold => behavior + #[serde(skip_serializing_if = "Option::is_none")] + pub window_container_behaviour_rules: Option>, + /// Enable or disable float override, which makes it so every new window opens in floating mode + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] + pub float_override: Option, + /// Enable or disable tiling for the workspace + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] + pub tile: Option, + /// Specify an axis on which to flip the selected layout + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_flip: Option, + /// Determine what happens to a new window when the Floating workspace layer is active + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] + pub floating_layer_behaviour: Option, +} + +impl From<&Workspace> for WorkspaceConfig { + fn from(value: &Workspace) -> Self { + let mut layout_rules = HashMap::new(); + for (threshold, layout) in &value.layout_rules { + match layout { + Layout::Default(value) => { + layout_rules.insert(*threshold, *value); + } + } + } + let layout_rules = (!layout_rules.is_empty()).then_some(layout_rules); + + let mut work_area_offset_rules = HashMap::new(); + for (threshold, rect) in &value.work_area_offset_rules { + work_area_offset_rules.insert(*threshold, *rect); + } + let work_area_offset_rules = + (!work_area_offset_rules.is_empty()).then_some(work_area_offset_rules); + + let mut window_container_behaviour_rules = HashMap::new(); + for (threshold, behaviour) in value.window_container_behaviour_rules.iter().flatten() { + window_container_behaviour_rules.insert(*threshold, *behaviour); + } + + let default_container_padding = DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst); + let default_workspace_padding = DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst); + + let container_padding = value.container_padding.and_then(|container_padding| { + if container_padding == default_container_padding { + None + } else { + Option::from(container_padding) + } + }); + + let workspace_padding = value.workspace_padding.and_then(|workspace_padding| { + if workspace_padding == default_workspace_padding { + None + } else { + Option::from(workspace_padding) + } + }); + + let tile = if value.tile { None } else { Some(false) }; + + Self { + name: value + .name + .clone() + .unwrap_or_else(|| String::from("unnamed")), + layout: value + .tile + .then_some(match value.layout { + Layout::Default(layout) => Option::from(layout), + }) + .flatten(), + layout_options: { + tracing::debug!( + "Parsing workspace config - layout_options: {:?}", + value.layout_options + ); + value.layout_options + }, + layout_options_rules: if value.layout_options_rules.is_empty() { + None + } else { + Some(value.layout_options_rules.iter().copied().collect()) + }, + // custom_layout: value + // .workspace_config + // .as_ref() + // .and_then(|c| c.custom_layout.clone()), + layout_rules, + container_padding, + workspace_padding, + work_area_offset_rules, + work_area_offset: value.work_area_offset, + apply_window_based_work_area_offset: Some(value.apply_window_based_work_area_offset), + window_container_behaviour: value.window_container_behaviour, + window_container_behaviour_rules: if window_container_behaviour_rules.is_empty() { + None + } else { + Some(window_container_behaviour_rules) + }, + float_override: value.float_override, + tile, + layout_flip: value.layout_flip, + floating_layer_behaviour: value.floating_layer_behaviour, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Monitor configuration +pub struct MonitorConfig { + /// Workspace configurations + pub workspaces: Vec, + /// Monitor-specific work area offset + #[serde(skip_serializing_if = "Option::is_none")] + pub work_area_offset: Option, + /// Window based work area offset + #[serde(skip_serializing_if = "Option::is_none")] + pub window_based_work_area_offset: Option, + /// Open window limit after which the window based work area offset will no longer be applied + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = 1)))] + pub window_based_work_area_offset_limit: Option, + /// Container padding + #[serde(skip_serializing_if = "Option::is_none")] + pub container_padding: Option, + /// Workspace padding (default: global) + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_padding: Option, + /// Determine what happens to a new window when the Floating workspace layer is active + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] + pub floating_layer_behaviour: Option, + /// Accepted so that a configuration written for another platform loads, and ignored: there is + /// no hiding position on KDE Plasma + #[serde(skip_serializing_if = "Option::is_none")] + pub window_hiding_position: Option, +} + +impl From<&Monitor> for MonitorConfig { + fn from(value: &Monitor) -> Self { + let mut workspaces = vec![]; + for w in value.workspaces() { + workspaces.push(WorkspaceConfig::from(w)); + } + + let default_container_padding = DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst); + let default_workspace_padding = DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst); + + let container_padding = value.container_padding.and_then(|container_padding| { + if container_padding == default_container_padding { + None + } else { + Option::from(container_padding) + } + }); + + let workspace_padding = value.workspace_padding.and_then(|workspace_padding| { + if workspace_padding == default_workspace_padding { + None + } else { + Option::from(workspace_padding) + } + }); + + Self { + workspaces, + work_area_offset: value.work_area_offset, + window_based_work_area_offset: value.window_based_work_area_offset, + window_based_work_area_offset_limit: Some(value.window_based_work_area_offset_limit), + container_padding, + workspace_padding, + floating_layer_behaviour: value.floating_layer_behaviour, + window_hiding_position: None, + } + } +} + +#[serde_with::serde_as] +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// The `komorebi.json` static configuration file reference for komorebi for KDE Plasma +pub struct StaticConfig { + // /// DISCOURAGED: Minimum width for a window to be eligible for tiling + // #[serde(skip_serializing_if = "Option::is_none")] + // pub minimum_window_width: Option, + // /// DISCOURAGED: Minimum height for a window to be eligible for tiling + // #[serde(skip_serializing_if = "Option::is_none")] + // pub minimum_window_height: Option, + /// Delta to resize windows by + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_RESIZE_DELTA)))] + pub resize_delta: Option, + /// Determine what happens when a new window is opened + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] + pub window_container_behaviour: Option, + /// Enable or disable float override, which makes it so every new window opens in floating mode + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] + pub float_override: Option, + /// Determines what happens on a new window when on the `FloatingLayer` + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] + pub floating_layer_behaviour: Option, + /// Determines the placement of a new window when toggling to float + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::CenterAndResize)))] + pub toggle_float_placement: Option, + /// Determines the `Placement` to be used when spawning a window on the floating layer with the + /// `FloatingLayerBehaviour` set to `FloatingLayerBehaviour::Float` + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::Center)))] + pub floating_layer_placement: Option, + /// Determines the `Placement` to be used when spawning a window with float override active + #[serde(skip_serializing_if = "Option::is_none")] + pub float_override_placement: Option, + /// Determines the `Placement` to be used when spawning a window that matches a + /// 'floating_applications' rule + #[serde(skip_serializing_if = "Option::is_none")] + pub float_rule_placement: Option, + /// Determine what happens when a window is moved across a monitor boundary + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = MoveBehaviour::Swap)))] + pub cross_monitor_move_behaviour: Option, + /// Determine what happens when an action is called on a window at a monitor boundary + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = CrossBoundaryBehaviour::Monitor)))] + pub cross_boundary_behaviour: Option, + /// Determine what happens when focusing in a direction while a monocle container is active + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = MonocleFocusBehaviour::NoOp)))] + pub monocle_focus_behaviour: Option, + /// Determine what happens when commands are sent while an unmanaged window is in the foreground + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = OperationBehaviour::Op)))] + pub unmanaged_window_operation_behaviour: Option, + /// Enable or disable mouse follows focus + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_MOUSE_FOLLOWS_FOCUS)))] + pub mouse_follows_focus: Option, + /// Global default workspace padding + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_WORKSPACE_PADDING)))] + pub default_workspace_padding: Option, + /// Global default container padding + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_CONTAINER_PADDING)))] + pub default_container_padding: Option, + /// Per-layout default options and rules, keyed by layout name. + /// Applied as fallback when a workspace does not define its own layout_options or layout_options_rules. + /// If a workspace defines either setting, all global defaults for that layout are completely replaced. + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_defaults: Option>, + /// Monitor and workspace configurations + #[serde(skip_serializing_if = "Option::is_none")] + pub monitors: Option>, + // /// Which Windows signal to use when hiding windows (default: Cloak) + // #[serde(skip_serializing_if = "Option::is_none")] + // pub window_hiding_behaviour: Option, + /// Global work area (space used for tiling) offset + #[serde(skip_serializing_if = "Option::is_none")] + pub global_work_area_offset: Option, + /// Individual window floating rules + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "float_rules")] + pub ignore_rules: Option>, + /// Individual window force-manage rules + #[serde(skip_serializing_if = "Option::is_none")] + pub manage_rules: Option>, + /// Identify applications which should be managed as floating windows + #[serde(skip_serializing_if = "Option::is_none")] + pub floating_applications: Option>, + /// Accepted so that a configuration written for another platform loads, and ignored: a KWin + /// window is always a window + #[serde(skip_serializing_if = "Option::is_none")] + pub titleless_applications: Option>, + /// Accepted so that a configuration written for another platform loads, and ignored: a KWin + /// window has no native tabs + #[serde(skip_serializing_if = "Option::is_none")] + pub tabbed_applications: Option>, + // /// Identify border overflow applications + // #[serde(skip_serializing_if = "Option::is_none")] + // pub border_overflow_applications: Option>, + // /// Identify tray and multi-window applications + // #[serde(skip_serializing_if = "Option::is_none")] + // pub tray_and_multi_window_applications: Option>, + // /// Identify applications that have the WS_EX_LAYERED extended window style + // #[serde(skip_serializing_if = "Option::is_none")] + // pub layered_applications: Option>, + // /// Identify applications that send EVENT_OBJECT_NAMECHANGE on launch (very rare) + // #[serde(skip_serializing_if = "Option::is_none")] + // pub object_name_change_applications: Option>, + // /// Do not process EVENT_OBJECT_NAMECHANGE events as Show events for identified applications matching these title regexes + // #[serde(skip_serializing_if = "Option::is_none")] + // pub object_name_change_title_ignore_list: Option>, + // /// Set monitor index preferences + // #[serde(skip_serializing_if = "Option::is_none")] + // pub monitor_index_preferences: Option>, + /// Set display index preferences + #[serde(skip_serializing_if = "Option::is_none")] + pub display_index_preferences: Option>, + // /// Stackbar configuration options + // #[serde(skip_serializing_if = "Option::is_none")] + // pub stackbar: Option, + /// Aspect ratio to resize with when toggling floating mode for a window + #[serde(skip_serializing_if = "Option::is_none")] + pub floating_window_aspect_ratio: Option, + // /// Which Windows API behaviour to use when manipulating windows (default: Sync) + // #[serde(skip_serializing_if = "Option::is_none")] + // pub window_handling_behaviour: Option, +} + +// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +// pub struct TabsConfig { +// /// Width of a stackbar tab +// #[serde(skip_serializing_if = "Option::is_none")] +// pub width: Option, +// /// Focused tab text colour +// #[serde(skip_serializing_if = "Option::is_none")] +// pub focused_text: Option, +// /// Unfocused tab text colour +// #[serde(skip_serializing_if = "Option::is_none")] +// pub unfocused_text: Option, +// /// Tab background colour +// #[serde(skip_serializing_if = "Option::is_none")] +// pub background: Option, +// /// Font family +// #[serde(skip_serializing_if = "Option::is_none")] +// pub font_family: Option, +// /// Font size +// #[serde(skip_serializing_if = "Option::is_none")] +// pub font_size: Option, +// } + +// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +// pub struct StackbarConfig { +// /// Stackbar height +// #[serde(skip_serializing_if = "Option::is_none")] +// pub height: Option, +// /// Stackbar label +// #[serde(skip_serializing_if = "Option::is_none")] +// pub label: Option, +// /// Stackbar mode (default: Never) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub mode: Option, +// /// Stackbar tab configuration options +// #[serde(skip_serializing_if = "Option::is_none")] +// pub tabs: Option, +// } + +impl From<&WindowManager> for StaticConfig { + #[allow(clippy::too_many_lines)] + fn from(value: &WindowManager) -> Self { + let mut monitors = vec![]; + for m in value.monitors() { + monitors.push(MonitorConfig::from(m)); + } + + Self { + resize_delta: Option::from(value.resize_delta), + window_container_behaviour: Option::from( + value.window_management_behaviour.current_behaviour, + ), + float_override: Option::from(value.window_management_behaviour.float_override), + floating_layer_behaviour: Option::from( + value.window_management_behaviour.floating_layer_behaviour, + ), + toggle_float_placement: Option::from( + value.window_management_behaviour.toggle_float_placement, + ), + floating_layer_placement: Option::from( + value.window_management_behaviour.floating_layer_placement, + ), + float_override_placement: Option::from( + value.window_management_behaviour.float_override_placement, + ), + float_rule_placement: Option::from( + value.window_management_behaviour.float_rule_placement, + ), + cross_monitor_move_behaviour: Option::from(value.cross_monitor_move_behaviour), + cross_boundary_behaviour: Option::from(value.cross_boundary_behaviour), + monocle_focus_behaviour: Option::from(value.monocle_focus_behaviour), + unmanaged_window_operation_behaviour: Option::from( + value.unmanaged_window_operation_behaviour, + ), + // minimum_window_height: Some(window::MINIMUM_HEIGHT.load(Ordering::SeqCst)), + // minimum_window_width: Some(window::MINIMUM_WIDTH.load(Ordering::SeqCst)), + mouse_follows_focus: Option::from(value.mouse_follows_focus), + default_workspace_padding: Option::from( + DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst), + ), + default_container_padding: Option::from( + DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst), + ), + layout_defaults: { + let guard = LAYOUT_DEFAULTS.lock(); + if guard.is_empty() { + None + } else { + Some(guard.clone()) + } + }, + monitors: Option::from(monitors), + // window_hiding_behaviour: Option::from(*HIDING_BEHAVIOUR.lock()), + global_work_area_offset: value.work_area_offset, + ignore_rules: None, + floating_applications: None, + titleless_applications: None, + manage_rules: None, + // border_overflow_applications: None, + // tray_and_multi_window_applications: None, + // layered_applications: None, + // object_name_change_applications: None, + // object_name_change_title_ignore_list: None, + // monitor_index_preferences: Option::from(MONITOR_INDEX_PREFERENCES.lock().clone()), + display_index_preferences: Option::from(DISPLAY_INDEX_PREFERENCES.read().clone()), + // stackbar: None, + // slow_application_compensation_time: Option::from( + // SLOW_APPLICATION_COMPENSATION_TIME.load(Ordering::SeqCst), + // ), + // slow_application_identifiers: Option::from(SLOW_APPLICATION_IDENTIFIERS.lock().clone()), + // bar_configurations: None, + // remove_titlebar_applications: Option::from(NO_TITLEBAR.lock().clone()), + floating_window_aspect_ratio: Option::from(*FLOATING_WINDOW_TOGGLE_ASPECT_RATIO.lock()), + // window_handling_behaviour: Option::from(WINDOW_HANDLING_BEHAVIOUR.load()), + tabbed_applications: None, + } + } +} + +impl StaticConfig { + #[allow(clippy::cognitive_complexity, clippy::too_many_lines)] + fn apply_globals(&mut self) -> eyre::Result<()> { + *FLOATING_WINDOW_TOGGLE_ASPECT_RATIO.lock() = self + .floating_window_aspect_ratio + .unwrap_or(AspectRatio::Predefined(PredefinedAspectRatio::Standard)); + + // if let Some(monitor_index_preferences) = &self.monitor_index_preferences { + // let mut preferences = MONITOR_INDEX_PREFERENCES.lock(); + // preferences.clone_from(monitor_index_preferences); + // } + // + + if let Some(display_index_preferences) = &self.display_index_preferences { + let mut preferences = DISPLAY_INDEX_PREFERENCES.write(); + preferences.clone_from(display_index_preferences); + } + + // if let Some(behaviour) = self.window_hiding_behaviour { + // let mut window_hiding_behaviour = HIDING_BEHAVIOUR.lock(); + // *window_hiding_behaviour = behaviour; + // } + + // if let Some(height) = self.minimum_window_height { + // window::MINIMUM_HEIGHT.store(height, Ordering::SeqCst); + // } + // + // if let Some(width) = self.minimum_window_width { + // window::MINIMUM_WIDTH.store(width, Ordering::SeqCst); + // } + + if let Some(container) = self.default_container_padding { + DEFAULT_CONTAINER_PADDING.store(container, Ordering::SeqCst); + } + + if let Some(workspace) = self.default_workspace_padding { + DEFAULT_WORKSPACE_PADDING.store(workspace, Ordering::SeqCst); + } + + if let Some(defaults) = &self.layout_defaults { + *LAYOUT_DEFAULTS.lock() = defaults.clone(); + } else { + LAYOUT_DEFAULTS.lock().clear(); + } + + let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); + let mut manage_identifiers = MANAGE_IDENTIFIERS.lock(); + // let mut tray_and_multi_window_identifiers = TRAY_AND_MULTI_WINDOW_IDENTIFIERS.lock(); + // let mut object_name_change_identifiers = OBJECT_NAME_CHANGE_ON_LAUNCH.lock(); + // let mut object_name_change_title_ignore_list = OBJECT_NAME_CHANGE_TITLE_IGNORE_LIST.lock(); + // let mut layered_identifiers = LAYERED_WHITELIST.lock(); + // let mut slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + // let mut no_titlebar_applications = NO_TITLEBAR.lock(); + + if let Some(rules) = &mut self.ignore_rules { + populate_rules(rules, &mut ignore_identifiers, &mut regex_identifiers)?; + } + + if let Some(rules) = &mut self.floating_applications { + populate_rules(rules, &mut floating_applications, &mut regex_identifiers)?; + } + + if let Some(rules) = &mut self.manage_rules { + populate_rules(rules, &mut manage_identifiers, &mut regex_identifiers)?; + } + + // `tabbed_applications` and `titleless_applications` work around how macOS exposes native + // tabs and untitled windows. They are accepted so one configuration works on every + // platform, and ignored: a KWin window is always a window. + if self.tabbed_applications.is_some() || self.titleless_applications.is_some() { + tracing::debug!("ignoring tabbed_applications and titleless_applications on KDE"); + } + + // if let Some(rules) = &mut self.object_name_change_applications { + // populate_rules( + // rules, + // &mut object_name_change_identifiers, + // &mut regex_identifiers, + // )?; + // } + // + // if let Some(regexes) = &mut self.object_name_change_title_ignore_list { + // let mut updated = vec![]; + // for r in regexes { + // if let Ok(regex) = Regex::new(r) { + // updated.push(regex); + // } + // } + // + // *object_name_change_title_ignore_list = updated; + // } + // + // if let Some(rules) = &mut self.layered_applications { + // populate_rules(rules, &mut layered_identifiers, &mut regex_identifiers)?; + // } + // + // if let Some(rules) = &mut self.tray_and_multi_window_applications { + // populate_rules( + // rules, + // &mut tray_and_multi_window_identifiers, + // &mut regex_identifiers, + // )?; + // } + // + // if let Some(rules) = &mut self.slow_application_identifiers { + // populate_rules( + // rules, + // &mut slow_application_identifiers, + // &mut regex_identifiers, + // )?; + // } + // + // if let Some(rules) = &mut self.remove_titlebar_applications { + // populate_rules(rules, &mut no_titlebar_applications, &mut regex_identifiers)?; + // } + // + // if let Some(stackbar) = &self.stackbar { + // if let Some(height) = &stackbar.height { + // STACKBAR_TAB_HEIGHT.store(*height, Ordering::SeqCst); + // } + // + // if let Some(label) = &stackbar.label { + // STACKBAR_LABEL.store(*label); + // } + // + // if let Some(mode) = &stackbar.mode { + // STACKBAR_MODE.store(*mode); + // } + // + // #[allow(clippy::assigning_clones)] + // if let Some(tabs) = &stackbar.tabs { + // if let Some(background) = &tabs.background { + // STACKBAR_TAB_BACKGROUND_COLOUR.store((*background).into(), Ordering::SeqCst); + // } + // + // if let Some(colour) = &tabs.focused_text { + // STACKBAR_FOCUSED_TEXT_COLOUR.store((*colour).into(), Ordering::SeqCst); + // } + // + // if let Some(colour) = &tabs.unfocused_text { + // STACKBAR_UNFOCUSED_TEXT_COLOUR.store((*colour).into(), Ordering::SeqCst); + // } + // + // if let Some(width) = &tabs.width { + // STACKBAR_TAB_WIDTH.store(*width, Ordering::SeqCst); + // } + // + // STACKBAR_FONT_SIZE.store(tabs.font_size.unwrap_or(0), Ordering::SeqCst); + // *STACKBAR_FONT_FAMILY.lock() = tabs.font_family.clone(); + // } + // } + // + // if let Some(behaviour) = self.window_handling_behaviour { + // WINDOW_HANDLING_BEHAVIOUR.store(behaviour); + // } + + Ok(()) + } + + /// Parses the text of a `komorebi.json` + /// + /// Comments and trailing commas are allowed, and keys that are not known are ignored. + /// + /// # Errors + /// + /// The text is not JSON, or a value is not what its key takes. + /// + /// # Example + /// + /// ```rust + /// use komorebi::static_config::StaticConfig; + /// + /// let config = StaticConfig::read_raw( + /// r#"{ + /// // a comment, and a trailing comma + /// "resize_delta": 100, + /// "a_key_that_is_not_known": true, + /// }"#, + /// )?; + /// assert_eq!(config.resize_delta, Some(100)); + /// + /// assert!(StaticConfig::read_raw(r#"{ "resize_delta": "wide" }"#).is_err()); + /// + /// # Ok::<(), Box>(()) + /// ``` + pub fn read_raw(raw: &str) -> eyre::Result { + Ok(serde_json::from_str(raw)?) + } + + /// Reads the file at `path`, as [`StaticConfig::read_raw`] reads text + /// + /// # Errors + /// + /// The file cannot be read, or it is not a configuration. + pub fn read(path: &PathBuf) -> eyre::Result { + let content = std::fs::read_to_string(path)?; + serde_json::from_str(&content).map_err(Into::into) + } + + /// Makes the window manager from the file at `path`, and starts watching the file + /// + /// The settings that are not the window manager's own (the default padding, the rules and the + /// others of [`crate`]) are applied first. The window manager listens on `unix_listener`, or + /// when that is `None` on `komorebi.sock` in [`struct@DATA_DIR`], where a socket file that is + /// left over is removed first. It has no monitors yet: [`WindowManager::init`] loads them, and + /// [`StaticConfig::postload`] gives them what the file says about them. + /// + /// A change to the file, or its removal, makes the watcher write a `ReloadStaticConfiguration` + /// message to `komorebi.sock` in [`struct@DATA_DIR`]. + /// + /// # Errors + /// + /// - The file cannot be read or is not a configuration ([`StaticConfig::read`]). + /// - A rule has a regular expression that is not valid. + /// - The socket file that is left over cannot be removed, or the socket cannot be bound. + /// - The file cannot be watched. + #[allow(clippy::too_many_lines)] + pub fn preload( + path: &PathBuf, + incoming: Receiver, + unix_listener: Option, + ) -> eyre::Result { + let mut value = Self::read(path)?; + value.apply_globals()?; + + let listener = match unix_listener { + Some(listener) => listener, + None => { + let socket = DATA_DIR.join("komorebi.sock"); + + match std::fs::remove_file(&socket) { + Ok(()) => {} + Err(error) => match error.kind() { + ErrorKind::NotFound => {} + _ => { + return Err(error.into()); + } + }, + }; + + UnixListener::bind(&socket)? + } + }; + + let mut wm = WindowManager { + monitors: Ring::default(), + monitor_usr_idx_map: HashMap::new(), + incoming_events: incoming, + command_listener: listener, + is_paused: false, + // virtual_desktop_id: current_virtual_desktop(), + work_area_offset: value.global_work_area_offset, + window_management_behaviour: WindowManagementBehaviour { + current_behaviour: value + .window_container_behaviour + .unwrap_or(WindowContainerBehaviour::Create), + float_override: value.float_override.unwrap_or_default(), + floating_layer_override: false, // this value is always automatically calculated + floating_layer_behaviour: value.floating_layer_behaviour.unwrap_or_default(), + toggle_float_placement: value + .toggle_float_placement + .unwrap_or(Placement::CenterAndResize), + floating_layer_placement: value + .floating_layer_placement + .unwrap_or(Placement::Center), + float_override_placement: value.float_override_placement.unwrap_or(Placement::None), + float_rule_placement: value.float_rule_placement.unwrap_or(Placement::None), + }, + cross_monitor_move_behaviour: value + .cross_monitor_move_behaviour + .unwrap_or(MoveBehaviour::Swap), + cross_boundary_behaviour: value + .cross_boundary_behaviour + .unwrap_or(CrossBoundaryBehaviour::Monitor), + monocle_focus_behaviour: value.monocle_focus_behaviour.unwrap_or_default(), + unmanaged_window_operation_behaviour: value + .unmanaged_window_operation_behaviour + .unwrap_or(OperationBehaviour::Op), + resize_delta: value.resize_delta.unwrap_or(DEFAULT_RESIZE_DELTA), + mouse_follows_focus: value + .mouse_follows_focus + .unwrap_or(DEFAULT_MOUSE_FOLLOWS_FOCUS), + hotwatch: Hotwatch::new()?, + minimized_windows: HashMap::new(), + known_window_ids: HashMap::new(), + }; + + let bytes = SocketMessage::ReloadStaticConfiguration(path.clone()).as_bytes()?; + + wm.hotwatch.watch(path, move |event| match event.kind { + // an editor either writes the file in place or replaces it with a new one, which is a + // modification in the first case and a removal in the second + EventKind::Modify(_) | EventKind::Remove(_) => { + let socket = DATA_DIR.join("komorebi.sock"); + let mut stream = + UnixStream::connect(socket).expect("could not connect to komorebi.sock"); + stream + .write_all(&bytes) + .expect("could not write to komorebi.sock"); + } + _ => {} + })?; + + Ok(wm) + } + + /// Gives each monitor of `wm`, once [`WindowManager::init`] has loaded them, and each of their + /// workspaces the configuration the file has for them + /// + /// A monitor takes the configuration at the index `display_index_preferences` gives its serial + /// number id, or else the first configuration that no monitor has taken. It gets as many + /// workspaces as the configuration lists, which are named and laid out as it says. A monitor + /// that has no configuration keeps what it has. + /// + /// # Errors + /// + /// The file cannot be read or is not a configuration ([`StaticConfig::read`]). + pub fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()> { + let mut value = Self::read(path)?; + let mut wm = wm.lock(); + + let configs_with_preference: Vec<_> = + DISPLAY_INDEX_PREFERENCES.read().keys().copied().collect(); + let mut configs_used = Vec::new(); + + let offset = wm.work_area_offset; + for monitor in wm.monitors_mut().iter_mut() { + let preferred_config_idx = { + let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + + display_index_preferences.iter().find_map(|(c_idx, id)| { + if monitor.serial_number_id.eq(id) { + Some(*c_idx) + } else { + None + } + }) + }; + + let idx = preferred_config_idx.or({ + // Monitor without preferred config idx. + // Get index of first config that is not a preferred config of some other monitor + // and that has not been used yet. This might return `None` as well, in that case + // this monitor won't have a config tied to it and will use the default values. + let m_config_count = value + .monitors + .as_ref() + .map(|ms| ms.len()) + .unwrap_or_default(); + (0..m_config_count) + .find(|i| !configs_with_preference.contains(i) && !configs_used.contains(i)) + }); + + if let Some(monitor_config) = value + .monitors + .as_mut() + .and_then(|ms| idx.and_then(|i| ms.get_mut(i))) + { + if let Some(used_config_idx) = idx { + configs_used.push(used_config_idx); + } + + monitor.ensure_workspace_count(monitor_config.workspaces.len()); + monitor.work_area_offset = monitor_config.work_area_offset; + monitor.window_based_work_area_offset = + monitor_config.window_based_work_area_offset; + monitor.window_based_work_area_offset_limit = monitor_config + .window_based_work_area_offset_limit + .unwrap_or(1); + monitor.container_padding = monitor_config.container_padding; + monitor.workspace_padding = monitor_config.workspace_padding; + monitor.floating_layer_behaviour = monitor_config.floating_layer_behaviour; + + monitor.update_workspaces_globals(offset); + for (j, ws) in monitor.workspaces_mut().iter_mut().enumerate() { + if let Some(workspace_config) = monitor_config.workspaces.get_mut(j) { + ws.load_static_config(workspace_config, value.layout_defaults.as_ref())?; + } + } + } + } + + Ok(()) + } + + /// Applies the file at `path` to `wm`, which is running, and tiles it again + /// + /// What [`StaticConfig::preload`] and [`StaticConfig::postload`] do for a window manager that + /// starts, this does for one that has monitors and windows: its settings, then the + /// configuration of each monitor and workspace. A monitor that already has a work area offset + /// keeps it. The windows stay where they are in the workspaces. + /// + /// # Errors + /// + /// - The file cannot be read or is not a configuration ([`StaticConfig::read`]); nothing has + /// changed then. + /// - A rule has a regular expression that is not valid; the settings before it have changed. + pub fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()> { + let mut value = Self::read(path)?; + + value.apply_globals()?; + + let configs_with_preference: Vec<_> = + DISPLAY_INDEX_PREFERENCES.read().keys().copied().collect(); + let mut configs_used = Vec::new(); + + let offset = wm.work_area_offset; + for monitor in wm.monitors_mut().iter_mut() { + let preferred_config_idx = { + let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + + display_index_preferences.iter().find_map(|(c_idx, id)| { + if monitor.serial_number_id.eq(id) { + Some(*c_idx) + } else { + None + } + }) + }; + + let idx = preferred_config_idx.or({ + // Monitor without preferred config idx. + // Get index of first config that is not a preferred config of some other monitor + // and that has not been used yet. This might return `None` as well, in that case + // this monitor won't have a config tied to it and will use the default values. + let m_config_count = value + .monitors + .as_ref() + .map(|ms| ms.len()) + .unwrap_or_default(); + (0..m_config_count) + .find(|i| !configs_with_preference.contains(i) && !configs_used.contains(i)) + }); + if let Some(monitor_config) = value + .monitors + .as_ref() + .and_then(|ms| idx.and_then(|i| ms.get(i))) + { + if let Some(used_config_idx) = idx { + configs_used.push(used_config_idx); + } + + monitor.ensure_workspace_count(monitor_config.workspaces.len()); + if monitor.work_area_offset.is_none() { + monitor.work_area_offset = monitor_config.work_area_offset; + } + monitor.window_based_work_area_offset = + monitor_config.window_based_work_area_offset; + monitor.window_based_work_area_offset_limit = monitor_config + .window_based_work_area_offset_limit + .unwrap_or(1); + monitor.container_padding = monitor_config.container_padding; + monitor.workspace_padding = monitor_config.workspace_padding; + monitor.floating_layer_behaviour = monitor_config.floating_layer_behaviour; + + monitor.update_workspaces_globals(offset); + + for (j, ws) in monitor.workspaces_mut().iter_mut().enumerate() { + if let Some(workspace_config) = monitor_config.workspaces.get(j) { + ws.load_static_config(workspace_config, value.layout_defaults.as_ref())?; + } + } + } + } + + wm.window_management_behaviour.current_behaviour = + value.window_container_behaviour.unwrap_or_default(); + wm.window_management_behaviour.float_override = value.float_override.unwrap_or_default(); + wm.window_management_behaviour.floating_layer_behaviour = + value.floating_layer_behaviour.unwrap_or_default(); + wm.window_management_behaviour.toggle_float_placement = value + .toggle_float_placement + .unwrap_or(Placement::CenterAndResize); + wm.window_management_behaviour.floating_layer_placement = + value.floating_layer_placement.unwrap_or(Placement::Center); + wm.window_management_behaviour.float_override_placement = + value.float_override_placement.unwrap_or(Placement::None); + wm.window_management_behaviour.float_rule_placement = + value.float_rule_placement.unwrap_or(Placement::None); + wm.cross_monitor_move_behaviour = value.cross_monitor_move_behaviour.unwrap_or_default(); + wm.cross_boundary_behaviour = value.cross_boundary_behaviour.unwrap_or_default(); + wm.monocle_focus_behaviour = value.monocle_focus_behaviour.unwrap_or_default(); + wm.unmanaged_window_operation_behaviour = value + .unmanaged_window_operation_behaviour + .unwrap_or_default(); + wm.resize_delta = value.resize_delta.unwrap_or(DEFAULT_RESIZE_DELTA); + wm.mouse_follows_focus = value + .mouse_follows_focus + .unwrap_or(DEFAULT_MOUSE_FOLLOWS_FOCUS); + wm.work_area_offset = value.global_work_area_offset; + + let monitor_count = wm.monitors().len(); + + for i in 0..monitor_count { + wm.update_focused_workspace_by_monitor_idx(i)?; + } + + // to apply the new layouts, padding and offsets + wm.retile_all(true)?; + + Ok(()) + } +} + +fn populate_rules( + matching_rules: &mut Vec, + identifiers: &mut Vec, + regex_identifiers: &mut HashMap, +) -> eyre::Result<()> { + for matching_rule in matching_rules { + if !identifiers.contains(matching_rule) { + match matching_rule { + MatchingRule::Simple(simple) => { + if simple.matching_strategy.is_none() { + simple.matching_strategy = Option::from(MatchingStrategy::Legacy); + } + + if matches!(simple.matching_strategy, Some(MatchingStrategy::Regex)) { + let re = Regex::new(&simple.id)?; + regex_identifiers.insert(simple.id.clone(), re); + } + } + MatchingRule::Composite(composite) => { + for rule in composite { + if rule.matching_strategy.is_none() { + rule.matching_strategy = Option::from(MatchingStrategy::Legacy); + } + + if matches!(rule.matching_strategy, Some(MatchingStrategy::Regex)) { + let re = Regex::new(&rule.id)?; + regex_identifiers.insert(rule.id.clone(), re); + } + } + } + } + identifiers.push(matching_rule.clone()); + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_keys_that_do_nothing_on_kde_are_accepted_and_ignored() { + let config = StaticConfig::read_raw( + r#"{ + "titleless_applications": ["a"], + "tabbed_applications": ["b"], + "a_key_of_another_platform": true, + "monitors": [ + { "window_hiding_position": "BottomRight", "workspaces": [{ "name": "one" }] } + ] + }"#, + ) + .unwrap(); + + assert_eq!(config.titleless_applications, Some(vec![String::from("a")])); + assert_eq!(config.tabbed_applications, Some(vec![String::from("b")])); + assert_eq!( + config.monitors.unwrap()[0].window_hiding_position, + Some(WindowHidingPosition::BottomRight) + ); + } + + #[test] + fn float_rules_is_another_name_for_ignore_rules() { + let rules = r#"[{ "kind": "Exe", "id": "a", "matching_strategy": "Equals" }]"#; + + let named = StaticConfig::read_raw(&format!(r#"{{ "ignore_rules": {rules} }}"#)).unwrap(); + let aliased = StaticConfig::read_raw(&format!(r#"{{ "float_rules": {rules} }}"#)).unwrap(); + + assert_eq!(named, aliased); + assert_eq!(named.ignore_rules.unwrap().len(), 1); + } + + #[test] + fn a_setting_that_is_null_is_a_setting_that_is_left_out() { + let config = + StaticConfig::read_raw(r#"{ "resize_delta": null, "monitors": null }"#).unwrap(); + + assert_eq!(config, StaticConfig::default()); + } + + #[test] + fn a_value_of_the_wrong_kind_is_an_error_that_names_the_key() { + let error = StaticConfig::read_raw(r#"{ "resize_delta": "wide" }"#).unwrap_err(); + + assert!(error.to_string().contains("invalid type"), "{error}"); + } + + #[test] + fn a_file_that_is_not_there_is_an_error() { + let path = PathBuf::from("/nonexistent/komorebi.json"); + + assert!(StaticConfig::read(&path).is_err()); + } +} diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index a0916f0f..fa1230b8 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -40,6 +40,12 @@ //! can be taken to another monitor ([`WindowManager::move_container_to_monitor`], //! [`WindowManager::move_workspace_to_monitor`]). //! +//! A `komorebi.json` ([`StaticConfig`]) can make the window manager +//! ([`StaticConfig::preload`]), and [`WindowManager::reload_static_configuration`] applies one to a +//! window manager that is running. A workspace's layout rules are added and cleared with +//! [`WindowManager::add_workspace_layout_default_rule`] and +//! [`WindowManager::clear_workspace_layout_rules`]. +//! //! [`listen_for_commands`]: crate::process_command::listen_for_commands use crate::DATA_DIR; @@ -67,6 +73,7 @@ use crate::desktop; use crate::lockable_sequence::Lockable; use crate::monitor::Monitor; use crate::ring::Ring; +use crate::static_config::StaticConfig; use crate::window::Window; use crate::window_manager_event::WindowManagerEvent; use crate::window_manager_event_listener; @@ -76,6 +83,7 @@ use color_eyre::eyre; use color_eyre::eyre::OptionExt; use color_eyre::eyre::bail; use crossbeam_channel::Receiver; +use hotwatch::Hotwatch; use std::collections::HashMap; use std::collections::VecDeque; use std::io::ErrorKind; @@ -102,6 +110,9 @@ pub struct WindowManager { pub is_paused: bool, /// How many pixels `ResizeWindowEdge` and `ResizeWindowAxis` resize by pub resize_delta: i32, + /// Watches `komorebi.json`, when the window manager was made from it + /// ([`StaticConfig::preload`]): a change to the file makes the daemon reload it + pub hotwatch: Hotwatch, /// 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, @@ -148,6 +159,7 @@ impl WindowManager { /// /// - The leftover socket file is there but cannot be removed. /// - The socket cannot be bound, for example because its directory does not exist. + /// - The file watcher cannot be made. pub fn new( incoming: Receiver, custom_socket_path: Option, @@ -172,6 +184,7 @@ impl WindowManager { command_listener: listener, is_paused: false, resize_delta: 50, + hotwatch: Hotwatch::new()?, unmanaged_window_operation_behaviour: Default::default(), window_management_behaviour: WindowManagementBehaviour::default(), cross_monitor_move_behaviour: Default::default(), @@ -2800,6 +2813,19 @@ impl WindowManager { Ok(()) } + /// Applies the `komorebi.json` at `pathbuf` to the window manager and tiles it again + /// ([`StaticConfig::reload`]) + /// + /// # Errors + /// + /// The file cannot be read, or is not a configuration, or has a rule with a regular expression + /// that is not valid, or the workspaces cannot be tiled again. + #[tracing::instrument(skip(self))] + pub fn reload_static_configuration(&mut self, pathbuf: &PathBuf) -> eyre::Result<()> { + tracing::info!("reloading static configuration"); + StaticConfig::reload(pathbuf, self) + } + /// 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 @@ -3108,6 +3134,92 @@ impl WindowManager { self.update_focused_workspace(false, false) } + /// Makes the workspace change to `layout` once it has `at_container_count` containers or more + /// ([`Workspace::layout_rules`]), replacing the rule it had for that count, and tiles it again + /// + /// # Errors + /// + /// There is no monitor or no workspace with those indices, or the workspaces cannot be tiled + /// again. + #[tracing::instrument(skip(self))] + pub fn add_workspace_layout_default_rule( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + at_container_count: 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")?; + + let rules: &mut Vec<(usize, Layout)> = &mut workspace.layout_rules; + rules.retain(|pair| pair.0 != at_container_count); + rules.push((at_container_count, Layout::Default(layout))); + rules.sort_by_key(|a| a.0); + + // 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)?) + } + } + + /// Takes the layout rules of the workspace away, which leaves it with the layout it has now, + /// and tiles it again + /// + /// # Errors + /// + /// There is no monitor or no workspace with those indices, or the workspaces cannot be tiled + /// again. + #[tracing::instrument(skip(self))] + pub fn clear_workspace_layout_rules( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + ) -> eyre::Result<()> { + tracing::info!("clearing workspace layout rules"); + + 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")?; + + let rules: &mut Vec<(usize, Layout)> = &mut workspace.layout_rules; + rules.clear(); + + // 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)?) + } + } + /// Makes the workspace padding of the focused workspace `adjustment` pixels larger or smaller, /// and tiles it again /// diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 697cf15f..52682fea 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -4,6 +4,12 @@ //! 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`]). +//! +//! A workspace takes its name, layout, padding, offsets and rules from its entry in +//! `komorebi.json` ([`Workspace::load_static_config`]). Its layout and its offset can change with +//! the number of containers it has ([`Workspace::layout_rules`], +//! [`Workspace::work_area_offset_rules`]), and its layout options come from the workspace or from +//! the defaults of its layout. use crate::backend::backend; use crate::container::Container; @@ -12,12 +18,14 @@ use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::FloatingLayerBehaviour; use crate::core::Layout; +use crate::core::LayoutDefaultEntry; use crate::core::LayoutOptions; use crate::core::OperationDirection; use crate::core::Rect; use crate::core::WindowContainerBehaviour; use crate::lockable_sequence::LockableSequence; use crate::ring::Ring; +use crate::static_config::WorkspaceConfig; use crate::window::Window; use color_eyre::eyre; use color_eyre::eyre::OptionExt; @@ -50,6 +58,17 @@ pub struct Workspace { pub floating_windows: Ring, pub layout: Layout, pub layout_options: Option, + /// The layout the workspace takes when it has this many containers or more, the highest + /// threshold that is reached winning, in ascending order of threshold + pub layout_rules: Vec<(usize, Layout)>, + /// Threshold-based layout options rules (container_count >= threshold -> use these options). + /// Sorted by threshold ascending at load time. + #[serde(default)] + pub layout_options_rules: Vec<(usize, LayoutOptions)>, + /// Cached per-layout defaults from the global `layout_defaults` config setting. + /// Pre-sorted at config load time; used as fallback when workspace has no overrides. + #[serde(skip)] + pub(crate) layout_defaults_cache: HashMap, pub layout_flip: Option, pub workspace_padding: Option, pub container_padding: Option, @@ -58,11 +77,19 @@ pub struct Workspace { pub tile: bool, /// The work area offset of this workspace, which it takes instead of its monitor's pub work_area_offset: Option, + /// The work area offset the workspace takes when it has this many containers or more, the + /// highest threshold that is reached winning, in ascending order of threshold; it comes before + /// [`Workspace::work_area_offset`] + pub work_area_offset_rules: Vec<(usize, Rect)>, /// Whether this workspace takes its monitor's window-based offset (true by default) pub apply_window_based_work_area_offset: bool, /// What a window that opens on this workspace gets, when it is not the window manager's /// default: a container of its own, or a place in the focused container pub window_container_behaviour: Option, + /// What a window that opens on this workspace gets when the workspace has this many containers + /// or more, the highest threshold that is reached winning, in ascending order of threshold; + /// [`Workspace::update`] sets [`Workspace::window_container_behaviour`] from it + pub window_container_behaviour_rules: Option>, /// Whether a window that opens on this workspace floats, when it is not the window manager's /// default pub float_override: Option, @@ -117,15 +144,20 @@ impl Default for Workspace { resize_dimensions: vec![], layout: Layout::Default(DefaultLayout::BSP), work_area_offset: None, + work_area_offset_rules: vec![], latest_layout: vec![], layout_flip: None, layout_options: None, + layout_rules: vec![], + layout_options_rules: vec![], + layout_defaults_cache: HashMap::new(), globals: Default::default(), layer: Default::default(), floating_layer_behaviour: None, tile: true, apply_window_based_work_area_offset: true, window_container_behaviour: None, + window_container_behaviour_rules: None, floating_windows: Default::default(), float_override: None, preselected_container_idx: None, @@ -157,6 +189,43 @@ pub struct WorkspaceGlobals { pub floating_layer_behaviour: Option, } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +/// Cached per-layout default options (pre-sorted rules) derived from the global `layout_defaults`. +pub(crate) struct CachedLayoutDefault { + pub layout_options: Option, + /// Threshold-based rules, sorted by threshold ascending at load time + pub layout_options_rules: Vec<(usize, LayoutOptions)>, +} + +/// Convert an optional HashMap of threshold-based layout options rules into a Vec sorted by +/// threshold ascending. +fn sorted_layout_options_rules( + rules: Option<&HashMap>, +) -> Vec<(usize, LayoutOptions)> { + match rules { + Some(rules) => { + let mut sorted: Vec<(usize, LayoutOptions)> = + rules.iter().map(|(t, o)| (*t, *o)).collect(); + sorted.sort_by_key(|(t, _)| *t); + sorted + } + None => vec![], + } +} + +/// Find the highest matching threshold rule for the given container count. +/// Rules must be sorted by threshold ascending. +fn resolve_threshold_match( + rules: &[(usize, LayoutOptions)], + container_count: usize, +) -> Option { + rules + .iter() + .rev() + .find(|(threshold, _)| container_count >= *threshold) + .map(|(_, opts)| *opts) +} + /// `komorebi_layouts::Rect::percentage_within_horizontal_bounds`, which that crate compiles only /// with its `darwin` feature trait HorizontalBounds { @@ -181,6 +250,152 @@ impl HorizontalBounds for Rect { } impl Workspace { + /// Takes the settings of `config`, which `komorebi.json` has for this workspace: its name, its + /// layout and the rules that change it with the number of containers, its padding and offsets, + /// what a new window gets and whether it floats, whether it tiles, how its layout is flipped + /// and what a new window does on its floating layer + /// + /// `layout_defaults` is what `komorebi.json` says every layout has, for the layout options the + /// workspace sets none of: it is copied here, sorted, so that [`Workspace::update`] has it at + /// hand. + /// + /// A workspace that names no layout and does not say it tiles has tiling off, as the file gave + /// it no layout to tile with, and one that has layout rules tiles. + pub fn load_static_config( + &mut self, + config: &WorkspaceConfig, + layout_defaults: Option<&HashMap>, + ) -> eyre::Result<()> { + self.name = Option::from(config.name.clone()); + + self.container_padding = config.container_padding; + + self.workspace_padding = config.workspace_padding; + + if let Some(layout) = &config.layout { + self.layout = Layout::Default(*layout); + } + + self.tile = !(/* config.custom_layout.is_none() && */config.layout.is_none() && config.tile.is_none() + || config.tile.is_some_and(|tile| !tile)); + + let mut all_layout_rules = vec![]; + if let Some(layout_rules) = &config.layout_rules { + for (count, rule) in layout_rules { + all_layout_rules.push((*count, Layout::Default(*rule))); + } + + all_layout_rules.sort_by_key(|(i, _)| *i); + self.tile = true; + } + + self.layout_rules = all_layout_rules.clone(); + + self.work_area_offset = config.work_area_offset; + + let mut all_work_area_offset_rules = vec![]; + if let Some(work_area_offset_rules) = &config.work_area_offset_rules { + for (count, rect) in work_area_offset_rules { + all_work_area_offset_rules.push((*count, *rect)); + } + + all_work_area_offset_rules.sort_by_key(|(i, _)| *i); + } + + self.work_area_offset_rules = all_work_area_offset_rules; + + self.apply_window_based_work_area_offset = + config.apply_window_based_work_area_offset.unwrap_or(true); + + self.window_container_behaviour = config.window_container_behaviour; + + if let Some(window_container_behaviour_rules) = &config.window_container_behaviour_rules { + if window_container_behaviour_rules.is_empty() { + self.window_container_behaviour_rules = None; + } else { + let mut all_rules = vec![]; + for (count, behaviour) in window_container_behaviour_rules { + all_rules.push((*count, *behaviour)); + } + + all_rules.sort_by_key(|(i, _)| *i); + self.window_container_behaviour_rules = Some(all_rules); + } + } else { + self.window_container_behaviour_rules = None; + } + + self.float_override = config.float_override; + self.layout_flip = config.layout_flip; + self.floating_layer_behaviour = config.floating_layer_behaviour; + // Load layout options directly (LayoutOptions is used in both config and runtime) + self.layout_options = config.layout_options; + + // Load threshold-based layout options rules, sorted by threshold ascending + self.layout_options_rules = + sorted_layout_options_rules(config.layout_options_rules.as_ref()); + + tracing::debug!( + "Workspace '{}' loaded layout_options: {:?}, layout_options_rules: {} entries", + self.name.as_deref().unwrap_or("unnamed"), + self.layout_options, + self.layout_options_rules.len(), + ); + + // Cache per-layout defaults from global layout_defaults, pre-sorting rules + self.layout_defaults_cache = if let Some(defaults) = layout_defaults { + defaults + .iter() + .map(|(layout, entry)| { + ( + *layout, + CachedLayoutDefault { + layout_options: entry.layout_options, + layout_options_rules: sorted_layout_options_rules( + entry.layout_options_rules.as_ref(), + ), + }, + ) + }) + .collect() + } else { + HashMap::new() + }; + + Ok(()) + } + + /// Compute effective layout options using the complete-replacement cascade: + /// + /// If the workspace defines EITHER `layout_options` OR `layout_options_rules`, + /// it completely replaces the global `layout_defaults` for this layout. + /// Global defaults are only used when the workspace has NEITHER setting. + /// + /// Within the effective source (workspace or global): + /// 1. Try threshold match from rules (highest matching threshold wins) + /// 2. If a rule matches -> use it (full replacement of base) + /// 3. Else -> use the base `layout_options` + fn effective_layout_options(&self) -> Option { + let container_count = self.containers().len(); + + let has_workspace_overrides = + self.layout_options.is_some() || !self.layout_options_rules.is_empty(); + + let (effective_base, effective_rules): (Option, &[(usize, LayoutOptions)]) = + if has_workspace_overrides { + (self.layout_options, &self.layout_options_rules) + } else { + match &self.layout { + Layout::Default(dl) => match self.layout_defaults_cache.get(dl) { + Some(entry) => (entry.layout_options, &entry.layout_options_rules), + None => (None, &[]), + }, + } + }; + + resolve_threshold_match(effective_rules, container_count).or(effective_base) + } + #[tracing::instrument(skip(self))] pub fn focus_container(&mut self, idx: usize) { tracing::info!("focusing container"); @@ -1211,6 +1426,15 @@ impl Workspace { /// [`Workspace::apply_window_based_work_area_offset`] is set, and the workspace padding, and /// puts every window of each container on its tile. /// + /// The offset of the highest of [`Workspace::work_area_offset_rules`] that the number of + /// containers reaches comes before the workspace's own, and a monocle container counts as one + /// container for it. The highest of [`Workspace::layout_rules`] that it reaches makes the + /// layout the workspace has from then on, and none that it does not reach changes it. The + /// highest of [`Workspace::window_container_behaviour_rules`] that it reaches is the workspace's + /// [`Workspace::window_container_behaviour`], which is none while it reaches none. The layout + /// options are the workspace's own or, when it has none, those `layout_defaults` gives the + /// layout, as [`Workspace::load_static_config`] copied them. + /// /// Containers that have no windows left are dropped first, except the one a preselection /// reserved, and so is a window that is in more than one container. A tile is clamped to the /// work area, so it cannot bleed onto a neighboring monitor, except in the scrolling layout, @@ -1251,7 +1475,25 @@ impl Workspace { .or(self.globals.workspace_padding) .unwrap_or_default(); let work_area = self.globals.work_area; - let work_area_offset = self.work_area_offset.or(self.globals.work_area_offset); + let mut rules_work_area_offset = None; + + if !self.work_area_offset_rules.is_empty() { + let count = if self.monocle_container.is_some() { + 1 + } else { + self.containers().len() + }; + + for (threshold, work_area_offset_rule) in &self.work_area_offset_rules { + if count >= *threshold { + rules_work_area_offset = Some(*work_area_offset_rule); + } + } + }; + + let work_area_offset = rules_work_area_offset + .or(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; @@ -1290,6 +1532,31 @@ impl Workspace { self.enforce_resize_constraints(); + if !self.layout_rules.is_empty() { + let mut updated_layout = None; + + for (threshold, layout) in &self.layout_rules { + if self.containers().len() >= *threshold { + updated_layout = Option::from(layout.clone()); + } + } + + if let Some(updated_layout) = updated_layout { + self.layout = updated_layout; + } + } + + if let Some(window_container_behaviour_rules) = &self.window_container_behaviour_rules { + let mut updated_behaviour = None; + for (threshold, behaviour) in window_container_behaviour_rules { + if self.containers().len() >= *threshold { + updated_behaviour = Option::from(*behaviour); + } + } + + self.window_container_behaviour = updated_behaviour; + } + if self.tile { // the backend batches the commands this produces and sends them together let result = (|| -> eyre::Result<()> { @@ -1302,6 +1569,15 @@ impl Workspace { // the compositor's own maximize, which is the work area and not the padded one window.maximize()?; } else if !self.containers().is_empty() { + let effective_layout_options = self.effective_layout_options(); + + tracing::debug!( + "Workspace '{}' update() - effective_layout_options: {:?} (base: {:?}, rules: {})", + self.name.as_deref().unwrap_or("unnamed"), + effective_layout_options, + self.layout_options, + self.layout_options_rules.len(), + ); let mut layouts = self.layout.as_boxed_arrangement().calculate( &adjusted_work_area, NonZeroUsize::new(self.containers().len()).ok_or_eyre( @@ -1311,7 +1587,7 @@ impl Workspace { self.layout_flip, &self.resize_dimensions, self.focused_container_idx(), - self.layout_options, + effective_layout_options, &self.latest_layout, ); @@ -2741,4 +3017,75 @@ mod tests { assert_eq!(fake.rect_of(421), Some(tile(0, 0, 1920, 1050))); Ok(()) } + + fn loaded(json: &str) -> eyre::Result { + let config: WorkspaceConfig = serde_json::from_str(json)?; + let mut workspace = Workspace::default(); + workspace.load_static_config(&config, None)?; + Ok(workspace) + } + + #[test] + fn layout_rules_are_kept_in_the_order_of_their_thresholds_and_turn_tiling_on() + -> eyre::Result<()> { + let workspace = loaded( + r#"{ "name": "rules", "tile": false, "layout_rules": { "3": "Rows", "2": "Columns" } }"#, + )?; + + assert_eq!( + workspace.layout_rules, + [ + (2, Layout::Default(DefaultLayout::Columns)), + (3, Layout::Default(DefaultLayout::Rows)) + ] + ); + assert!(workspace.tile); + assert_eq!(workspace.name.as_deref(), Some("rules")); + Ok(()) + } + + #[test] + fn a_workspace_tiles_when_it_has_a_layout_or_is_told_to() -> eyre::Result<()> { + assert!(!loaded(r#"{ "name": "no layout" }"#)?.tile); + assert!(loaded(r#"{ "name": "layout", "layout": "Grid" }"#)?.tile); + assert!(loaded(r#"{ "name": "told to", "tile": true }"#)?.tile); + assert!(!loaded(r#"{ "name": "told not to", "layout": "Grid", "tile": false }"#)?.tile); + + // the layout is the workspace's own when it names one, and what it had when it does not + assert_eq!( + loaded(r#"{ "name": "grid", "layout": "Grid" }"#)?.layout, + Layout::Default(DefaultLayout::Grid) + ); + assert_eq!( + loaded(r#"{ "name": "none" }"#)?.layout, + Layout::Default(DefaultLayout::BSP) + ); + Ok(()) + } + + #[test] + fn the_offset_of_the_highest_rule_the_containers_reach_comes_before_the_workspaces_own() + -> eyre::Result<()> { + let (fake, mut workspace) = workspace_with(&[431, 432]); + workspace.workspace_padding = Some(0); + workspace.container_padding = Some(0); + workspace.work_area_offset = Some(tile(0, 100, 0, 100)); + workspace.work_area_offset_rules = vec![(1, tile(10, 0, 20, 0)), (2, tile(40, 0, 80, 0))]; + + with_backend(fake.clone(), || workspace.update())?; + + // two containers reach both rules, and the second is the higher: 40 on the left, and 80 + // narrower + assert_eq!(fake.rect_of(431), Some(tile(40, 0, 920, 1050))); + assert_eq!(fake.rect_of(432), Some(tile(960, 0, 920, 1050))); + + workspace.remove_container_by_idx(1); + with_backend(fake.clone(), || workspace.update())?; + assert_eq!(fake.rect_of(431), Some(tile(10, 0, 1900, 1050))); + + workspace.work_area_offset_rules.clear(); + with_backend(fake.clone(), || workspace.update())?; + assert_eq!(fake.rect_of(431), Some(tile(0, 100, 1920, 950))); + Ok(()) + } } diff --git a/komorebi/tests/config.rs b/komorebi/tests/config.rs new file mode 100644 index 00000000..0a5c9280 --- /dev/null +++ b/komorebi/tests/config.rs @@ -0,0 +1,979 @@ +//! `komorebi.json` against an in-memory desktop: what the window manager does with the settings, +//! the workspaces, the rules and the paddings the file gives it, how it comes out again as +//! [`StaticConfig`], and what happens when it is loaded a second time. +//! +//! The file is loaded the way the daemon loads it: [`StaticConfig::preload`] makes the window +//! manager, [`WindowManager::init`] reads the desktop, and [`StaticConfig::postload`] gives the +//! monitors their part of the file. The settings the file sets are process-wide, so the tests of +//! this file take turns, and each starts from the paddings of a window manager with no file. +//! +//! The fake's one monitor is 1920x1080 with a work area of 1920x1050. +//! +//! Window ids are in the 38_000s. The rules of the file use names of their own, since the rules +//! of a test are still there in the next one. + +use color_eyre::eyre; +use komorebi::DEFAULT_CONTAINER_PADDING; +use komorebi::DEFAULT_WORKSPACE_PADDING; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::CrossBoundaryBehaviour; +use komorebi::core::DefaultLayout; +use komorebi::core::FloatingLayerBehaviour; +use komorebi::core::Layout; +use komorebi::core::MonocleFocusBehaviour; +use komorebi::core::MoveBehaviour; +use komorebi::core::OperationBehaviour; +use komorebi::core::Placement; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::core::WindowContainerBehaviour; +use komorebi::static_config::StaticConfig; +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 parking_lot::Mutex; +use std::os::unix::net::UnixListener; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::MutexGuard; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; + +/// What the tests of this file take turns with +static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// A desktop and the window manager loaded from a `komorebi.json`, which is kept for as long as the +/// test holds its turn +struct Loaded { + fake: Arc, + wm: Arc>, + _turn: MutexGuard<'static, ()>, +} + +/// A unix socket path, which is limited to ~104 bytes on macOS, and which the temp dir alone can +/// exceed +fn short_path(suffix: &str) -> PathBuf { + static NEXT: AtomicU32 = AtomicU32::new(0); + PathBuf::from(format!( + "/tmp/kmc-{}-{}.{suffix}", + std::process::id(), + NEXT.fetch_add(1, Ordering::SeqCst) + )) +} + +fn write_config(json: &str) -> PathBuf { + let path = short_path("json"); + std::fs::write(&path, json).unwrap(); + path +} + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// Loads `json` over a fake desktop with one monitor, as `main` does +fn load(json: &str) -> Loaded { + let turn = TURN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + DEFAULT_WORKSPACE_PADDING.store(5, Ordering::SeqCst); + DEFAULT_CONTAINER_PADDING.store(5, Ordering::SeqCst); + + let fake = Arc::new(FakeBackend::with_one_monitor()); + let path = write_config(json); + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = short_path("sock"); + let listener = UnixListener::bind(&socket).unwrap(); + + let wm = with_backend(fake.clone(), || -> eyre::Result { + let mut wm = StaticConfig::preload(&path, receiver, Some(listener))?; + wm.init()?; + Ok(wm) + }) + .unwrap(); + let wm = Arc::new(Mutex::new(wm)); + StaticConfig::postload(&path, &wm).unwrap(); + with_backend(fake.clone(), || wm.lock().retile_all(false)).unwrap(); + + let _ = std::fs::remove_file(&socket); + + Loaded { + fake, + wm, + _turn: turn, + } +} + +impl Loaded { + fn open(&self, id: u32, exe: &str, class: &str) { + self.fake + .open_window(id, exe, class, &format!("window {id}")); + with_backend(self.fake.clone(), || { + self.wm.lock().process_event(added(id)) + }) + .unwrap(); + } + + fn open_terminal(&self, id: u32) { + self.open(id, "foot", "foot"); + } + + fn send(&self, message: SocketMessage) { + with_backend(self.fake.clone(), || { + self.wm.lock().process_command(message, Vec::new()) + }) + .unwrap(); + } + + fn rect(&self, id: u32) -> Rect { + self.fake.rect_of(id).unwrap() + } + + /// The windows of each container of the focused workspace + fn containers(&self) -> Vec> { + let wm = self.wm.lock(); + let workspace = wm.focused_workspace().unwrap(); + workspace + .containers() + .iter() + .map(|container| container.windows().iter().map(|window| window.id).collect()) + .collect() + } + + /// The floating windows of the focused workspace + fn floating(&self) -> Vec { + let wm = self.wm.lock(); + let workspace = wm.focused_workspace().unwrap(); + workspace + .floating_windows() + .iter() + .map(|window| window.id) + .collect() + } + + /// The names of the workspaces of the first monitor + fn workspace_names(&self) -> Vec> { + self.wm.lock().monitors()[0] + .workspaces() + .iter() + .map(|workspace| workspace.name.clone()) + .collect() + } +} + +fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect { + Rect { + left, + top, + right, + bottom, + } +} + +#[test] +fn a_configuration_that_says_nothing_leaves_the_defaults() { + let config = load("{}"); + let wm = config.wm.lock(); + + assert_eq!(wm.resize_delta, 50); + assert!(wm.mouse_follows_focus); + assert_eq!(wm.cross_monitor_move_behaviour, MoveBehaviour::Swap); + assert_eq!(wm.cross_boundary_behaviour, CrossBoundaryBehaviour::Monitor); + assert_eq!( + wm.unmanaged_window_operation_behaviour, + OperationBehaviour::Op + ); + assert_eq!(wm.work_area_offset, None); + assert_eq!( + wm.window_management_behaviour.toggle_float_placement, + Placement::CenterAndResize + ); + assert_eq!( + wm.window_management_behaviour.float_rule_placement, + Placement::None + ); + assert_eq!( + wm.window_management_behaviour.current_behaviour, + WindowContainerBehaviour::Create + ); + assert!(!wm.window_management_behaviour.float_override); + assert_eq!( + wm.window_management_behaviour.float_override_placement, + Placement::None + ); + assert_eq!( + wm.window_management_behaviour.floating_layer_behaviour, + FloatingLayerBehaviour::Tile + ); + assert_eq!( + wm.window_management_behaviour.floating_layer_placement, + Placement::Center + ); + assert_eq!(wm.monocle_focus_behaviour, MonocleFocusBehaviour::NoOp); + // the monitor has the workspace it started with, which no one named + assert_eq!(wm.monitors()[0].workspaces().len(), 1); + assert_eq!(wm.monitors()[0].workspaces()[0].name, None); +} + +#[test] +fn the_settings_of_the_configuration_are_the_window_managers() { + let config = load( + r#"{ + "resize_delta": 100, + "mouse_follows_focus": false, + "cross_monitor_move_behaviour": "Insert", + "cross_boundary_behaviour": "Workspace", + "unmanaged_window_operation_behaviour": "NoOp", + "toggle_float_placement": "None", + "float_rule_placement": "Center", + "window_container_behaviour": "Append", + "float_override": true, + "float_override_placement": "CenterAndResize", + "floating_layer_behaviour": "Float", + "floating_layer_placement": "None", + "monocle_focus_behaviour": "Cycle", + "global_work_area_offset": { "left": 10, "top": 20, "right": 30, "bottom": 40 } + }"#, + ); + let wm = config.wm.lock(); + + assert_eq!(wm.resize_delta, 100); + assert!(!wm.mouse_follows_focus); + assert_eq!(wm.cross_monitor_move_behaviour, MoveBehaviour::Insert); + assert_eq!( + wm.cross_boundary_behaviour, + CrossBoundaryBehaviour::Workspace + ); + assert_eq!( + wm.unmanaged_window_operation_behaviour, + OperationBehaviour::NoOp + ); + assert_eq!( + wm.window_management_behaviour.toggle_float_placement, + Placement::None + ); + assert_eq!( + wm.window_management_behaviour.float_rule_placement, + Placement::Center + ); + assert_eq!( + wm.window_management_behaviour.current_behaviour, + WindowContainerBehaviour::Append + ); + assert!(wm.window_management_behaviour.float_override); + assert_eq!( + wm.window_management_behaviour.float_override_placement, + Placement::CenterAndResize + ); + assert_eq!( + wm.window_management_behaviour.floating_layer_behaviour, + FloatingLayerBehaviour::Float + ); + assert_eq!( + wm.window_management_behaviour.floating_layer_placement, + Placement::None + ); + assert_eq!(wm.monocle_focus_behaviour, MonocleFocusBehaviour::Cycle); + assert_eq!(wm.work_area_offset, Some(rect(10, 20, 30, 40))); +} + +#[test] +fn with_append_a_window_that_opens_joins_the_focused_container() { + let config = load(r#"{ "window_container_behaviour": "Append" }"#); + + config.open_terminal(38_091); + config.open_terminal(38_092); + + // the first window has no container to join, the second joins it + let containers = config.containers(); + assert_eq!(containers.len(), 1); + assert_eq!(containers[0].len(), 2); +} + +#[test] +fn the_behaviour_of_a_workspace_comes_before_the_one_for_every_workspace() { + let config = load( + r#"{ + "window_container_behaviour": "Append", + "monitors": [ + { + "workspaces": [ + { "name": "stack", "layout": "BSP" }, + { "name": "tiles", "layout": "BSP", "window_container_behaviour": "Create" } + ] + } + ] + }"#, + ); + + { + let wm = config.wm.lock(); + let workspaces = wm.monitors()[0].workspaces(); + assert_eq!(workspaces[0].window_container_behaviour, None); + assert_eq!( + workspaces[1].window_container_behaviour, + Some(WindowContainerBehaviour::Create) + ); + } + + config.open_terminal(38_101); + config.open_terminal(38_102); + assert_eq!(config.containers().len(), 1, "the first workspace appends"); + + config.send(SocketMessage::FocusWorkspaceNumber(1)); + config.open_terminal(38_103); + config.open_terminal(38_104); + assert_eq!(config.containers().len(), 2, "the second creates"); +} + +#[test] +fn window_container_behaviour_rules_change_the_behaviour_with_the_number_of_containers() { + let config = load( + r#"{ + "monitors": [ + { + "workspaces": [ + { + "name": "chat", + "layout": "BSP", + "window_container_behaviour_rules": { "2": "Append" } + } + ] + } + ] + }"#, + ); + + config.open_terminal(38_111); + config.open_terminal(38_112); + assert_eq!(config.containers().len(), 2, "below the threshold: create"); + + config.open_terminal(38_113); + let containers = config.containers(); + assert_eq!(containers.len(), 2, "from the threshold: append"); + assert_eq!(containers.iter().map(Vec::len).sum::(), 3); +} + +#[test] +fn with_the_float_override_a_window_that_opens_floats_where_the_placement_says() { + let config = load(r#"{ "float_override": true, "float_override_placement": "Center" }"#); + + config.open_terminal(38_121); + + assert_eq!(config.floating(), [38_121]); + assert!(config.containers().is_empty()); + // the window keeps its 800x600 and is centered in the work area, 1920x1050 + let window = config.rect(38_121); + assert_eq!((window.right, window.bottom), (800, 600)); + assert!((2 * window.left + window.right - 1920).abs() <= 1); + assert!((2 * window.top + window.bottom - 1050).abs() <= 1); +} + +#[test] +fn the_float_override_of_a_workspace_comes_before_the_one_for_every_workspace() { + let config = load( + r#"{ + "float_override": true, + "monitors": [ + { "workspaces": [ { "name": "tiles", "layout": "BSP", "float_override": false } ] } + ] + }"#, + ); + + config.open_terminal(38_131); + + assert_eq!(config.containers(), [vec![38_131]]); + assert!(config.floating().is_empty()); +} + +#[test] +fn the_floating_layer_behaviour_floats_what_opens_while_a_workspace_is_on_its_floating_layer() { + let config = + load(r#"{ "floating_layer_behaviour": "Float", "floating_layer_placement": "Center" }"#); + config.open_terminal(38_141); + config.open_terminal(38_142); + assert_eq!( + config.containers().len(), + 2, + "on the tiling layer they tile" + ); + + config.send(SocketMessage::ToggleFloat); + assert_eq!(config.floating(), [38_142]); + config.open_terminal(38_143); + + assert_eq!(config.floating(), [38_142, 38_143]); + assert_eq!(config.containers(), [vec![38_141]]); +} + +#[test] +fn the_floating_layer_behaviour_of_a_workspace_comes_before_a_monitors_and_that_before_the_default() +{ + let config = load( + r#"{ + "floating_layer_behaviour": "Float", + "monitors": [ + { + "floating_layer_behaviour": "Tile", + "workspaces": [ + { "name": "monitors", "layout": "BSP" }, + { "name": "own", "layout": "BSP", "floating_layer_behaviour": "Float" } + ] + } + ] + }"#, + ); + + let wm = config.wm.lock(); + assert_eq!( + wm.window_management_behaviour(0, 0) + .floating_layer_behaviour, + FloatingLayerBehaviour::Tile, + "the monitor's, over the one for every monitor" + ); + assert_eq!( + wm.window_management_behaviour(0, 1) + .floating_layer_behaviour, + FloatingLayerBehaviour::Float, + "the workspace's, over the monitor's" + ); +} + +#[test] +fn the_default_paddings_and_the_offset_decide_where_a_tile_is() { + let config = load( + r#"{ + "default_workspace_padding": 20, + "default_container_padding": 10, + "global_work_area_offset": { "left": 100, "top": 0, "right": 200, "bottom": 0 } + }"#, + ); + + config.open_terminal(38_001); + + // the offset moves the left edge of the work area 100 to the right and makes it 200 narrower; + // the workspace padding and the container padding, 20 and 10, are between it and the window + assert_eq!(config.rect(38_001), rect(130, 30, 1660, 990)); +} + +#[test] +fn a_monitor_and_a_workspace_can_have_a_padding_and_an_offset_of_their_own() { + let config = load( + r#"{ + "default_workspace_padding": 20, + "default_container_padding": 10, + "monitors": [ + { + "container_padding": 0, + "workspace_padding": 0, + "work_area_offset": { "left": 50, "top": 0, "right": 50, "bottom": 0 }, + "workspaces": [ + { "name": "plain", "layout": "BSP" }, + { + "name": "padded", + "layout": "BSP", + "workspace_padding": 30, + "container_padding": 0, + "work_area_offset": { "left": 0, "top": 10, "right": 0, "bottom": 10 } + } + ] + } + ] + }"#, + ); + + // the monitor's offset and no padding at all + config.open_terminal(38_011); + assert_eq!(config.rect(38_011), rect(50, 0, 1870, 1050)); + + // the workspace's own offset and padding come before the monitor's + config.send(SocketMessage::FocusWorkspaceNumber(1)); + config.open_terminal(38_012); + assert_eq!(config.rect(38_012), rect(30, 40, 1860, 980)); +} + +#[test] +fn workspaces_are_named_and_laid_out_as_the_configuration_says() { + let config = load( + r#"{ + "monitors": [ + { + "workspaces": [ + { "name": "web", "layout": "BSP" }, + { "name": "code", "layout": "Columns" }, + { "name": "chat", "layout": "Rows", "tile": true } + ] + } + ] + }"#, + ); + + assert_eq!( + config.workspace_names(), + [ + Some(String::from("web")), + Some(String::from("code")), + Some(String::from("chat")) + ] + ); + let wm = config.wm.lock(); + let layouts: Vec<_> = wm.monitors()[0] + .workspaces() + .iter() + .map(|workspace| workspace.layout.clone()) + .collect(); + assert_eq!( + layouts, + [ + Layout::Default(DefaultLayout::BSP), + Layout::Default(DefaultLayout::Columns), + Layout::Default(DefaultLayout::Rows), + ] + ); +} + +#[test] +fn a_workspace_with_no_layout_does_not_tile() { + let config = load( + r#"{ + "monitors": [ + { + "workspaces": [ + { "name": "free" }, + { "name": "tiled", "tile": true }, + { "name": "off", "layout": "BSP", "tile": false } + ] + } + ] + }"#, + ); + + // the first workspace was given no layout and does not say it tiles: its window is left where + // it opened (800x600 at 100,100) + config.open_terminal(38_021); + assert_eq!(config.rect(38_021), rect(100, 100, 800, 600)); + + config.send(SocketMessage::FocusWorkspaceNumber(1)); + config.open_terminal(38_022); + assert_eq!(config.rect(38_022), rect(10, 10, 1900, 1030)); + + config.send(SocketMessage::FocusWorkspaceNumber(2)); + config.open_terminal(38_023); + assert_eq!(config.rect(38_023), rect(100, 100, 800, 600)); +} + +#[test] +fn layout_rules_change_the_layout_with_the_number_of_windows() { + let config = load( + r#"{ + "default_workspace_padding": 0, + "default_container_padding": 0, + "monitors": [ + { + "workspaces": [ + { + "name": "grow", + "layout": "BSP", + "layout_rules": { "3": "Columns", "2": "Rows" } + } + ] + } + ] + }"#, + ); + + config.open_terminal(38_031); + assert_eq!(config.rect(38_031), rect(0, 0, 1920, 1050)); + + // two windows: rows, one above the other + config.open_terminal(38_032); + assert_eq!(config.rect(38_031), rect(0, 0, 1920, 525)); + assert_eq!(config.rect(38_032), rect(0, 525, 1920, 525)); + + // three: columns, side by side + config.open_terminal(38_033); + assert_eq!(config.rect(38_031), rect(0, 0, 640, 1050)); + assert_eq!(config.rect(38_032), rect(640, 0, 640, 1050)); + assert_eq!(config.rect(38_033), rect(1280, 0, 640, 1050)); + + // the rules are the workspace's, in the order of their thresholds + let wm = config.wm.lock(); + assert_eq!( + wm.monitors()[0].workspaces()[0].layout_rules, + [ + (2, Layout::Default(DefaultLayout::Rows)), + (3, Layout::Default(DefaultLayout::Columns)) + ] + ); +} + +#[test] +fn layout_rules_can_be_added_and_cleared_while_the_daemon_runs() { + let config = load( + r#"{ + "default_workspace_padding": 0, + "default_container_padding": 0, + "monitors": [ { "workspaces": [ { "name": "rules", "layout": "BSP" } ] } ] + }"#, + ); + config.open_terminal(38_041); + config.open_terminal(38_042); + // two windows in BSP: side by side + assert_eq!(config.rect(38_041), rect(0, 0, 960, 1050)); + + config.send(SocketMessage::NamedWorkspaceLayoutRule( + String::from("rules"), + 2, + DefaultLayout::Rows, + )); + assert_eq!(config.rect(38_041), rect(0, 0, 1920, 525)); + + config.send(SocketMessage::ClearNamedWorkspaceLayoutRules(String::from( + "rules", + ))); + // the layout the rule gave stays: clearing takes the rules away and does not undo them + assert!( + config.wm.lock().monitors()[0].workspaces()[0] + .layout_rules + .is_empty() + ); + assert_eq!(config.rect(38_041), rect(0, 0, 1920, 525)); + + config.send(SocketMessage::WorkspaceLayoutRule( + 0, + 0, + 2, + DefaultLayout::Columns, + )); + assert_eq!(config.rect(38_041), rect(0, 0, 960, 1050)); + config.send(SocketMessage::ClearWorkspaceLayoutRules(0, 0)); + assert!( + config.wm.lock().monitors()[0].workspaces()[0] + .layout_rules + .is_empty() + ); +} + +#[test] +fn work_area_offset_rules_change_the_offset_with_the_number_of_windows() { + let config = load( + r#"{ + "default_workspace_padding": 0, + "default_container_padding": 0, + "monitors": [ + { + "workspaces": [ + { + "name": "margins", + "layout": "Columns", + "work_area_offset_rules": { + "2": { "left": 100, "top": 0, "right": 100, "bottom": 0 } + } + } + ] + } + ] + }"#, + ); + + config.open_terminal(38_051); + assert_eq!(config.rect(38_051), rect(0, 0, 1920, 1050)); + + config.open_terminal(38_052); + assert_eq!(config.rect(38_051), rect(100, 0, 910, 1050)); + assert_eq!(config.rect(38_052), rect(1010, 0, 910, 1050)); +} + +#[test] +fn layout_options_of_a_workspace_replace_the_defaults_of_its_layout() { + let config = load( + r#"{ + "default_workspace_padding": 0, + "default_container_padding": 0, + "layout_defaults": { + "Columns": { "layout_options": { "column_ratios": [0.75] } } + }, + "monitors": [ + { + "workspaces": [ + { "name": "default", "layout": "Columns" }, + { + "name": "own", + "layout": "Columns", + "layout_options": { "column_ratios": [0.25] } + }, + { + "name": "rules", + "layout": "Columns", + "layout_options_rules": { + "3": { "column_ratios": [0.5] } + } + }, + { "name": "other", "layout": "Rows" } + ] + } + ] + }"#, + ); + + // layout_defaults: the first of two columns has three quarters of the work area + config.open_terminal(38_061); + config.open_terminal(38_062); + assert_eq!(config.rect(38_061), rect(0, 0, 1440, 1050)); + + // a workspace that has options of its own does not have the defaults, even if it has less + config.send(SocketMessage::FocusWorkspaceNumber(1)); + config.open_terminal(38_063); + config.open_terminal(38_064); + assert_eq!(config.rect(38_063), rect(0, 0, 480, 1050)); + + // a workspace with rules and no options of its own does not have the defaults either: the + // columns are even until there are three + config.send(SocketMessage::FocusWorkspaceNumber(2)); + config.open_terminal(38_065); + config.open_terminal(38_066); + assert_eq!(config.rect(38_065), rect(0, 0, 960, 1050)); + config.open_terminal(38_067); + assert_eq!(config.rect(38_065), rect(0, 0, 960, 1050)); + + // the defaults are of one layout: the workspace with another layout has none + config.send(SocketMessage::FocusWorkspaceNumber(3)); + config.open_terminal(38_068); + config.open_terminal(38_069); + assert_eq!(config.rect(38_068), rect(0, 0, 1920, 525)); +} + +#[test] +fn the_rules_of_the_configuration_decide_which_windows_are_tiled() { + let config = load( + r#"{ + "ignore_rules": [ + { "kind": "Exe", "id": "config-ignored", "matching_strategy": "Equals" } + ], + "floating_applications": [ + { "kind": "Class", "id": "config-floated", "matching_strategy": "Equals" } + ], + "manage_rules": [ + { "kind": "Exe", "id": "config-managed", "matching_strategy": "Equals" }, + { "kind": "Exe", "id": "config-ignored-but", "matching_strategy": "Equals" } + ] + }"#, + ); + + config.open(38_071, "config-ignored", "ignored"); + config.open(38_072, "foot", "config-floated"); + config.open(38_073, "foot", "foot"); + + let wm = config.wm.lock(); + let workspace = &wm.monitors()[0].workspaces()[0]; + // the ignored window is not in the workspace and stays where it opened + assert!(!workspace.contains_window(38_071)); + assert_eq!(config.rect(38_071), rect(100, 100, 800, 600)); + // the window that matches a float rule is the workspace's floating window + assert!( + !workspace + .containers() + .iter() + .any(|c| c.contains_window(38_072)) + ); + assert!(workspace.floating_windows().iter().any(|w| w.id == 38_072)); + // the other is tiled + assert!( + workspace + .containers() + .iter() + .any(|c| c.contains_window(38_073)) + ); +} + +#[test] +fn a_configuration_comes_out_again_as_the_settings_of_the_window_manager() { + let config = load( + r#"{ + "resize_delta": 100, + "cross_monitor_move_behaviour": "Insert", + "window_container_behaviour": "Append", + "float_override": true, + "float_override_placement": "Center", + "floating_layer_behaviour": "Float", + "floating_layer_placement": "None", + "monocle_focus_behaviour": "Cycle", + "default_workspace_padding": 20, + "default_container_padding": 10, + "monitors": [ + { + "floating_layer_behaviour": "Tile", + "workspaces": [ + { "name": "web", "layout": "BSP", "layout_rules": { "2": "Rows" } }, + { + "name": "code", + "layout": "Columns", + "workspace_padding": 0, + "window_container_behaviour": "Create", + "window_container_behaviour_rules": { "3": "Append" }, + "float_override": false, + "floating_layer_behaviour": "Float" + }, + { "name": "chat" } + ] + } + ] + }"#, + ); + + let generated = StaticConfig::from(&*config.wm.lock()); + + assert_eq!(generated.resize_delta, Some(100)); + assert_eq!( + generated.cross_monitor_move_behaviour, + Some(MoveBehaviour::Insert) + ); + assert_eq!(generated.default_workspace_padding, Some(20)); + assert_eq!(generated.default_container_padding, Some(10)); + assert_eq!( + generated.window_container_behaviour, + Some(WindowContainerBehaviour::Append) + ); + assert_eq!(generated.float_override, Some(true)); + assert_eq!(generated.float_override_placement, Some(Placement::Center)); + assert_eq!( + generated.floating_layer_behaviour, + Some(FloatingLayerBehaviour::Float) + ); + assert_eq!(generated.floating_layer_placement, Some(Placement::None)); + assert_eq!( + generated.monocle_focus_behaviour, + Some(MonocleFocusBehaviour::Cycle) + ); + + let monitor = &generated.monitors.as_ref().unwrap()[0]; + assert_eq!( + monitor.floating_layer_behaviour, + Some(FloatingLayerBehaviour::Tile) + ); + let workspaces = &monitor.workspaces; + assert_eq!(workspaces.len(), 3); + assert_eq!(workspaces[0].name, "web"); + assert_eq!(workspaces[0].layout, Some(DefaultLayout::BSP)); + assert_eq!( + workspaces[0].layout_rules, + Some([(2, DefaultLayout::Rows)].into_iter().collect()) + ); + // a padding that is the default is left out, one that is not is kept + assert_eq!(workspaces[0].workspace_padding, None); + assert_eq!(workspaces[1].workspace_padding, Some(0)); + // a workspace that does not tile has no layout in it + assert_eq!(workspaces[2].layout, None); + assert_eq!(workspaces[2].tile, Some(false)); + assert_eq!( + workspaces[1].window_container_behaviour, + Some(WindowContainerBehaviour::Create) + ); + assert_eq!( + workspaces[1].window_container_behaviour_rules, + Some( + [(3, WindowContainerBehaviour::Append)] + .into_iter() + .collect() + ) + ); + assert_eq!(workspaces[1].float_override, Some(false)); + assert_eq!( + workspaces[1].floating_layer_behaviour, + Some(FloatingLayerBehaviour::Float) + ); + assert_eq!(workspaces[0].window_container_behaviour_rules, None); + + // what is generated is a configuration that loads, and says the same again + let json = serde_json::to_string_pretty(&generated).unwrap(); + assert_eq!(StaticConfig::read_raw(&json).unwrap(), generated); +} + +#[test] +fn a_changed_configuration_is_applied_to_the_windows_that_are_there() { + let config = load( + r#"{ + "resize_delta": 100, + "window_container_behaviour": "Append", + "floating_layer_behaviour": "Float", + "monocle_focus_behaviour": "Cycle", + "monitors": [ { "workspaces": [ { "name": "one", "layout": "BSP" } ] } ] + }"#, + ); + config.open_terminal(38_081); + assert_eq!(config.rect(38_081), rect(10, 10, 1900, 1030)); + + let changed = write_config( + r#"{ + "resize_delta": 30, + "default_workspace_padding": 0, + "default_container_padding": 0, + "mouse_follows_focus": false, + "monitors": [ + { "workspaces": [ { "name": "uno", "layout": "BSP" }, { "name": "dos" } ] } + ] + }"#, + ); + config.send(SocketMessage::ReloadStaticConfiguration(changed)); + + { + let wm = config.wm.lock(); + assert_eq!(wm.resize_delta, 30); + assert!(!wm.mouse_follows_focus); + // a key the file leaves out is the default of its setting + assert_eq!( + wm.window_management_behaviour.current_behaviour, + WindowContainerBehaviour::Create + ); + assert_eq!( + wm.window_management_behaviour.floating_layer_behaviour, + FloatingLayerBehaviour::Tile + ); + assert_eq!(wm.monocle_focus_behaviour, MonocleFocusBehaviour::NoOp); + } + assert_eq!( + config.workspace_names(), + [Some(String::from("uno")), Some(String::from("dos"))] + ); + // the window stays in the workspace, and is tiled again with the new padding + assert_eq!(config.rect(38_081), rect(0, 0, 1920, 1050)); +} + +#[test] +fn a_configuration_that_cannot_be_read_changes_nothing() { + let config = load(r#"{ "resize_delta": 100 }"#); + let broken = write_config(r#"{ "resize_delta": "wide" "#); + let missing = short_path("json"); + + for path in [broken, missing] { + let result = with_backend(config.fake.clone(), || { + config + .wm + .lock() + .reload_static_configuration(&path) + .map_err(|error| error.to_string()) + }); + assert!(result.is_err(), "{}", path.display()); + } + + assert_eq!(config.wm.lock().resize_delta, 100); +} + +#[test] +fn a_rule_that_is_not_a_regular_expression_is_an_error_at_load() { + let _turn = TURN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let path = write_config( + r#"{ "ignore_rules": [ { "kind": "Exe", "id": "(unclosed", "matching_strategy": "Regex" } ] }"#, + ); + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = short_path("sock"); + + let result = StaticConfig::preload(&path, receiver, Some(UnixListener::bind(&socket).unwrap())); + + let _ = std::fs::remove_file(&socket); + assert!(result.is_err()); +} diff --git a/komorebi/tests/config_displays.rs b/komorebi/tests/config_displays.rs new file mode 100644 index 00000000..80e97869 --- /dev/null +++ b/komorebi/tests/config_displays.rs @@ -0,0 +1,99 @@ +//! A `komorebi.json` with more than one monitor in it, against an in-memory desktop with three: +//! which monitor takes which configuration. +//! +//! A monitor takes the configuration at the index `display_index_preferences` gives its serial +//! number id, and a monitor without one takes the first configuration that no preference and no +//! monitor has taken. The preferences are process-wide, so this file is one test. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::Rect; +use komorebi::monitor::Monitor; +use komorebi::static_config::StaticConfig; +use parking_lot::Mutex; +use std::os::unix::net::UnixListener; +use std::path::PathBuf; +use std::sync::Arc; + +fn screen(width: i32) -> Rect { + Rect { + left: 0, + top: 0, + right: width, + bottom: 1080, + } +} + +fn workspace_names(monitor: &Monitor) -> Vec> { + monitor + .workspaces() + .iter() + .map(|workspace| workspace.name.clone()) + .collect() +} + +#[test] +fn a_monitor_takes_the_configuration_its_display_index_preference_gives_it() { + let fake = Arc::new(FakeBackend::new()); + fake.add_monitor(1, "Left", screen(1920), screen(1920)); + fake.add_monitor(2, "Right", screen(1920), screen(1920)); + fake.add_monitor(3, "Third", screen(1920), screen(1920)); + + let path = PathBuf::from(format!("/tmp/kmd-{}.json", std::process::id())); + std::fs::write( + &path, + r#"{ + "display_index_preferences": { "1": "Left" }, + "monitors": [ + { "workspaces": [ { "name": "first" } ] }, + { "workspaces": [ { "name": "second" }, { "name": "second too" } ] } + ] + }"#, + ) + .unwrap(); + let socket = PathBuf::from(format!("/tmp/kmd-{}.sock", std::process::id())); + let (_sender, receiver) = crossbeam_channel::bounded(1); + + let wm = with_backend(fake.clone(), || { + let mut wm = + StaticConfig::preload(&path, receiver, Some(UnixListener::bind(&socket).unwrap())) + .unwrap(); + wm.init().unwrap(); + wm + }); + let wm = Arc::new(Mutex::new(wm)); + StaticConfig::postload(&path, &wm).unwrap(); + let _ = std::fs::remove_file(&socket); + let _ = std::fs::remove_file(&path); + + let wm = wm.lock(); + let monitor = |serial: &str| -> &Monitor { + wm.monitors() + .iter() + .find(|monitor| monitor.serial_number_id == serial) + .unwrap() + }; + + // the preference makes "Left" the monitor of the second configuration + assert_eq!( + workspace_names(monitor("Left")), + [ + Some(String::from("second")), + Some(String::from("second too")) + ] + ); + // "Right" has no preference: the first configuration that is no one's preference + assert_eq!( + workspace_names(monitor("Right")), + [Some(String::from("first"))] + ); + // "Third" has none left, and keeps what it began with + assert_eq!(workspace_names(monitor("Third")), [None]); + + // and the state the daemon would generate keeps the preference + let generated = StaticConfig::from(&*wm); + assert_eq!( + generated.display_index_preferences.unwrap().get(&1), + Some(&String::from("Left")) + ); +} diff --git a/komorebi/tests/config_parity.rs b/komorebi/tests/config_parity.rs new file mode 100644 index 00000000..f0405476 --- /dev/null +++ b/komorebi/tests/config_parity.rs @@ -0,0 +1,216 @@ +//! Can one `komorebi.json` be shared across platforms? The fixtures are the file this repository +//! ships (`docs/komorebi.example.json`) and files of komorebi for Windows, which has keys that +//! mean nothing on KDE Plasma. Every fixture must deserialize with [`StaticConfig`], round-trip +//! through its serializer, and lose only the top-level keys that are Windows-only +//! ([`WINDOWS_ONLY`]) or that are read once the feature they configure is there ([`NOT_YET`]). +//! Run with `--nocapture` to see exactly which paths each config has silently dropped. +//! +//! Extra configs (for example your own) can be checked without copying them into the repo: +//! KOMOREBI_PARITY_EXTRA=~/.config/komorebi/komorebi.json cargo test -p komorebi --test config_parity -- --nocapture + +use std::collections::BTreeSet; +use std::path::Path; +use std::path::PathBuf; + +use komorebi::static_config::StaticConfig; +use serde_json::Value; + +/// Top-level fields of upstream (Windows) `StaticConfig` that this one lacks for good, from +/// diffing the two `pub struct StaticConfig` definitions. +const WINDOWS_ONLY: &[&str] = &[ + "bar_configurations", + "border_implementation", + "border_overflow_applications", + "border_style", + "border_z_order", + "invisible_borders", + "layered_applications", + "minimum_window_height", + "minimum_window_width", + "monitor_index_preferences", + "object_name_change_applications", + "object_name_change_title_ignore_list", + "remove_titlebar_applications", + "slow_application_compensation_time", + "slow_application_identifiers", + "stackbar", + "tray_and_multi_window_applications", + "window_handling_behaviour", + "window_hiding_behaviour", +]; + +/// Top-level fields that `StaticConfig` has when the feature they configure is there, and that are +/// ignored until then. Each comment says which commit of the plan brings the feature, and takes +/// the key off this list. +const NOT_YET: &[&str] = &[ + // application specific configuration (39) + "app_specific_configuration_path", + // borders drawn by the compositor (43) + "border", + "border_colours", + "border_offset", + "border_radius", + "border_width", + // animation (45) + "animation", + // transparency (47) + "transparency", + "transparency_alpha", + "transparency_ignore_rules", + // focus follows mouse (48) + "focus_follows_mouse", + // themes (49) + "theme", +]; + +fn repo_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .to_path_buf() +} + +fn fixtures() -> Vec { + let root = repo_root(); + let mut out = vec![root.join("docs/komorebi.example.json")]; + let dir = root.join("spikes/config-parity/fixtures"); + let mut stack = vec![dir]; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { + continue; + }; + for e in rd.flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if p.extension().is_some_and(|x| x == "json") { + out.push(p); + } + } + } + if let Ok(extra) = std::env::var("KOMOREBI_PARITY_EXTRA") { + out.extend( + extra + .split(':') + .filter(|s| !s.is_empty()) + .map(PathBuf::from), + ); + } + out.sort(); + out +} + +/// Every key path present in `input` but absent from `output` (what serde threw away). +fn dropped(input: &Value, output: &Value, path: &str, out: &mut Vec) { + match (input, output) { + (Value::Object(i), Value::Object(o)) => { + for (k, v) in i { + let p = if path.is_empty() { + k.clone() + } else { + format!("{path}.{k}") + }; + match o.get(k) { + Some(ov) => dropped(v, ov, &p, out), + None if v.is_null() => {} + None => out.push(p), + } + } + } + (Value::Array(i), Value::Array(o)) => { + for (n, (iv, ov)) in i.iter().zip(o).enumerate() { + dropped(iv, ov, &format!("{path}[{n}]"), out); + } + } + _ => {} + } +} + +#[test] +fn fixtures_load_round_trip_and_only_lose_windows_only_keys() { + let windows_only: BTreeSet<&str> = WINDOWS_ONLY.iter().chain(NOT_YET).copied().collect(); + let files = fixtures(); + assert!( + files.len() >= 3, + "expected the repo fixtures, found {files:?}" + ); + + for file in files { + let name = file + .strip_prefix(repo_root()) + .unwrap_or(&file) + .display() + .to_string(); + let raw = std::fs::read_to_string(&file).unwrap_or_else(|e| panic!("{name}: {e}")); + let config = + StaticConfig::read_raw(&raw).unwrap_or_else(|e| panic!("{name} failed to load: {e}")); + + // round trip through our own serializer + let again = serde_json::to_string(&config).unwrap(); + let reloaded = + StaticConfig::read_raw(&again).unwrap_or_else(|e| panic!("{name} round trip: {e}")); + assert_eq!(config, reloaded, "{name}: round trip changed the config"); + + // what did serde silently ignore? + let input: Value = serde_json::from_str(&raw).unwrap(); + let mut lost = Vec::new(); + dropped( + &input, + &serde_json::to_value(&config).unwrap(), + "", + &mut lost, + ); + println!("{name}: loaded; {} paths ignored", lost.len()); + for p in &lost { + println!(" ignored: {p}"); + } + + let unexpected: Vec<_> = lost + .iter() + .filter(|p| !p.contains('.') && !p.contains('[')) + .filter(|p| p.as_str() != "$schema" && !windows_only.contains(p.as_str())) + .collect(); + assert!( + unexpected.is_empty(), + "{name}: dropped top-level keys that are neither Windows-only nor not yet read: {unexpected:?}" + ); + } +} + +/// The top-level keys `StaticConfig` reads, from its schema +fn keys_that_are_read() -> BTreeSet { + let schema = serde_json::to_value(schemars::schema_for!(StaticConfig)).unwrap(); + schema["properties"] + .as_object() + .unwrap() + .keys() + .cloned() + .collect() +} + +#[test] +fn the_lists_name_no_key_that_is_read() { + let read = keys_that_are_read(); + + let stale: Vec<_> = WINDOWS_ONLY + .iter() + .chain(NOT_YET) + .filter(|key| read.contains(**key)) + .collect(); + + assert!( + stale.is_empty(), + "StaticConfig reads these keys, which are still listed as ignored: {stale:?}" + ); +} + +#[test] +fn the_example_in_the_docs_is_the_example_file() { + let page = std::fs::read_to_string(repo_root().join("docs/example-configurations.md")).unwrap(); + let file = std::fs::read_to_string(repo_root().join("docs/komorebi.example.json")).unwrap(); + + let start = page.find("```json\n").expect("the page has the example") + "```json\n".len(); + let end = start + page[start..].find("```").expect("the example ends"); + + assert_eq!(page[start..end].trim(), file.trim()); +} diff --git a/komorebi/tests/hot_reload.rs b/komorebi/tests/hot_reload.rs new file mode 100644 index 00000000..b2a3310f --- /dev/null +++ b/komorebi/tests/hot_reload.rs @@ -0,0 +1,183 @@ +//! The daemon and its `komorebi.json`: `komorebi --fake-backend` finds the file in the config home +//! or is given it with `--config`, is configured by it, and applies it again when the file changes. +//! +//! What the daemon has made of the file is read back with `GenerateStaticConfig`. The daemon +//! reloads a file that changed after about two seconds. + +use std::io::Read; +use std::io::Write; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; +use std::path::Path; +use std::path::PathBuf; +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 when the test ends +struct Daemon(Child); + +impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +/// A runtime directory, with a config home and a file in it, that goes when the test ends +struct Home(PathBuf); + +impl Home { + /// /tmp: short enough for a unix socket path on macOS + fn new(name: &str) -> Self { + let dir = PathBuf::from(format!("/tmp/komorebi-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("config")).unwrap(); + Self(dir) + } + + fn config_home(&self) -> PathBuf { + self.0.join("config") + } + + fn socket(&self) -> PathBuf { + self.0.join("komorebi").join("komorebi.sock") + } + + /// Starts the daemon with `args`, the configuration home and the runtime directory of this + /// test + fn start(&self, args: &[&str]) -> Daemon { + Daemon( + Command::new(env!("CARGO_BIN_EXE_komorebi")) + .arg("--fake-backend") + .args(args) + .env("KOMOREBI_CONFIG_HOME", self.config_home()) + .env("XDG_RUNTIME_DIR", &self.0) + // the logs go to the home directory, which may not be writable (the nix sandbox) + .env("HOME", &self.0) + .env_remove("XDG_DATA_HOME") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("komorebi runs"), + ) + } + + /// What the daemon says its settings are + fn settings(&self) -> Option { + let answer = send(&self.socket(), r#"{"type":"GenerateStaticConfig"}"#).ok()?; + serde_json::from_str(&answer).ok() + } + + /// Waits up to 15 seconds for the daemon to say `resize_delta` is what it is given + fn wait_for_resize_delta(&self, resize_delta: i64) -> bool { + eventually(|| { + self.settings() + .is_some_and(|settings| settings["resize_delta"] == resize_delta) + }) + } +} + +impl Drop for Home { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Waits up to fifteen seconds for `done` +fn eventually(mut done: impl FnMut() -> bool) -> bool { + let started = Instant::now(); + while started.elapsed() < Duration::from_secs(15) { + if done() { + return true; + } + std::thread::sleep(Duration::from_millis(50)); + } + 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) +} + +fn workspace_names(settings: &serde_json::Value) -> Vec<&str> { + settings["monitors"][0]["workspaces"] + .as_array() + .unwrap() + .iter() + .map(|workspace| workspace["name"].as_str().unwrap()) + .collect() +} + +#[test] +fn without_a_file_the_daemon_runs_on_its_defaults() { + let home = Home::new("hr-none"); + let _daemon = home.start(&[]); + + assert!(home.wait_for_resize_delta(50), "the default delta"); + let settings = home.settings().unwrap(); + // the workspace the monitor started with, which no one named + assert_eq!(workspace_names(&settings), ["unnamed"]); +} + +#[test] +fn the_daemon_reads_komorebi_json_from_the_config_home() { + let home = Home::new("hr-home"); + std::fs::write( + home.config_home().join("komorebi.json"), + r#"{ "resize_delta": 100, "monitors": [ { "workspaces": [ { "name": "web" }, { "name": "code" } ] } ] }"#, + ) + .unwrap(); + let _daemon = home.start(&[]); + + assert!(home.wait_for_resize_delta(100), "the delta of the file"); + assert_eq!(workspace_names(&home.settings().unwrap()), ["web", "code"]); +} + +#[test] +fn the_daemon_follows_the_file_it_is_given_when_the_file_changes() { + let home = Home::new("hr-follow"); + let file = home.0.join("mine.json"); + std::fs::write(&file, r#"{ "resize_delta": 100 }"#).unwrap(); + // a file in the config home is not the one it was given + std::fs::write( + home.config_home().join("komorebi.json"), + r#"{ "resize_delta": 1 }"#, + ) + .unwrap(); + let _daemon = home.start(&["--config", file.to_str().unwrap()]); + + assert!(home.wait_for_resize_delta(100), "the file --config gave"); + + // written in place + std::fs::write( + &file, + r#"{ "resize_delta": 77, "monitors": [ { "workspaces": [ { "name": "after" } ] } ] }"#, + ) + .unwrap(); + assert!(home.wait_for_resize_delta(77), "the file written in place"); + assert_eq!(workspace_names(&home.settings().unwrap()), ["after"]); + + // replaced by another file, as an editor does that writes a new file and renames it over + let replacement = home.0.join("mine.json.new"); + std::fs::write(&replacement, r#"{ "resize_delta": 55 }"#).unwrap(); + std::fs::rename(&replacement, &file).unwrap(); + assert!(home.wait_for_resize_delta(55), "the file replaced"); + + // a file that does not parse is no reason to lose what the daemon has + std::fs::write(&file, r#"{ "resize_delta": "#).unwrap(); + std::thread::sleep(Duration::from_secs(4)); + assert!( + home.wait_for_resize_delta(55), + "the daemon still answers, unchanged" + ); +} diff --git a/komorebic/Cargo.toml b/komorebic/Cargo.toml index 881baeb7..80ab86df 100644 --- a/komorebic/Cargo.toml +++ b/komorebic/Cargo.toml @@ -12,7 +12,9 @@ clap = { workspace = true } clap_complete = "4" chrono = { workspace = true } color-eyre = { workspace = true } +dirs = { workspace = true } fs-tail = "0.1" +lazy_static = { workspace = true } pastey = { workspace = true } sysinfo = { workspace = true } diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 121385e4..f2096819 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -72,13 +72,19 @@ //! daemon stops, `session-float-rules` shows those rules and `clear-session-float-rules` removes //! them, and `global-state` shows the rules the daemon has. //! +//! `workspace-layout-rule` and `named-workspace-layout-rule` make a workspace change layout once +//! it has so many windows, and `clear-workspace-layout-rules` and +//! `clear-named-workspace-layout-rules` take those rules away. `generate-static-config` prints the +//! settings of the daemon as a `komorebi.json`. +//! //! `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 +//! The others work without the daemon: `start` runs `komorebi` in the background, with the +//! `komorebi.json` it is given with `--config`, `configuration` shows the path of the +//! `komorebi.json` the daemon reads, `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; @@ -94,6 +100,7 @@ use komorebi_client::DefaultLayout; use komorebi_client::MoveBehaviour; use komorebi_client::OperationBehaviour; use komorebi_client::OperationDirection; +use komorebi_client::PathExt; use komorebi_client::Rect; use komorebi_client::Sizing; use komorebi_client::SocketMessage; @@ -101,6 +108,7 @@ use komorebi_client::StateQuery; use komorebi_client::replace_env_in_path; use komorebi_client::send_message; use komorebi_client::send_query; +use lazy_static::lazy_static; use std::fs::File; use std::io::BufRead; use std::io::Write; @@ -108,9 +116,31 @@ use std::num::NonZeroUsize; use std::path::PathBuf; use std::process::Command; use std::process::Stdio; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use std::time::Duration; use sysinfo::ProcessesToUpdate; +lazy_static! { + static ref HAS_CUSTOM_CONFIG_HOME: AtomicBool = AtomicBool::new(false); + static ref HOME_DIR: PathBuf = { + std::env::var("KOMOREBI_CONFIG_HOME").map_or_else( + |_| dirs::home_dir().expect("there is no home directory").join(".config").join("komorebi"), + |home_path| { + let home = home_path.replace_env(); + if home.as_path().is_dir() { + HAS_CUSTOM_CONFIG_HOME.store(true, Ordering::SeqCst); + home + } else { + panic!( + "$KOMOREBI_CONFIG_HOME is set to \"{home_path}\", which is not a valid directory", + ); + } + }, + ) + }; +} + #[derive(Copy, Clone, ValueEnum)] enum BooleanState { Enable, @@ -219,6 +249,7 @@ gen_named_target_subcommand_args! { MoveToNamedWorkspace, SendToNamedWorkspace, FocusNamedWorkspace, + ClearNamedWorkspaceLayoutRules } // Thanks to @danielhenrymantilla for showing me how to use cfg_attr with an optional argument like @@ -389,6 +420,15 @@ gen_application_target_subcommand_args! { // RemoveTitleBar, } +#[derive(Parser)] +pub struct ClearWorkspaceLayoutRules { + /// Monitor index (zero-indexed) + monitor: usize, + + /// Workspace index on the specified monitor (zero-indexed) + workspace: usize, +} + #[derive(Parser)] struct Resize { #[clap(value_enum)] @@ -489,6 +529,33 @@ pub struct MoveToMonitorWorkspace { target_workspace: usize, } +#[derive(Parser)] +pub struct WorkspaceLayoutRule { + /// Monitor index (zero-indexed) + monitor: usize, + + /// Workspace index on the specified monitor (zero-indexed) + workspace: usize, + + /// The number of window containers on-screen required to trigger this layout rule + at_container_count: usize, + + #[clap(value_enum)] + layout: DefaultLayout, +} + +#[derive(Parser)] +pub struct NamedWorkspaceLayoutRule { + /// Target workspace name + workspace: String, + + /// The number of window containers on-screen required to trigger this layout rule + at_container_count: usize, + + #[clap(value_enum)] + layout: DefaultLayout, +} + #[derive(Parser)] struct DisplayIndexPreference { /// Preferred monitor index (zero-indexed) @@ -516,6 +583,10 @@ struct EnsureNamedWorkspaces { #[derive(Parser)] #[allow(clippy::struct_excessive_bools)] struct Start { + /// Path to a static configuration JSON file + #[clap(short, long)] + #[clap(value_parser = replace_env_in_path)] + config: Option, /// Arguments to pass to komorebi, after a `--`: `komorebic start -- --log-level debug` #[clap(last = true)] komorebi_args: Vec, @@ -595,6 +666,9 @@ enum SubCommand { Start(Start), /// Stop the komorebi process Stop(Stop), + /// Show the path to komorebi.json + #[clap(alias = "config")] + Configuration, /// Show the path to komorebi's data directory, which has its socket #[clap(alias = "datadir")] DataDirectory, @@ -865,6 +939,26 @@ enum SubCommand { // #[clap(hide = true)] // #[clap(arg_required_else_help = true)] // NamedWorkspaceCustomLayout(NamedWorkspaceCustomLayout), + /// Add a dynamic layout rule for the specified workspace + #[clap(arg_required_else_help = true)] + WorkspaceLayoutRule(WorkspaceLayoutRule), + /// Add a dynamic layout rule for the specified workspace + #[clap(arg_required_else_help = true)] + NamedWorkspaceLayoutRule(NamedWorkspaceLayoutRule), + // /// Add a dynamic custom layout for the specified workspace + // #[clap(hide = true)] + // #[clap(arg_required_else_help = true)] + // WorkspaceCustomLayoutRule(WorkspaceCustomLayoutRule), + // /// Add a dynamic custom layout for the specified workspace + // #[clap(hide = true)] + // #[clap(arg_required_else_help = true)] + // NamedWorkspaceCustomLayoutRule(NamedWorkspaceCustomLayoutRule), + /// Clear all dynamic layout rules for the specified workspace + #[clap(arg_required_else_help = true)] + ClearWorkspaceLayoutRules(ClearWorkspaceLayoutRules), + /// Clear all dynamic layout rules for the specified workspace + #[clap(arg_required_else_help = true)] + ClearNamedWorkspaceLayoutRules(ClearNamedWorkspaceLayoutRules), /// Enable or disable window tiling for the specified workspace #[clap(arg_required_else_help = true)] WorkspaceTiling(WorkspaceTiling), @@ -935,6 +1029,8 @@ enum SubCommand { MouseFollowsFocus(MouseFollowsFocus), /// Toggle mouse follows focus on all workspaces ToggleMouseFollowsFocus, + /// Generates a static configuration JSON file based on the current window manager state + GenerateStaticConfig, } fn print_query(message: &SocketMessage) { @@ -989,6 +1085,10 @@ fn main() -> eyre::Result<()> { SubCommand::Start(args) => { let mut command = &mut Command::new("komorebi"); + if let Some(config) = &args.config { + command = command.args(["--config", &config.display().to_string()]) + }; + command = command .args(&args.komorebi_args) .stdout(Stdio::null()) @@ -1028,7 +1128,13 @@ fn main() -> eyre::Result<()> { if !running { println!("\nRunning komorebi directly for detailed error output\n"); - if let Ok(output) = Command::new("komorebi").args(&args.komorebi_args).output() { + let mut command = Command::new("komorebi"); + + if let Some(config) = &args.config { + command.args(["--config", &config.display().to_string()]); + } + + if let Ok(output) = command.args(&args.komorebi_args).output() { println!("{}", String::from_utf8(output.stderr)?); } } @@ -1040,6 +1146,13 @@ fn main() -> eyre::Result<()> { send_message(&SocketMessage::Stop)?; } } + SubCommand::Configuration => { + let static_config = HOME_DIR.join("komorebi.json"); + + if static_config.exists() { + println!("{}", static_config.display()); + } + } SubCommand::DataDirectory => { let dir = &*komorebi_client::DATA_DIR; if dir.exists() { @@ -1446,6 +1559,17 @@ fn main() -> eyre::Result<()> { send_message(&SocketMessage::LayoutRatios(args.columns, args.rows))?; } } + SubCommand::ClearWorkspaceLayoutRules(args) => { + send_message(&SocketMessage::ClearWorkspaceLayoutRules( + args.monitor, + args.workspace, + ))?; + } + SubCommand::ClearNamedWorkspaceLayoutRules(args) => { + send_message(&SocketMessage::ClearNamedWorkspaceLayoutRules( + args.workspace, + ))?; + } SubCommand::CrossMonitorMoveBehaviour(args) => { send_message(&SocketMessage::CrossMonitorMoveBehaviour( args.move_behaviour, @@ -1469,6 +1593,21 @@ fn main() -> eyre::Result<()> { args.names, ))?; } + SubCommand::WorkspaceLayoutRule(args) => { + send_message(&SocketMessage::WorkspaceLayoutRule( + args.monitor, + args.workspace, + args.at_container_count, + args.layout, + ))?; + } + SubCommand::NamedWorkspaceLayoutRule(args) => { + send_message(&SocketMessage::NamedWorkspaceLayoutRule( + args.workspace, + args.at_container_count, + args.layout, + ))?; + } SubCommand::MonocleFocusBehaviour(args) => { send_message(&SocketMessage::MonocleFocusBehaviour(args.behaviour))?; } @@ -1489,6 +1628,9 @@ fn main() -> eyre::Result<()> { SubCommand::UnsubscribeSocket(args) => { send_message(&SocketMessage::RemoveSubscriberSocket(args.socket))?; } + SubCommand::GenerateStaticConfig => { + print_query(&SocketMessage::GenerateStaticConfig); + } SubCommand::QuickSaveResize => { send_message(&SocketMessage::QuickSave)?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 8fd26929..7bd1cbf2 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -50,6 +50,16 @@ impl Runtime { .output() .unwrap() } + + /// Runs `komorebic` with `KOMOREBI_CONFIG_HOME` set to `home` + fn komorebic_with_config_home(&self, home: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(args) + .env("XDG_RUNTIME_DIR", &self.0) + .env("KOMOREBI_CONFIG_HOME", home) + .output() + .unwrap() + } } impl Drop for Runtime { @@ -611,6 +621,77 @@ fn the_named_workspace_subcommands_send_the_names_they_are_given() { ); } +#[test] +fn the_layout_rule_subcommands_send_what_they_are_given() { + sends( + &["workspace-layout-rule", "0", "1", "3", "columns"], + r#"{"type":"WorkspaceLayoutRule","content":[0,1,3,"Columns"]}"#, + ); + sends( + &["named-workspace-layout-rule", "mail", "2", "rows"], + r#"{"type":"NamedWorkspaceLayoutRule","content":["mail",2,"Rows"]}"#, + ); + sends( + &["clear-workspace-layout-rules", "0", "1"], + r#"{"type":"ClearWorkspaceLayoutRules","content":[0,1]}"#, + ); + sends( + &["clear-named-workspace-layout-rules", "mail"], + r#"{"type":"ClearNamedWorkspaceLayoutRules","content":"mail"}"#, + ); +} + +#[test] +fn generate_static_config_prints_the_answer_of_the_daemon() { + let runtime = Runtime::new(); + let daemon = runtime.serve(r#"{"resize_delta":50}"#); + + let output = runtime.komorebic(&["generate-static-config"]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!(daemon.join().unwrap(), r#"{"type":"GenerateStaticConfig"}"#); + assert_eq!(stdout(&output), "{\"resize_delta\":50}\n"); +} + +#[test] +fn configuration_shows_the_path_of_komorebi_json_when_there_is_one() { + let runtime = Runtime::new(); + let home = runtime.0.join("config"); + std::fs::create_dir_all(&home).unwrap(); + + // `config` is another name for it + for name in ["configuration", "config"] { + let output = runtime.komorebic_with_config_home(&home, &[name]); + assert!(output.status.success(), "{output:?}"); + assert_eq!(stdout(&output), "", "no file, nothing to show"); + } + + std::fs::write(home.join("komorebi.json"), "{}").unwrap(); + + for name in ["configuration", "config"] { + let output = runtime.komorebic_with_config_home(&home, &[name]); + assert!(output.status.success(), "{output:?}"); + assert_eq!( + stdout(&output), + format!("{}\n", home.join("komorebi.json").display()) + ); + } +} + +#[test] +fn a_config_home_that_is_not_a_directory_is_refused() { + let runtime = Runtime::new(); + let home = runtime.0.join("not-there"); + + let output = runtime.komorebic_with_config_home(&home, &["configuration"]); + + assert!(!output.status.success(), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("which is not a valid directory"), + "{output:?}" + ); +} + #[test] fn the_monitor_subcommands_send_what_they_are_given() { sends( @@ -734,10 +815,13 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "adjust-workspace-padding.md", "cancel-preselect.md", "change-layout.md", + "clear-named-workspace-layout-rules.md", "clear-session-float-rules.md", + "clear-workspace-layout-rules.md", "close-workspace.md", "close.md", "completions.md", + "configuration.md", "container-padding.md", "cross-monitor-move-behaviour.md", "cycle-empty-workspace.md", @@ -770,6 +854,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "focus.md", "focused-workspace-container-padding.md", "focused-workspace-padding.md", + "generate-static-config.md", "global-state.md", "global-work-area-offset.md", "ignore-rule.md", @@ -791,6 +876,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "move-workspace-to-monitor.md", "move.md", "named-workspace-container-padding.md", + "named-workspace-layout-rule.md", "named-workspace-layout.md", "named-workspace-padding.md", "named-workspace-tiling.md", @@ -843,6 +929,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "unstack-all.md", "unstack.md", "unsubscribe-socket.md", + "workspace-layout-rule.md", "workspace-layout.md", "workspace-name.md", "workspace-padding.md", diff --git a/nix/nixos-module.nix b/nix/nixos-module.nix index 69333f15..fbef4626 100644 --- a/nix/nixos-module.nix +++ b/nix/nixos-module.nix @@ -39,21 +39,46 @@ in ''; }; + configFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; + default = null; + example = lib.literalExpression "./komorebi.json"; + description = '' + The `komorebi.json` the daemon is configured by. The unit starts komorebi with it, as + `--config`, in place of the `komorebi.json` the daemon looks for in `~/.config/komorebi` + (`$KOMOREBI_CONFIG_HOME`). The file is in the Nix store, so it does not change under the + daemon: a new file is read when the daemon starts again. `komorebic configuration` still + shows the file of the config home, which the daemon does not read while this is set. With + no `configFile`, the daemon reads the file of the config home, if there is one. + ''; + }; + 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. + `logLevel`, and with `--config` and `configFile` when that is set. 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}"; + services.komorebi.execStart = lib.concatStringsSep " " ( + [ + (lib.getExe' cfg.package "komorebi") + "--log-level" + cfg.logLevel + ] + ++ lib.optionals (cfg.configFile != null) [ + "--config" + "${cfg.configFile}" + ] + ); } (lib.mkIf cfg.enable { diff --git a/nix/tests/nixos-module.nix b/nix/tests/nixos-module.nix index 9544be83..558b40ce 100644 --- a/nix/tests/nixos-module.nix +++ b/nix/tests/nixos-module.nix @@ -72,6 +72,17 @@ let } ); + withConfigFile = eval ( + { pkgs, ... }: + { + imports = [ plasma ]; + services.komorebi = { + enable = true; + configFile = pkgs.writeText "komorebi.json" "{}"; + }; + } + ); + unknownLevel = eval { imports = [ plasma ]; services.komorebi = { @@ -177,6 +188,19 @@ let && lib.elem otherPackage.services.komorebi.package otherPackage.environment.systemPackages; got = (unit otherPackage).serviceConfig.ExecStart; } + { + name = "without a configFile, the unit passes no --config"; + ok = !(lib.hasInfix "--config" enabled.services.komorebi.execStart); + got = enabled.services.komorebi.execStart; + } + { + name = "configFile reaches execStart and the unit as --config, after the log level"; + ok = + withConfigFile.services.komorebi.execStart + == "${withConfigFile.services.komorebi.package}/bin/komorebi --log-level info --config ${withConfigFile.services.komorebi.configFile}" + && (unit withConfigFile).serviceConfig.ExecStart == withConfigFile.services.komorebi.execStart; + got = (unit withConfigFile).serviceConfig.ExecStart; + } { name = "a log level the daemon does not have does not evaluate"; ok = !(evaluates unknownLevel.services.komorebi.logLevel); diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index d7f5fe10..1fa95ec2 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -251,6 +251,12 @@ workspace-layout 0 0 columns workspace-layout 0 0 bsp named-workspace-layout one columns named-workspace-layout one bsp +workspace-layout-rule 0 0 2 rows +workspace-layout-rule 0 0 3 columns +clear-workspace-layout-rules 0 0 +named-workspace-layout-rule one 3 columns +clear-named-workspace-layout-rules one +workspace-layout 0 0 bsp focus-monitor 1 focus-monitor 0 cycle-monitor next @@ -418,6 +424,8 @@ for args in [ "global-state", "monitor-information", "data-directory", + "configuration", + "generate-static-config", "session-float-rules", ]: checks.check(f"komorebic {args}", kde.run(f"komorebic {args}")[0] == 0) diff --git a/nix/tests/vm/suites/module/default.nix b/nix/tests/vm/suites/module/default.nix index 7fae097d..f39658c3 100644 --- a/nix/tests/vm/suites/module/default.nix +++ b/nix/tests/vm/suites/module/default.nix @@ -2,4 +2,24 @@ tier = "fast"; kind = "session"; timeoutMinutes = 10; + # the unit starts the daemon with this file, as `--config`: two named workspaces, and a padding + # that moves the tile of the first window away from the edge of the screen + node = + { pkgs, ... }: + { + services.komorebi.configFile = pkgs.writeText "komorebi.json" '' + { + "default_workspace_padding": 40, + "default_container_padding": 0, + "monitors": [ + { + "workspaces": [ + { "name": "web", "layout": "BSP" }, + { "name": "code", "layout": "Columns" } + ] + } + ] + } + ''; + }; } diff --git a/nix/tests/vm/suites/module/test.py b/nix/tests/vm/suites/module/test.py index 0fa30990..173fc992 100644 --- a/nix/tests/vm/suites/module/test.py +++ b/nix/tests/vm/suites/module/test.py @@ -1,11 +1,14 @@ # 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. +# opened in the session, that it runs with the module's log level, its `configFile` 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. Once the unit is stopped, the daemon is started with a `komorebi.json` of the +# user's, which it follows when the file changes. # The options and the unit the module writes are checked without a machine by `nixos-module-eval` # (`nix/tests/nixos-module.nix`). import json +import shlex from komorebi_vm import Checks, Kde, Rect, daemon @@ -60,7 +63,11 @@ 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"]) +checks.check("... at the module's log level", command[1:3] == ["--log-level", "debug"]) +checks.check( + "... with the module's configFile as its --config", + len(command) == 5 and command[3] == "--config" and command[4].endswith("-komorebi.json"), +) 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( @@ -69,6 +76,21 @@ checks.check( == ["/run/wrappers/bin", "/etc/profiles/per-user/komorebi/bin", "/run/current-system/sw/bin"], ) +print("== 1b. the daemon is configured by the file") +workspaces = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"] +checks.check( + "its workspaces are the ones the file names", + [workspace["name"] for workspace in workspaces] == ["web", "code"], +) +checks.check( + "KWin has a virtual desktop for each of them", + kde.wait_for(lambda: kde.desktops() >= 2, timeout=30), +) +checks.check( + "the settings the daemon says it has are the file's", + json.loads(kde.komorebic("generate-static-config"))["default_workspace_padding"] == 40, +) + print("== 2. a window opened in the session is tiled") width = json.loads(kde.komorebic("monitor-information"))[0]["size"]["right"] @@ -96,6 +118,11 @@ checks.check("the window opens", kde.wait_for(lambda: kde.wid("tiled") != "", ti 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'))}") +want = asked() +checks.check( + "its tile is as far from the edge as the file's workspace padding says", + want is not None and want.x == 40, +) print("== 3. systemd starts a komorebi that was killed again") kde.systemctl("kill", "--signal=SIGKILL", UNIT) @@ -120,4 +147,45 @@ checks.check("komorebic stop stops the unit", kde.wait_for(lambda: not active(), checks.check("... which is not failed", not failed()) checks.check("... and not started again", not kde.wait_for(active, timeout=5)) +print("== 5. a daemon follows the file it is started with, and reloads it when it changes") +MINE = "/home/komorebi/mine.json" + + +def write(text: str) -> None: + kde.sh(f"printf %s {shlex.quote(text)} > {MINE}") + + +def resize_delta() -> int: + return json.loads(kde.komorebic("generate-static-config"))["resize_delta"] + + +def workspace_names() -> list[str]: + elements = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"] + return [workspace["name"] for workspace in elements] + + +write('{ "resize_delta": 100 }') +kde.komorebic("start", "--config", MINE) +checks.check("komorebic start --config starts a daemon that answers", kde.wait_for(answering)) +checks.check("... which has the settings of the file", resize_delta() == 100) + +write( + '{ "resize_delta": 33, "monitors": [ { "workspaces": [' + ' { "name": "one" }, { "name": "two" }, { "name": "three" } ] } ] }' +) +checks.check( + "a change to the file is applied", + kde.wait_for( + lambda: resize_delta() == 33 and workspace_names() == ["one", "two", "three"], + timeout=30, + ), +) +kde.komorebic("focus-workspace", "2") +checks.check( + "... and a workspace it added is one KWin shows", + kde.wait_for(lambda: kde.shown() == 3, timeout=30), +) +kde.komorebic("stop") +checks.check("that daemon stops", kde.wait_for(lambda: not answering(), timeout=30)) + checks.finish() diff --git a/spikes/config-parity/fixtures/windows-kitchen-sink.json b/spikes/config-parity/fixtures/windows-kitchen-sink.json new file mode 100644 index 00000000..a981fc5f --- /dev/null +++ b/spikes/config-parity/fixtures/windows-kitchen-sink.json @@ -0,0 +1,79 @@ +{ + "$schema": "https://raw.githubusercontent.com/LGUG2Z/komorebi/master/schema.json", + "app_specific_configuration_path": "$Env:USERPROFILE/applications.json", + "window_hiding_behaviour": "Cloak", + "cross_monitor_move_behaviour": "Insert", + "default_workspace_padding": 20, + "default_container_padding": 20, + "border": true, + "border_width": 8, + "border_offset": -1, + "border_implementation": "Komorebi", + "border_style": "System", + "border_z_order": "Top", + "focus_follows_mouse": "Windows", + "mouse_follows_focus": true, + "transparency": true, + "transparency_alpha": 200, + "transparency_ignore_rules": [ + { "kind": "Exe", "id": "firefox.exe", "matching_strategy": "Equals" } + ], + "minimum_window_width": 100, + "minimum_window_height": 100, + "invisible_borders": { "left": 7, "top": 0, "right": 14, "bottom": 7 }, + "window_handling_behaviour": "Async", + "slow_application_compensation_time": 20, + "slow_application_identifiers": [ + { "kind": "Exe", "id": "idea64.exe", "matching_strategy": "Equals" } + ], + "object_name_change_applications": [ + { "kind": "Exe", "id": "firefox.exe", "matching_strategy": "Equals" } + ], + "object_name_change_title_ignore_list": ["^.*Chrome.*$"], + "layered_applications": [ + { "kind": "Exe", "id": "steam.exe", "matching_strategy": "Equals" } + ], + "tray_and_multi_window_applications": [ + { "kind": "Exe", "id": "Discord.exe", "matching_strategy": "Equals" } + ], + "border_overflow_applications": [ + { "kind": "Exe", "id": "Notion.exe", "matching_strategy": "Equals" } + ], + "remove_titlebar_applications": [ + { "kind": "Exe", "id": "Spotify.exe", "matching_strategy": "Equals" } + ], + "monitor_index_preferences": { + "0": { "left": 0, "top": 0, "right": 1920, "bottom": 1080 } + }, + "stackbar": { "height": 40, "label": "Process", "mode": "OnStack" }, + "bar_configurations": ["C:/Users/me/komorebi.bar.json"], + "floating_applications": [ + { "kind": "Class", "id": "Notepad", "matching_strategy": "Equals" }, + [ + { "kind": "Exe", "id": "chrome.exe", "matching_strategy": "Equals" }, + { "kind": "Title", "id": "Picture in picture", "matching_strategy": "StartsWith" } + ] + ], + "ignore_rules": [ + { "kind": "Path", "id": "C:/Windows/System32/*", "matching_strategy": "Legacy" } + ], + "monitors": [ + { + "work_area_offset": { "left": 200, "top": 100, "right": 1520, "bottom": 880 }, + "window_based_work_area_offset_limit": 1, + "workspaces": [ + { + "name": "I", + "layout": "BSP", + "container_padding": 10, + "workspace_padding": 10, + "apply_window_based_work_area_offset": true, + "initial_workspace_rules": [ + { "kind": "Exe", "id": "firefox.exe", "matching_strategy": "Equals" } + ] + }, + { "name": "II", "layout": "VerticalStack" } + ] + } + ] +} diff --git a/spikes/config-parity/fixtures/windows-upstream/docs-komorebi.example.json b/spikes/config-parity/fixtures/windows-upstream/docs-komorebi.example.json new file mode 100644 index 00000000..bfb62d59 --- /dev/null +++ b/spikes/config-parity/fixtures/windows-upstream/docs-komorebi.example.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://raw.githubusercontent.com/LGUG2Z/komorebi/v0.1.41/schema.json", + "app_specific_configuration_path": "$Env:USERPROFILE/applications.json", + "window_hiding_behaviour": "Cloak", + "cross_monitor_move_behaviour": "Insert", + "default_workspace_padding": 20, + "default_container_padding": 20, + "border": true, + "border_width": 8, + "border_offset": -1, + "theme": { + "palette": "Base16", + "name": "Ashes", + "unfocused_border": "Base03", + "bar_accent": "Base0D" + }, + "monitors": [ + { + "workspaces": [ + { + "name": "I", + "layout": "BSP" + }, + { + "name": "II", + "layout": "VerticalStack" + }, + { + "name": "III", + "layout": "HorizontalStack" + }, + { + "name": "IV", + "layout": "UltrawideVerticalStack" + }, + { + "name": "V", + "layout": "Rows" + }, + { + "name": "VI", + "layout": "Grid" + }, + { + "name": "VII", + "layout": "RightMainVerticalStack" + } + ] + } + ] +}