diff --git a/Cargo.lock b/Cargo.lock index 42370af2..13f1f0c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2581,6 +2581,7 @@ dependencies = [ "dirs 6.0.0", "fs-tail", "komorebi-client", + "komorebi-hotkeys", "lazy_static", "pastey", "schemars 1.2.3", diff --git a/README.md b/README.md index 086b4231..6d561b15 100644 --- a/README.md +++ b/README.md @@ -86,8 +86,9 @@ without a checkout of the toolchain. unlocked (`monitor_reconciliator`, `reconcile`, `kwin::power`), sends its subscribers a notification of each event, message and change of the monitors it handles (`notify_subscribers`), and is configured by a `komorebi.json` that - it reads and reads again when it changes (`static_config`), and checks it, and - the desktop it runs on, for mistakes without the daemon (`check`). + it reads and reads again when it changes (`static_config`), and checks it, the + key binding file, and the desktop it runs on, for mistakes without the daemon + (`check`). - [`komorebi-client`](komorebi-client): a library that sends messages to the daemon, reads its answers, subscribes to its notifications, and re-exports the types they are made of. @@ -101,7 +102,9 @@ without a checkout of the toolchain. - [`komorebic`](komorebic): the command line. A subcommand that asks something of the daemon is one message on its socket; `quickstart`, `enable-autostart`, `disable-autostart`, `start`, `check`, `configuration`, `log`, `data-directory`, - `completions` and the hidden `docgen` work without the daemon. + `completions` and the hidden `docgen` work without the daemon, and so do + `export-kde-shortcuts` and `hotkeys compile`, which write the bindings of a + key binding file that KDE can run by itself as shortcut files. - [`version`](version): the version string every binary reports. The layouts, which turn a work area and a number of containers into a rectangle @@ -287,9 +290,11 @@ module's `config` option is typed from that schema (`nix/komorebi-options.nix`, `check` reads the file the way the daemon does and says in words what is wrong with it: JSON that does not parse, with the line, a value komorebi does not read, a key that is not a setting (with the nearest one that is), a workspace that is not tiled, and an applications file that is not -there. It also looks at the desktop (a Plasma session on Wayland, KWin 6 on the session bus, the -daemon and its script in KWin, and what starts komorebi at login), unless `--configuration-only` -leaves that out. It exits with status 1 if something is an error. +there. It looks at the key binding file as well (how many bindings it has, the lines that cannot +be read, and whether the shortcut files `hotkeys compile` wrote are the ones it would write now), +and at the desktop (a Plasma session on Wayland, KWin 6 on the session bus, the daemon and its +script in KWin, and what starts komorebi at login), unless `--configuration-only` leaves that out. +It exits with status 1 if something is an error. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event, each message and each @@ -316,6 +321,12 @@ the palette of a picture is made and kept in the cache directory. A monitor or a can have a wallpaper, which the Plasma shell is asked to show when the workspace comes into view, and which gives the borders the colors of its palette. +Key bindings are written in the format of skhd, whkd or sxhkd. `komorebi-hotkeys` +reads such a file into one model and sorts its bindings into static shortcuts, +which KDE runs by itself from a `.desktop` file, and those that need komorebi +to register the keys and decide what each press does. `komorebic hotkeys +compile` writes the static shortcuts. + ## Documentation The user guide starts at [`docs/index.md`](docs/index.md), diff --git a/docs/cli/check.md b/docs/cli/check.md index 6bb81417..25a41b93 100644 --- a/docs/cli/check.md +++ b/docs/cli/check.md @@ -8,7 +8,7 @@ Options: Path to a static configuration JSON file --configuration-only - Look at the configuration only, not at the desktop + Look at the configuration and the key bindings only, not at the desktop -h, --help Print help diff --git a/docs/cli/export-kde-shortcuts.md b/docs/cli/export-kde-shortcuts.md new file mode 100644 index 00000000..2b7dfaa1 --- /dev/null +++ b/docs/cli/export-kde-shortcuts.md @@ -0,0 +1,22 @@ +```text +Turn an skhdrc into KDE global shortcuts (they work over RDP, unlike evdev hotkey daemons) + +Usage: export-kde-shortcuts [OPTIONS] + +Options: + -s, --skhdrc + The skhdrc to translate [default: skhdrc in the komorebi config directory] + + -o, --output + Where to write the shortcut files [default: $XDG_DATA_HOME/kglobalaccel] + + --reload + Activate shortcuts that are new straight away, instead of at the next login + + --dry-run + Show the shortcuts that would be written without writing anything + + -h, --help + Print help + +``` diff --git a/docs/cli/hotkeys-compile.md b/docs/cli/hotkeys-compile.md new file mode 100644 index 00000000..3da42e35 --- /dev/null +++ b/docs/cli/hotkeys-compile.md @@ -0,0 +1,41 @@ +```text +Plan the bindings of a key binding file, and write those that are static shortcuts as KDE shortcut +files + +Usage: compile [OPTIONS] [FILE] + +Arguments: + [FILE] + The key binding file [default: the first of skhdrc, whkdrc and sxhkdrc in the komorebi + config directory] + +Options: + -f, --format + The format of the file [default: from the end of its name: skhdrc, whkdrc or sxhkdrc] + + [possible values: skhd, whkd, sxhkd] + + -m, --mode + Which bindings are static shortcuts: none (engine), every binding a shortcut file can + express (auto), or only those, leaving the others out (static) + + [default: engine] + [possible values: auto, engine, static] + + -o, --output + Where to write the shortcut files [default: $XDG_DATA_HOME/kglobalaccel] + + --strict + Write nothing, and fail, when a diagnostic is a warning or an error: something in the file + is not realized the way its own hotkey daemon realizes it + + --reload + Activate shortcuts that are new straight away, instead of at the next login + + --dry-run + Show the shortcuts that would be written without writing anything + + -h, --help + Print help + +``` diff --git a/docs/cli/hotkeys.md b/docs/cli/hotkeys.md new file mode 100644 index 00000000..391a0816 --- /dev/null +++ b/docs/cli/hotkeys.md @@ -0,0 +1,15 @@ +```text +Turn a key binding file (skhdrc, whkdrc, sxhkdrc) into KDE global shortcuts + +Usage: hotkeys + +Commands: + compile Plan the bindings of a key binding file, and write those that are static shortcuts as KDE + shortcut files + help Print this message or the help of the given subcommand(s) + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index aae46f0f..0d62fd26 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -964,8 +964,9 @@ configuration or a wallpaper that is not there, a wallpaper no theme can be made that is only a name, which is not tiled, and a workspace that appends windows to a container and has placement rules, which are not used then (the workspace's `window_container_behaviour`, or the file's when it has none). [`check_configuration`] also returns the [`Wants`] of the file: whether -it draws borders, which animation style it asks for and whether it has wallpapers. `komorebic` -prints [`Report::render`] and exits with status 1 if [`Report::has_errors`]. +it draws borders, which animation style it asks for and whether it has wallpapers. The key binding +file has a section of its own, which `komorebic` makes (see [Key bindings](#key-bindings)). +`komorebic` prints [`Report::render`] and exits with status 1 if [`Report::has_errors`]. [`check_environment`] looks at the desktop, with D-Bus calls of its own on the session bus (they are in the table of [PLATFORM.md](PLATFORM.md#d-bus)), and `komorebic check --configuration-only` @@ -1633,6 +1634,27 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11). - [`tests/fixtures`](../../komorebi-hotkeys/tests/fixtures): the corpus, `.skhdrc`, `.whkdrc` and `.sxhkdrc`, each case in every format that can express it. +### The front end + +[`komorebic/src/hotkeys.rs`](../../komorebic/src/hotkeys.rs) is the command line over the +crate, and decides nothing about what a file means. `komorebic hotkeys compile` reads a file (by default the +first of `skhdrc`, `whkdrc` and `sxhkdrc` in the komorebi config directory, its format from +the end of its name), plans it in the mode it is given (by default `PlanMode::default()`), +prints the diagnostics of reading and of planning on standard error, and writes the static +shortcuts to `$XDG_DATA_HOME/kglobalaccel` or `--output`, replacing the files it wrote before. +With `--strict`, a diagnostic that is a warning or an error stops it before it writes +anything. `--dry-run` writes nothing and prints what a write would change, and `--reload` +hands each new file to the running KWin, which otherwise reads them at the next login. +`komorebic export-kde-shortcuts` is the same for an skhdrc, in `PlanMode::Static`. + +`komorebic check` has a section for the key bindings, between the configuration and the desktop. +`hotkeys::check` finds the file as `compile` does, reads and plans it in the default mode, and +returns [`Finding`]s: how many bindings the file has and where they go, how many lines cannot be +read and left out (a warning) and how many bindings are not realized as their own daemon would +(a note), each with the first five, and whether the generated files in the shortcut directory are +the ones `kde::diff` says that plan would write. It reads no file the desktop has no part in, so +`--configuration-only` keeps it. + ### What is guaranteed, and by what | Rule | Enforced by | Proof | Escape hatch | @@ -1654,6 +1676,12 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11). | Stopping the engine gives every key back | test, of the effects; carrying them out is the daemon's | `start_activates_the_default_mode_and_stop_gives_everything_back` | none | | The engine does no I/O and reads no clock | convention only | none | none | | The whkd reader reads a whkdrc as whkd does | test, on the files it is given | `every_whkdrc_of_the_corpus_reads_as_whkd_reads_it`, `the_example_of_whkds_readme_reads_as_whkd_reads_it` | none | +| `hotkeys compile` writes the static shortcuts of the plan and nothing else, from a file of any format | test, through the binary | `compile_writes_the_same_shortcut_files_from_each_format`, `compile_in_engine_mode_writes_no_shortcut_and_removes_the_ones_it_wrote` | none | +| `komorebic check` reads the key binding file `hotkeys compile` would read, the way it does | framework path: `check` and `export` share `find` and `diagnostics`, and call the same `parse` and `plan` | `the_first_file_of_the_three_formats_is_the_one_that_is_read`, `the_key_binding_file_of_the_config_home_is_read_and_a_line_it_cannot_read_is_a_warning` | none | +| A line of the key binding file that cannot be read does not fail `komorebic check` | test, through the binary | `the_key_binding_file_of_the_config_home_is_read_and_a_line_it_cannot_read_is_a_warning` | none | +| `komorebic check` says when the shortcut files are not the ones `hotkeys compile` would write | test | `shortcut_files_that_are_not_the_ones_of_the_plan_are_a_warning_that_says_how_many`, `shortcut_files_the_file_does_not_call_for_are_a_warning_until_compile_replaces_them` | none | +| `--strict` writes nothing when a diagnostic is a warning or an error | test, through the binary | `strict_refuses_a_file_with_a_warning_and_writes_nothing` | none | +| KWin runs a static shortcut's command on its key, from the system profile at the start of a session and from the user's directory after `--reload` | VM test | `vm-keys-static` | none | ## Where to look in the code @@ -1686,7 +1714,8 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11). format. - [`komorebi/src/check.rs`](../../komorebi/src/check.rs): the checks of `komorebic check`, with their tests; [`komorebic/tests/check.rs`](../../komorebic/tests/check.rs) runs the command on - configurations and on buses that are not there, and reads what it prints and its exit status; + configurations, on key binding files and on buses that are not there, and reads what it prints + and its exit status; [`nix/tests/vm/suites/check`](../../nix/tests/vm/suites/check/test.py), the desktop check against a real KWin, with the daemon running, with its script gone, with no daemon and with no KWin. - [`komorebi/src/process_event.rs`](../../komorebi/src/process_event.rs): what each event @@ -1836,6 +1865,11 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11). [`sxhkd.rs`](../../komorebi-hotkeys/src/sxhkd.rs); [`plan.rs`](../../komorebi-hotkeys/src/plan.rs) and [`kde.rs`](../../komorebi-hotkeys/src/kde.rs) for the shortcuts, [`engine.rs`](../../komorebi-hotkeys/src/engine.rs) for the engine. +- [`komorebic/src/hotkeys.rs`](../../komorebic/src/hotkeys.rs): `export-kde-shortcuts` and + `hotkeys compile`, and the key bindings section of `komorebic check`; + [`komorebic/tests/hotkeys.rs`](../../komorebic/tests/hotkeys.rs), what they write. +- [`nix/tests/vm/suites/keys-static`](../../nix/tests/vm/suites/keys-static/test.py): static + shortcuts run by a real KWin. - [`komorebi-hotkeys/tests`](../../komorebi-hotkeys/tests): the corpus test and the comparison with `whkd-parser`. - [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 613cbe80..5c0d2f13 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -747,6 +747,9 @@ The cost is the robustness of static shortcuts: the engine works only while komo and a komorebi process that was killed leaves its keys registered and dead until they are released. +Which of the two is the default is still open for a decision. `PlanMode::default()` is the +one place it is set, and `komorebic hotkeys compile` takes its default from there. + ## Why does the engine grab and give back keys, instead of using KDE's own key sequences? Because KDE's do not work for this, as measured on KWin 6.8.1 (2026-10-27). kglobalacceld diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index e02cb8df..454d6f4c 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -292,6 +292,31 @@ At time of writing (2026-10-27), the headless KWin of the VM tests (Plasma 6.8) major version from it. The check does not need the answer: without the line it says that KWin is there and its version could not be read. +## Global shortcuts + +KDE's global shortcut daemon runs inside KWin 6.8: `kwin_wayland` owns `org.kde.kglobalaccel` +on the session bus, and there is no separate `kglobalacceld` process. A KWin started with +`--no-global-shortcuts`, as the headless VM tests start it, has none. + +A static shortcut is a `.desktop` file in a `kglobalaccel` directory with +`X-KDE-GlobalAccel-CommandShortcut=true` and the key in `X-KDE-Shortcuts`; KWin runs its +`Exec` line on the key. `komorebic hotkeys compile` and `komorebic export-kde-shortcuts` +write such files. What follows was measured at time of writing (2026-10-27) on KWin 6.8.1: + +- KWin reads the files when it starts: those in `$XDG_DATA_HOME/kglobalaccel` and those in + `share/kglobalaccel` of the data directories, the system profile of NixOS among them. +- A file added while KWin runs is not read until something calls + `doRegister(["", "_launch", "", ""])` on `/kglobalaccel`, which is what `--reload` + does for each new file (through `busctl`); the shortcut then works at once. A file whose + content changed keeps the old content until the next login, and a removed file stays + registered until then too. +- In `Exec`, `%` starts a field code, so a command's `%` is written `%%`. +- A static shortcut ran its command 165 to 436 ms after the key, 233 ms at the median, over 8 + presses, in a virtual machine under HVF with 4 cores. A key held for 1.5 s ran the command + once. +- The VM test `vm-keys-static` presses the keys of shortcut files in the system profile, and of + one written and handed over in the middle of the session. + ## Files and directories | Path | What | Lifetime | @@ -309,12 +334,18 @@ there and its version could not be read. | `$XDG_CACHE_HOME/komorebi` (`~/.cache/komorebi`) | the palettes made from wallpapers, a file for each picture and variant, `NAME-HASH.base16.VARIANT.json` | never removed by komorebi; made again when the picture's path, size or time of last change differ | | `$XDG_DATA_HOME/komorebi/komorebi.log.YYYY-MM-DD` | the daemon's log, with colors, which `komorebic log` follows | a file a day (the UTC date), never removed by komorebi | | `$XDG_DATA_HOME/komorebi/komorebi_plaintext.log.YYYY-MM-DD` | the same log without colors | as above | +| `$XDG_DATA_HOME/kglobalaccel/komorebi-*.desktop` | the static shortcuts `komorebic hotkeys compile` and `komorebic export-kde-shortcuts` write, each with `X-Komorebi-Generated=true` | replaced at every write: the files with that key are removed, and no other | +| `$KOMOREBI_CONFIG_HOME/{skhdrc,whkdrc,sxhkdrc}` | the key binding file `komorebic hotkeys compile` reads when it is given none (the first that exists), and the skhdrc of `export-kde-shortcuts` | the user's | Without `XDG_RUNTIME_DIR` the bridge and the socket are in `komorebi` in the local data directory instead, with the logs (see [`XDG_DATA_HOME`](#xdg_data_home)). ## What `komorebic check` looks at +The key binding file is the first of `skhdrc`, `whkdrc` and `sxhkdrc` in `$KOMOREBI_CONFIG_HOME`, +and the shortcut files it compares with are the generated `komorebi-*.desktop` files in +`$XDG_DATA_HOME/kglobalaccel`; neither needs a bus. + Apart from the bus, it looks at the files that start komorebi at login, in this order, and says which it found first: `$XDG_CONFIG_HOME/autostart/komorebi.desktop` (the autostart entry), `$XDG_CONFIG_HOME/systemd/user/komorebi.service`, `/etc/systemd/user/komorebi.service` and @@ -348,7 +379,9 @@ either. An address with no bus behind it is the first error under [No KWin](#no- 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. +daemon and `komorebic` panic when they first need the config home, and say so. Environment +variables in it are expanded (`$HOME/komorebi`). `komorebic hotkeys compile` looks in it for the +key binding file it is not given. ### `XDG_RUNTIME_DIR` @@ -374,6 +407,8 @@ The logs are written to `$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if `XDG_DATA_HOME` is not set), which the daemon makes before anything else: a home it cannot write to stops it at once. When `XDG_RUNTIME_DIR` is not set, the bridge and the socket go there too. +`komorebic` writes static shortcuts to `$XDG_DATA_HOME/kglobalaccel` unless it is given +`--output`. ### `KWIN_EFFECTS_FORCE_ANIMATIONS` diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index c5fd5215..8c6667da 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -184,6 +184,25 @@ the run. pointer lands within a pixel of where it is asked. The program itself is [`komorebi_vm/uinput.py`](../../nix/tests/vm/lib/komorebi_vm/uinput.py), whose arithmetic the `vm-lib` check tests. +- `Keys(machine).send("alt-shift-k")` presses a combo on the machine's + keyboard, written as KDE writes it in lower case with `-` between the keys + (`meta` and `super` are the left Super key). + +## Pressing keys + +A key test presses keys with QEMU's `sendkey` (`machine.send_key`), through +`Keys`. The key reaches the guest's kernel as a key of the machine's virtual +keyboard, and KWin sees it as it sees a person's: a global shortcut fires on +it, and any other key goes to the focused window. QEMU holds the keys for 100 +ms, less than the delay before a key repeats. Phase 0 drove keys from a uinput +device inside the guest instead, as the pointer is driven now; `sendkey` needs +no helper program for keys, and on x86_64 under KVM `vm-keys-static` passed with +it on its first run (2026-10-27). + +Global shortcuts need the session node: the headless KWin runs with +`--no-global-shortcuts`, so it has no `org.kde.kglobalaccel`. A static +shortcut written into the system profile by the suite's `node` (as +`vm-keys-static` does) is found when the session starts. Poll for what the test needs with `wait_for`. A fixed sleep is too long on KVM and too short on TCG. diff --git a/docs/index.md b/docs/index.md index 6835610f..ba795009 100644 --- a/docs/index.md +++ b/docs/index.md @@ -76,7 +76,8 @@ changes size, is unplugged or is plugged in, and [Sleeping and locking](usage/sleeping-and-locking.md) what it does when the machine wakes up and the screen is unlocked. [Checking the setup](usage/checking-the-setup.md) explains how `komorebic check` finds the -mistakes in a configuration, and what is missing from the desktop, before the daemon does. +mistakes in a configuration and a key binding file, and what is missing from the desktop, before +the daemon does. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/checking-the-setup.md b/docs/usage/checking-the-setup.md index fd8f540f..cc81fa5b 100644 --- a/docs/usage/checking-the-setup.md +++ b/docs/usage/checking-the-setup.md @@ -1,8 +1,8 @@ # Checking the setup -[`komorebic check`](../cli/check.md) reads your configuration the way the daemon does, looks at the -desktop komorebi has to run on, and says in words what is wrong. It does not need the daemon to be -running, and it changes nothing. +[`komorebic check`](../cli/check.md) reads your configuration the way the daemon does, reads your +key binding file, looks at the desktop komorebi has to run on, and says in words what is wrong. It +does not need the daemon to be running, and it changes nothing. ```sh komorebic check @@ -12,10 +12,10 @@ komorebic check --configuration-only It reads `komorebi.json` in the [config home](configuration.md#where-the-file-is), or the file `--komorebi-config` names (`-k`; environment variables in the path are replaced). It prints a -section of findings for the configuration and one for the desktop, then the number of errors and -warnings, and exits with status 1 if and only if a finding is an error, so a script can run it -before it starts the daemon. `--configuration-only` leaves the desktop out, for a machine that is -not the one komorebi will run on: a build that checks a file, say. +section of findings for the configuration, one for the key bindings and one for the desktop, then +the number of errors and warnings, and exits with status 1 if and only if a finding is an error, so +a script can run it before it starts the daemon. `--configuration-only` leaves the desktop out, for +a machine that is not the one komorebi will run on: a build that checks a file, say. ## What a finding says @@ -82,9 +82,32 @@ The first section says where komorebi looks, and then what it finds in the file: The check takes the keys it knows from the schema of the types the daemon reads the file with, at every level, so it knows every setting komorebi reads. +## The key bindings + +The second section is about the key binding file `komorebic hotkeys compile` would read: the first +of `skhdrc`, `whkdrc` and `sxhkdrc` in the config home. It reads the file as +[`hotkeys compile`](../cli/hotkeys-compile.md) does, plans it in the mode `hotkeys compile` uses +when it is not given one, and looks at: + +- **No file.** A `note`, with where key bindings come from: a key binding file made into shortcuts + by `komorebic hotkeys compile`, or shortcuts set up in System Settings. +- **The bindings.** `ok` with the file, how many bindings it has, and how many of them become + shortcut files and how many are for komorebi's engine. +- **Lines that cannot be read.** A `warning` that says how many are left out, and shows the first + five with their line numbers. The rest of the file is read all the same. +- **Bindings that are not realized as the file's own hotkey daemon would.** A `note` with how many, + and the first five: a left Alt that is the same as the right one, say, since KDE does not tell + them apart. +- **Shortcut files that are not the plan's.** A `warning` when the generated files in + `$XDG_DATA_HOME/kglobalaccel` are not the ones `komorebic hotkeys compile` would write for the + file now: how many to add, to change and to remove. The hint is the command that makes them + match. Otherwise `ok`. + +`--configuration-only` leaves this section in: it looks at files, not at the desktop. + ## The desktop -The second section is about the desktop `komorebic check` runs in, which has to be the session +The third section is about the desktop `komorebic check` runs in, which has to be the session komorebi runs in: it asks the session bus of the environment it is run from, so run it in a terminal of the Plasma session, not over ssh. It looks, in this order, at: diff --git a/komorebic/Cargo.toml b/komorebic/Cargo.toml index 324fb84d..e86aa410 100644 --- a/komorebic/Cargo.toml +++ b/komorebic/Cargo.toml @@ -6,6 +6,7 @@ edition = "2024" [dependencies] komorebi-client = { path = "../komorebi-client", default-features = false } +komorebi-hotkeys = { path = "../komorebi-hotkeys" } version = { path = "../version" } clap = { workspace = true } diff --git a/komorebic/src/hotkeys.rs b/komorebic/src/hotkeys.rs new file mode 100644 index 00000000..b49d4b3d --- /dev/null +++ b/komorebic/src/hotkeys.rs @@ -0,0 +1,707 @@ +//! The key binding subcommands: `export-kde-shortcuts` and `hotkeys`. +//! +//! Both are front ends over [`komorebi_hotkeys`]: they read a key binding file +//! ([`komorebi_hotkeys::parse`]), sort its bindings into KDE shortcut files and the engine's +//! ([`komorebi_hotkeys::plan::plan`]), print what the crate has to say about the file, and write the +//! shortcut files ([`komorebi_hotkeys::kde::write`]). `export-kde-shortcuts` does this for an +//! skhdrc, as static shortcuts only; `hotkeys compile` for a file of any of the three formats, in +//! any [`PlanMode`]. + +use crate::HOME_DIR; +use clap::Parser; +use clap::Subcommand; +use clap::ValueEnum; +use color_eyre::eyre; +use komorebi_client::check::Finding; +use komorebi_hotkeys::Diagnostic; +use komorebi_hotkeys::Format; +use komorebi_hotkeys::ParseOptions; +use komorebi_hotkeys::Parsed; +use komorebi_hotkeys::Severity; +use komorebi_hotkeys::kde; +use komorebi_hotkeys::plan::Plan; +use komorebi_hotkeys::plan::PlanMode; +use komorebi_hotkeys::plan::PlanOptions; +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use std::process::Stdio; + +#[derive(Parser)] +pub struct ExportKdeShortcuts { + /// The skhdrc to translate [default: skhdrc in the komorebi config directory] + #[clap(short, long)] + skhdrc: Option, + /// Where to write the shortcut files [default: $XDG_DATA_HOME/kglobalaccel] + #[clap(short, long)] + output: Option, + /// Activate shortcuts that are new straight away, instead of at the next login + #[clap(long)] + reload: bool, + /// Show the shortcuts that would be written without writing anything + #[clap(long)] + dry_run: bool, +} + +#[derive(Parser)] +pub struct Hotkeys { + #[clap(subcommand)] + command: HotkeysCommand, +} + +#[derive(Subcommand)] +enum HotkeysCommand { + /// Plan the bindings of a key binding file, and write those that are static shortcuts as KDE + /// shortcut files + Compile(Compile), +} + +#[derive(Parser)] +struct Compile { + /// The key binding file [default: the first of skhdrc, whkdrc and sxhkdrc in the komorebi + /// config directory] + file: Option, + /// The format of the file [default: from the end of its name: skhdrc, whkdrc or sxhkdrc] + #[clap(short, long, value_enum)] + format: Option, + /// Which bindings are static shortcuts: none (engine), every binding a shortcut file can + /// express (auto), or only those, leaving the others out (static) + #[clap(short, long, value_enum, default_value_t = PlanMode::default().into())] + mode: KeyPlanMode, + /// Where to write the shortcut files [default: $XDG_DATA_HOME/kglobalaccel] + #[clap(short, long)] + output: Option, + /// Write nothing, and fail, when a diagnostic is a warning or an error: something in the + /// file is not realized the way its own hotkey daemon realizes it + #[clap(long)] + strict: bool, + /// Activate shortcuts that are new straight away, instead of at the next login + #[clap(long)] + reload: bool, + /// Show the shortcuts that would be written without writing anything + #[clap(long)] + dry_run: bool, +} + +/// [`Format`], for the command line +#[derive(Clone, Copy, ValueEnum)] +enum KeyFormat { + Skhd, + Whkd, + Sxhkd, +} + +impl From for Format { + fn from(format: KeyFormat) -> Self { + match format { + KeyFormat::Skhd => Format::Skhd, + KeyFormat::Whkd => Format::Whkd, + KeyFormat::Sxhkd => Format::Sxhkd, + } + } +} + +/// [`PlanMode`], for the command line +#[derive(Clone, Copy, ValueEnum)] +enum KeyPlanMode { + Auto, + Engine, + Static, +} + +impl From for KeyPlanMode { + fn from(mode: PlanMode) -> Self { + match mode { + PlanMode::Auto => KeyPlanMode::Auto, + PlanMode::Engine => KeyPlanMode::Engine, + PlanMode::Static => KeyPlanMode::Static, + } + } +} + +impl From for PlanMode { + fn from(mode: KeyPlanMode) -> Self { + match mode { + KeyPlanMode::Auto => PlanMode::Auto, + KeyPlanMode::Engine => PlanMode::Engine, + KeyPlanMode::Static => PlanMode::Static, + } + } +} + +/// What to export, and how +struct Export { + file: PathBuf, + format: Format, + mode: PlanMode, + output: Option, + strict: bool, + reload: bool, + dry_run: bool, +} + +/// `komorebic export-kde-shortcuts`: the bindings of an skhdrc that can be KDE shortcut files +pub fn export_kde_shortcuts(args: ExportKdeShortcuts) -> eyre::Result<()> { + export(Export { + file: args.skhdrc.unwrap_or_else(|| HOME_DIR.join("skhdrc")), + format: Format::Skhd, + mode: PlanMode::Static, + output: args.output, + strict: false, + reload: args.reload, + dry_run: args.dry_run, + }) +} + +/// `komorebic hotkeys` +pub fn hotkeys(args: Hotkeys) -> eyre::Result<()> { + match args.command { + HotkeysCommand::Compile(args) => { + let file = match args.file { + Some(file) => file, + None => find_file(&HOME_DIR)?, + }; + let format = match args.format { + Some(format) => format.into(), + None => format_of(&file)?, + }; + export(Export { + file, + format, + mode: args.mode.into(), + output: args.output, + strict: args.strict, + reload: args.reload, + dry_run: args.dry_run, + }) + } + } +} + +const FORMATS: [Format; 3] = [Format::Skhd, Format::Whkd, Format::Sxhkd]; + +/// The first key binding file of the three formats in `dir`, and its format +fn find(dir: &Path) -> Option<(PathBuf, Format)> { + FORMATS + .into_iter() + .map(|format| (dir.join(format.file_name()), format)) + .find(|(path, _)| path.is_file()) +} + +/// The first key binding file of the three formats in `dir` +fn find_file(dir: &Path) -> eyre::Result { + find(dir).map(|(path, _)| path).ok_or_else(|| { + eyre::Report::msg(format!( + "there is no skhdrc, whkdrc or sxhkdrc in {}: name the file to read", + dir.display() + )) + }) +} + +/// The format a file's name ends with +fn format_of(file: &Path) -> eyre::Result { + let name = file + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); + FORMATS + .into_iter() + .find(|format| name.ends_with(format.file_name())) + .ok_or_else(|| { + eyre::Report::msg(format!( + "{} does not end with skhdrc, whkdrc or sxhkdrc: give its --format", + file.display() + )) + }) +} + +/// Where the shortcut files go when no directory is given: `kglobalaccel` in the data directory +fn shortcut_dir() -> Option { + dirs::data_dir().map(|dir| dir.join("kglobalaccel")) +} + +/// What reading and planning a file have to say about it, in the order of the file +fn diagnostics<'a>(parsed: &'a Parsed, plan: &'a Plan) -> Vec<&'a Diagnostic> { + let mut diagnostics: Vec<&Diagnostic> = + parsed.diagnostics.iter().chain(&plan.diagnostics).collect(); + diagnostics.sort_by_key(|diagnostic| diagnostic.span.start); + diagnostics +} + +fn export(export: Export) -> eyre::Result<()> { + let file = &export.file; + let text = std::fs::read_to_string(file).map_err(|error| { + eyre::Report::msg(format!("could not read {}: {error}", file.display())) + })?; + let parsed = komorebi_hotkeys::parse(export.format, &text, &ParseOptions::default()); + let plan = komorebi_hotkeys::plan::plan(&parsed.keymap, &PlanOptions { mode: export.mode }); + + let diagnostics = diagnostics(&parsed, &plan); + for diagnostic in &diagnostics { + eprintln!("{}: {diagnostic}", file.display()); + } + if export.strict + && diagnostics + .iter() + .any(|diagnostic| diagnostic.severity >= Severity::Warning) + { + eyre::bail!( + "{} is not realized as it says (the warnings and errors above), and --strict is set", + file.display() + ); + } + + for shortcut in &plan.static_files { + println!("{:<24} {}", shortcut.combo.to_string(), shortcut.command); + } + let engine: usize = plan.engine.modes.iter().map(|m| m.bindings.len()).sum(); + let files = kde::desktop_files(&plan.static_files); + let output = export + .output + .unwrap_or_else(|| shortcut_dir().expect("there is no data directory")); + + if export.dry_run { + let diff = kde::diff(&output, &files)?; + println!( + "{} shortcuts would be written to {} ({} new, {} changed, {} removed), {} bindings need the engine", + files.len(), + output.display(), + diff.added.len(), + diff.changed.len(), + diff.removed.len(), + engine + ); + return Ok(()); + } + + let written = kde::write(&output, &files)?; + println!( + "wrote {} shortcuts to {} ({} new, {} changed, {} removed), {} bindings need the engine", + files.len(), + output.display(), + written.added.len(), + written.changed.len(), + written.removed.len(), + engine + ); + + // KWin 6.8 runs the global shortcut daemon itself and reads these files when it starts. A + // shortcut it has not met can be handed over now; one it already runs keeps what it loaded + // until the next login. + if export.reload { + for name in written.added.iter().chain(&written.unchanged) { + let registered = Command::new("busctl") + .args([ + "--user", + "call", + "org.kde.kglobalaccel", + "/kglobalaccel", + "org.kde.KGlobalAccel", + "doRegister", + "as", + "4", + name, + "_launch", + "", + "", + ]) + .stdout(Stdio::null()) + .status() + .is_ok_and(|status| status.success()); + if !registered { + eyre::bail!("could not register {name} with KWin: is this a Plasma session?"); + } + } + println!( + "{} shortcuts are active now", + written.added.len() + written.unchanged.len() + ); + if !(written.changed.is_empty() && written.removed.is_empty()) { + println!( + "{} changed and {} removed ones take effect at your next login", + written.changed.len(), + written.removed.len() + ); + } + } else if !files.is_empty() || !written.removed.is_empty() { + println!("they take effect at your next login; --reload activates new ones straight away"); + } + + Ok(()) +} + +/// `n` and the noun, in the singular when there is one +fn count(n: usize, singular: &str, plural: &str) -> String { + format!("{n} {}", if n == 1 { singular } else { plural }) +} + +/// The first five diagnostics of a kind, one to a line, for the hint of a finding +fn lines(diagnostics: &[&Diagnostic], severity: Severity) -> (usize, String) { + let of_kind: Vec = diagnostics + .iter() + .filter(|diagnostic| diagnostic.severity == severity) + .map(|diagnostic| diagnostic.to_string()) + .collect(); + ( + of_kind.len(), + of_kind.into_iter().take(5).collect::>().join("\n"), + ) +} + +/// The key bindings, for `komorebic check`: the file `hotkeys compile` would read, what reading +/// and planning it have to say, and whether the shortcut files there are the ones it would write +/// for it. +pub fn check(home: &Path) -> Vec { + check_in(home, shortcut_dir().as_deref(), PlanMode::default()) +} + +/// [`check`], for the key binding file in `home`, planned in `mode`, against the shortcut files in +/// `shortcuts` +fn check_in(home: &Path, shortcuts: Option<&Path>, mode: PlanMode) -> Vec { + let Some((file, format)) = find(home) else { + return vec![ + Finding::note(format!( + "there is no skhdrc, whkdrc or sxhkdrc in {}", + home.display() + )) + .hint( + "key bindings are KDE global shortcuts: they come from a key binding file through `komorebic hotkeys compile`, or are set up in System Settings", + ), + ]; + }; + let text = match std::fs::read_to_string(&file) { + Ok(text) => text, + Err(error) => { + return vec![Finding::warning(format!( + "could not read {}: {error}", + file.display() + ))]; + } + }; + + let parsed = komorebi_hotkeys::parse(format, &text, &ParseOptions::default()); + let plan = komorebi_hotkeys::plan::plan(&parsed.keymap, &PlanOptions { mode }); + let diagnostics = diagnostics(&parsed, &plan); + + let bindings: usize = parsed.keymap.modes.iter().map(|m| m.bindings.len()).sum(); + let engine: usize = plan.engine.modes.iter().map(|m| m.bindings.len()).sum(); + let mut findings = vec![Finding::ok(format!( + "{} has {}: {} as shortcut files, {} in the engine", + file.display(), + count(bindings, "key binding", "key bindings"), + plan.static_files.len(), + engine + ))]; + + let (errors, shown) = lines(&diagnostics, Severity::Error); + if errors > 0 { + findings.push( + Finding::warning(format!( + "{} of it cannot be read and left out", + count(errors, "line", "lines") + )) + .hint(shown), + ); + } + let (warnings, shown) = lines(&diagnostics, Severity::Warning); + if warnings > 0 { + findings.push( + Finding::note(format!( + "{} not realized as {} would", + count(warnings, "binding is", "bindings are"), + format.file_name().trim_end_matches("rc") + )) + .hint(shown), + ); + } + + let files = kde::desktop_files(&plan.static_files); + match shortcuts.map(|dir| kde::diff(dir, &files)) { + Some(Ok(diff)) if diff.added.is_empty() && diff.changed.is_empty() && diff.removed.is_empty() => { + findings.push(Finding::ok(if files.is_empty() { + "no shortcut files are needed, and komorebi has written none" + } else { + "the shortcut files are the ones `komorebic hotkeys compile` writes" + })); + } + Some(Ok(diff)) => findings.push( + Finding::warning(format!( + "the shortcut files are not the ones `komorebic hotkeys compile` would write: {} to add, {} to change, {} to remove", + diff.added.len(), + diff.changed.len(), + diff.removed.len() + )) + .hint("`komorebic hotkeys compile --reload`"), + ), + Some(Err(error)) => findings.push(Finding::warning(format!( + "could not look at the shortcut files: {error}" + ))), + None => {} + } + + findings +} + +#[cfg(test)] +mod tests { + use super::*; + use komorebi_client::check::Level; + + /// A directory of its own, removed when it goes out of scope + struct Scratch(PathBuf); + + impl Scratch { + fn new() -> Self { + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let dir = std::env::temp_dir().join(format!( + "komorebic-hotkeys-unit-{}-{}", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn file(&self, name: &str, text: &str) -> &Self { + std::fs::write(self.0.join(name), text).unwrap(); + self + } + + fn shortcuts(&self) -> PathBuf { + self.0.join("shortcuts") + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + const SKHDRC: &str = "alt - h : komorebic focus left\nalt - l : komorebic focus right\n"; + + /// The level and message of each finding + fn said(findings: &[Finding]) -> Vec<(Level, String)> { + findings + .iter() + .map(|finding| (finding.level, finding.message.clone())) + .collect() + } + + #[test] + fn without_a_key_binding_file_there_is_a_note_that_says_where_they_come_from() { + let home = Scratch::new(); + + let findings = check_in(&home.0, Some(&home.shortcuts()), PlanMode::Auto); + + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].level, Level::Note); + assert!( + findings[0] + .message + .starts_with("there is no skhdrc, whkdrc or sxhkdrc in") + ); + assert!( + findings[0] + .hint + .as_deref() + .is_some_and(|hint| hint.contains("komorebic hotkeys compile")) + ); + } + + #[test] + fn the_first_file_of_the_three_formats_is_the_one_that_is_read() { + let home = Scratch::new(); + home.file("sxhkdrc", "super + h\n komorebic focus left\n") + .file( + "whkdrc", + "alt + h : komorebic focus left\nalt + l : komorebic focus right\n", + ); + + let findings = check_in(&home.0, None, PlanMode::Engine); + + assert_eq!(findings[0].level, Level::Ok); + assert!( + findings[0] + .message + .ends_with("whkdrc has 2 key bindings: 0 as shortcut files, 2 in the engine"), + "{}", + findings[0].message + ); + } + + #[test] + fn the_bindings_are_counted_by_where_the_plan_puts_them() { + let home = Scratch::new(); + home.file( + "sxhkdrc", + "super + h\n komorebic focus left\nsuper + l\n komorebic focus right\nsuper + w ; h\n komorebic move left\n", + ); + + let auto = check_in(&home.0, None, PlanMode::Auto); + let engine = check_in(&home.0, None, PlanMode::Engine); + + assert!( + auto[0] + .message + .ends_with("has 3 key bindings: 2 as shortcut files, 1 in the engine"), + "{}", + auto[0].message + ); + assert!( + engine[0] + .message + .ends_with("has 3 key bindings: 0 as shortcut files, 3 in the engine"), + "{}", + engine[0].message + ); + } + + #[test] + fn one_binding_is_not_plural() { + let home = Scratch::new(); + home.file("skhdrc", "alt - h : komorebic focus left\n"); + + let findings = check_in(&home.0, None, PlanMode::Auto); + + assert!( + findings[0] + .message + .ends_with("has 1 key binding: 1 as shortcut files, 0 in the engine"), + "{}", + findings[0].message + ); + } + + #[test] + fn shortcut_files_that_are_the_ones_of_the_plan_are_ok() { + let home = Scratch::new(); + home.file("skhdrc", SKHDRC); + let parsed = komorebi_hotkeys::parse(Format::Skhd, SKHDRC, &ParseOptions::default()); + let plan = komorebi_hotkeys::plan::plan( + &parsed.keymap, + &PlanOptions { + mode: PlanMode::Auto, + }, + ); + kde::write(&home.shortcuts(), &kde::desktop_files(&plan.static_files)).unwrap(); + + let findings = check_in(&home.0, Some(&home.shortcuts()), PlanMode::Auto); + + assert_eq!( + said(&findings)[1], + ( + Level::Ok, + "the shortcut files are the ones `komorebic hotkeys compile` writes".to_string() + ) + ); + } + + #[test] + fn shortcut_files_that_are_not_the_ones_of_the_plan_are_a_warning_that_says_how_many() { + let home = Scratch::new(); + home.file("skhdrc", SKHDRC); + let old = "alt - h : komorebic focus left\nalt - x : komorebic focus down\n"; + let parsed = komorebi_hotkeys::parse(Format::Skhd, old, &ParseOptions::default()); + let plan = komorebi_hotkeys::plan::plan( + &parsed.keymap, + &PlanOptions { + mode: PlanMode::Auto, + }, + ); + kde::write(&home.shortcuts(), &kde::desktop_files(&plan.static_files)).unwrap(); + + let findings = check_in(&home.0, Some(&home.shortcuts()), PlanMode::Auto); + + assert_eq!(findings[1].level, Level::Warning); + assert_eq!( + findings[1].message, + "the shortcut files are not the ones `komorebic hotkeys compile` would write: 1 to add, 0 to change, 1 to remove" + ); + assert_eq!( + findings[1].hint.as_deref(), + Some("`komorebic hotkeys compile --reload`") + ); + } + + #[test] + fn a_file_that_needs_no_shortcut_files_and_a_directory_without_any_agree() { + let home = Scratch::new(); + home.file("skhdrc", SKHDRC); + + let findings = check_in(&home.0, Some(&home.shortcuts()), PlanMode::Engine); + + assert_eq!( + said(&findings)[1], + ( + Level::Ok, + "no shortcut files are needed, and komorebi has written none".to_string() + ) + ); + } + + #[test] + fn a_line_that_cannot_be_read_is_a_warning_that_shows_the_line() { + let home = Scratch::new(); + home.file( + "skhdrc", + "alt - h : komorebic focus left\nalt - nosuchkey : komorebic focus up\n", + ); + + let findings = check_in(&home.0, None, PlanMode::Auto); + + assert_eq!(findings[1].level, Level::Warning); + assert_eq!( + findings[1].message, + "1 line of it cannot be read and left out" + ); + assert!( + findings[1] + .hint + .as_deref() + .is_some_and(|hint| hint.starts_with("line 2: error: ")), + "{:?}", + findings[1].hint + ); + } + + #[test] + fn a_binding_that_is_not_realized_as_its_own_daemon_would_is_a_note() { + let home = Scratch::new(); + home.file("skhdrc", "lalt - j : komorebic focus down\n"); + + let findings = check_in(&home.0, None, PlanMode::Auto); + + assert_eq!(findings[1].level, Level::Note); + assert_eq!( + findings[1].message, + "1 binding is not realized as skhd would" + ); + assert!( + findings[1] + .hint + .as_deref() + .is_some_and(|hint| hint.starts_with("line 1: warning: ")), + "{:?}", + findings[1].hint + ); + } + + #[test] + fn a_hint_shows_five_lines_at_most() { + let home = Scratch::new(); + let text: String = (0..8) + .map(|n| format!("lalt - {} : x\n", (b'a' + n) as char)) + .collect(); + home.file("skhdrc", &text); + + let findings = check_in(&home.0, None, PlanMode::Auto); + + assert_eq!( + findings[1].message, + "8 bindings are not realized as skhd would" + ); + assert_eq!(findings[1].hint.as_deref().unwrap().lines().count(), 5); + } +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 4ef20872..cbf4c37c 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -101,17 +101,19 @@ //! The others work without the daemon: `quickstart` writes an example `komorebi.json` and //! `applications.json` in the config home, `enable-autostart` and `disable-autostart` write and //! remove the entry that has Plasma start komorebi at login, `start` runs `komorebi` in the -//! background, with the -//! `komorebi.json` it is given with `--config`, `check` reads the `komorebi.json` the daemon would -//! and looks at the desktop, and reports what is wrong, exiting with status 1 if something is an -//! error, -//! `configuration` shows the path of the -//! `komorebi.json` the daemon reads, `log` follows its log, `data-directory` shows where its +//! background, with the `komorebi.json` it is given with `--config`, `check` reads the +//! `komorebi.json` the daemon would and the key binding file, looks at the desktop, and reports +//! what is wrong, exiting with status 1 if something is an error, `configuration` shows the path +//! of the `komorebi.json` the daemon reads, `log` follows its log, `data-directory` shows where its //! socket is, `completions` prints a completion script for a shell, and `static-config-schema`, //! `application-specific-configuration-schema`, `notification-schema` and `socket-schema` print //! the JSON Schema of `komorebi.json`, of an `applications.json`, of a notification and of a //! message. 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. +//! +//! `export-kde-shortcuts` and `hotkeys compile` read a key binding file (an skhdrc, a whkdrc or an +//! sxhkdrc) and write the bindings KDE can run by itself as shortcut files; the [`hotkeys`] module +//! has the details. use chrono::Utc; use clap::CommandFactory; @@ -149,6 +151,8 @@ use std::sync::atomic::Ordering; use std::time::Duration; use sysinfo::ProcessesToUpdate; +mod hotkeys; + lazy_static! { static ref HAS_CUSTOM_CONFIG_HOME: AtomicBool = AtomicBool::new(false); static ref HOME_DIR: PathBuf = { @@ -836,7 +840,7 @@ struct Check { #[clap(action, short, long)] #[clap(value_parser = replace_env_in_path)] komorebi_config: Option, - /// Look at the configuration only, not at the desktop + /// Look at the configuration and the key bindings only, not at the desktop #[clap(long)] configuration_only: bool, } @@ -863,6 +867,11 @@ enum SubCommand { Completions(Completions), /// Gather example configurations for a new-user quickstart Quickstart, + /// Turn an skhdrc into KDE global shortcuts (they work over RDP, unlike evdev hotkey daemons) + ExportKdeShortcuts(hotkeys::ExportKdeShortcuts), + /// Turn a key binding file (skhdrc, whkdrc, sxhkdrc) into KDE global shortcuts + #[clap(arg_required_else_help = true)] + Hotkeys(hotkeys::Hotkeys), /// Start komorebi as a background process Start(Start), /// Stop the komorebi process @@ -1367,12 +1376,18 @@ fn main() -> eyre::Result<()> { for cmd in subcommands { let name = cmd.get_name().to_string(); if !ignore.contains(&name.as_str()) { - // the same pages whatever the width of the terminal docgen runs in - let help_text = cmd.clone().term_width(100).render_long_help().to_string(); - let outpath = output_dir.join(format!("{name}.md")); - let markdown = format!("```text\n{help_text}\n```\n"); - std::fs::write(&outpath, markdown)?; - println!("{}", outpath.display()); + // a subcommand of a subcommand (`hotkeys compile`) gets a page of its own + let nested = cmd + .get_subcommands() + .map(|sub| (format!("{name}-{}", sub.get_name()), sub.clone())); + for (name, cmd) in std::iter::once((name.clone(), cmd.clone())).chain(nested) { + // the same pages whatever the width of the terminal docgen runs in + let help_text = cmd.term_width(100).render_long_help().to_string(); + let outpath = output_dir.join(format!("{name}.md")); + let markdown = format!("```text\n{help_text}\n```\n"); + std::fs::write(&outpath, markdown)?; + println!("{}", outpath.display()); + } } } } @@ -1380,6 +1395,8 @@ fn main() -> eyre::Result<()> { let mut cli = Opts::command(); clap_complete::generate(args.shell, &mut cli, "komorebic", &mut std::io::stdout()); } + SubCommand::ExportKdeShortcuts(args) => hotkeys::export_kde_shortcuts(args)?, + SubCommand::Hotkeys(args) => hotkeys::hotkeys(args)?, SubCommand::Quickstart => { fn write_file_with_prompt( path: &PathBuf, @@ -1496,6 +1513,8 @@ fn main() -> eyre::Result<()> { place.extend(findings); report.push("Configuration", place); + report.push("Key bindings", hotkeys::check(&HOME_DIR)); + if !args.configuration_only { report.push( "The desktop", diff --git a/komorebic/tests/check.rs b/komorebic/tests/check.rs index bfb7d1b4..f6c4ab8b 100644 --- a/komorebic/tests/check.rs +++ b/komorebic/tests/check.rs @@ -204,3 +204,106 @@ fn what_starts_komorebi_at_login_is_said_whether_or_not_the_desktop_is_there() { let _ = std::fs::remove_dir_all(dir); } + +/// Runs `komorebic check --configuration-only` in the config home `dir`, with a data home of its +/// own: the section of the key bindings is the one this looks at. +fn check_keys(dir: &Path) -> (Output, String) { + let output = Command::new(env!("CARGO_BIN_EXE_komorebic")) + .arg("check") + .arg("--configuration-only") + .env("KOMOREBI_CONFIG_HOME", dir) + .env("XDG_DATA_HOME", dir.join("data")) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&output.stdout).into_owned(); + (output, text) +} + +#[test] +fn without_a_key_binding_file_the_section_says_where_key_bindings_come_from() { + let dir = scratch("keys-none"); + + let (output, text) = check_keys(&dir); + + assert!(output.status.success(), "{text}"); + assert!(text.contains("Key bindings"), "{text}"); + assert!( + text.contains("there is no skhdrc, whkdrc or sxhkdrc in"), + "{text}" + ); + assert!(text.contains("komorebic hotkeys compile"), "{text}"); + + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_key_binding_file_of_the_config_home_is_read_and_a_line_it_cannot_read_is_a_warning() { + let dir = scratch("keys-file"); + std::fs::write( + dir.join("skhdrc"), + "alt - h : komorebic focus left\nalt - nosuchkey : komorebic focus up\n", + ) + .unwrap(); + + let (output, text) = check_keys(&dir); + + // a warning is not a reason to fail + assert!(output.status.success(), "{text}"); + assert!(text.contains("skhdrc has 1 key binding"), "{text}"); + assert!( + text.contains("1 line of it cannot be read and left out"), + "{text}" + ); + assert!(text.contains("line 2: error: "), "{text}"); + assert!(text.contains("1 warning(s)"), "{text}"); + + let _ = std::fs::remove_dir_all(dir); +} + +// the data home is where `dirs` looks on Linux only +#[cfg(target_os = "linux")] +#[test] +fn shortcut_files_the_file_does_not_call_for_are_a_warning_until_compile_replaces_them() { + let dir = scratch("keys-stale"); + std::fs::write(dir.join("skhdrc"), "alt - h : komorebic focus left\n").unwrap(); + let shortcuts = dir.join("data/kglobalaccel"); + std::fs::create_dir_all(&shortcuts).unwrap(); + std::fs::write( + shortcuts.join("komorebi-old.desktop"), + "[Desktop Entry]\nX-Komorebi-Generated=true\n", + ) + .unwrap(); + + let (output, text) = check_keys(&dir); + + assert!(output.status.success(), "{text}"); + assert!( + text.contains( + "the shortcut files are not the ones `komorebic hotkeys compile` would write" + ), + "{text}" + ); + assert!(text.contains("1 to remove"), "{text}"); + assert!( + text.contains("komorebic hotkeys compile --reload"), + "{text}" + ); + + let compiled = Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(["hotkeys", "compile"]) + .env("KOMOREBI_CONFIG_HOME", &dir) + .env("XDG_DATA_HOME", dir.join("data")) + .output() + .unwrap(); + assert!(compiled.status.success(), "{compiled:?}"); + + let (_, text) = check_keys(&dir); + assert!(!text.contains("are not the ones"), "{text}"); + assert!( + text.contains("the shortcut files are the ones") + || text.contains("no shortcut files are needed"), + "{text}" + ); + + let _ = std::fs::remove_dir_all(dir); +} diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 99c2f09c..c5d9d6c5 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -1144,6 +1144,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "enforce-workspace-rules.md", "ensure-named-workspaces.md", "ensure-workspaces.md", + "export-kde-shortcuts.md", "flip-layout.md", "focus-last-workspace.md", "focus-monitor-at-cursor.md", @@ -1159,6 +1160,8 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "generate-static-config.md", "global-state.md", "global-work-area-offset.md", + "hotkeys-compile.md", + "hotkeys.md", "ignore-rule.md", "initial-named-workspace-rule.md", "initial-workspace-rule.md", diff --git a/komorebic/tests/hotkeys.rs b/komorebic/tests/hotkeys.rs new file mode 100644 index 00000000..933fd6b4 --- /dev/null +++ b/komorebic/tests/hotkeys.rs @@ -0,0 +1,301 @@ +//! `export-kde-shortcuts` and `hotkeys compile` as a person runs them: the shortcut files they +//! write for a key binding file, what they print, and when they refuse. + +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use std::process::Output; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; + +/// A directory for one test: a komorebi config directory in `config`, and shortcut files in +/// `shortcuts` +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + static NEXT: AtomicU32 = AtomicU32::new(0); + let dir = std::env::temp_dir().join(format!( + "komorebic-hotkeys-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::SeqCst) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("config")).unwrap(); + Self(dir) + } + + fn config(&self) -> PathBuf { + self.0.join("config") + } + + fn shortcuts(&self) -> PathBuf { + self.0.join("shortcuts") + } + + /// Writes `text` to the config directory as `name`, and returns its path + fn file(&self, name: &str, text: &str) -> PathBuf { + let path = self.config().join(name); + std::fs::write(&path, text).unwrap(); + path + } + + fn komorebic(&self, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(args) + .env("KOMOREBI_CONFIG_HOME", self.config()) + .output() + .unwrap() + } + + /// The names of the files in the shortcut directory, sorted + fn written(&self) -> Vec { + let Ok(entries) = std::fs::read_dir(self.shortcuts()) else { + return Vec::new(); + }; + let mut names: Vec = entries + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + names.sort(); + names + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +fn stderr(output: &Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +fn fixture(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../komorebi-hotkeys/tests/fixtures") + .join(name) +} + +const SKHDRC: &str = "\ +alt - h : komorebic focus left +alt - l : komorebic focus right +lalt - j : komorebic focus down +:: resize +alt - r ; resize +resize < h : komorebic resize-axis horizontal decrease +"; + +#[test] +fn export_kde_shortcuts_writes_a_file_for_each_binding_a_shortcut_can_be() { + let scratch = Scratch::new(); + scratch.file("skhdrc", SKHDRC); + + let output = scratch.komorebic(&[ + "export-kde-shortcuts", + "--output", + scratch.shortcuts().to_str().unwrap(), + ]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!( + scratch.written(), + [ + "komorebi-focus-down.desktop", + "komorebi-focus-left.desktop", + "komorebi-focus-right.desktop", + ] + ); + let left = + std::fs::read_to_string(scratch.shortcuts().join("komorebi-focus-left.desktop")).unwrap(); + assert!(left.contains("\nX-KDE-Shortcuts=Alt+H\n"), "{left}"); + assert!(left.contains("\nExec=komorebic focus left\n"), "{left}"); + assert!( + stdout(&output).starts_with("Alt+H komorebic focus left\n"), + "{output:?}" + ); + assert!( + stdout(&output).contains("wrote 3 shortcuts to "), + "{output:?}" + ); + // the modes are left out, and lalt is either Alt: the diagnostics say so, with the file + let diagnostics = stderr(&output); + assert!( + diagnostics.contains("skhdrc: line 3: warning: "), + "{diagnostics}" + ); + assert!( + diagnostics.contains("skhdrc: line 5: warning: "), + "{diagnostics}" + ); + assert!(diagnostics.contains("is left out"), "{diagnostics}"); +} + +#[test] +fn a_dry_run_writes_nothing_and_says_what_a_write_would_change() { + let scratch = Scratch::new(); + let skhdrc = scratch.file("my-bindings", SKHDRC); + let shortcuts = scratch.shortcuts(); + std::fs::create_dir_all(&shortcuts).unwrap(); + std::fs::write(shortcuts.join("mine.desktop"), "[Desktop Entry]\n").unwrap(); + + let output = scratch.komorebic(&[ + "export-kde-shortcuts", + "--skhdrc", + skhdrc.to_str().unwrap(), + "--output", + shortcuts.to_str().unwrap(), + "--dry-run", + ]); + + assert!(output.status.success(), "{output:?}"); + assert_eq!(scratch.written(), ["mine.desktop"]); + assert!( + stdout(&output).contains("3 shortcuts would be written to "), + "{output:?}" + ); + assert!( + stdout(&output).contains("(3 new, 0 changed, 0 removed), 0 bindings need the engine"), + "{output:?}" + ); +} + +#[test] +fn compile_writes_the_same_shortcut_files_from_each_format() { + let written = |file: &str| { + let scratch = Scratch::new(); + let output = scratch.komorebic(&[ + "hotkeys", + "compile", + "--mode", + "auto", + fixture(file).to_str().unwrap(), + "--output", + scratch.shortcuts().to_str().unwrap(), + ]); + assert!(output.status.success(), "{output:?}"); + scratch.written() + }; + + let skhd = written("sample.skhdrc"); + + assert_eq!(skhd.len(), 50); + assert_eq!(skhd, written("sample.whkdrc")); + assert_eq!(skhd, written("sample.sxhkdrc")); +} + +#[test] +fn compile_without_a_file_reads_the_first_file_of_the_config_directory() { + let scratch = Scratch::new(); + scratch.file("whkdrc", ".shell pwsh\nalt + h : komorebic focus left\n"); + scratch.file("sxhkdrc", "alt + l\n komorebic focus right\n"); + + let output = scratch.komorebic(&[ + "hotkeys", + "compile", + "--mode", + "static", + "--output", + scratch.shortcuts().to_str().unwrap(), + ]); + + assert!(output.status.success(), "{output:?}"); + // skhdrc, whkdrc, sxhkdrc: the whkdrc is the first that exists + assert_eq!(scratch.written(), ["komorebi-focus-left.desktop"]); +} + +#[test] +fn compile_in_engine_mode_writes_no_shortcut_and_removes_the_ones_it_wrote() { + let scratch = Scratch::new(); + let skhdrc = scratch.file("skhdrc", SKHDRC); + let compile = |mode: &str| { + scratch.komorebic(&[ + "hotkeys", + "compile", + "--mode", + mode, + skhdrc.to_str().unwrap(), + "--output", + scratch.shortcuts().to_str().unwrap(), + ]) + }; + assert!(compile("static").status.success()); + assert_eq!(scratch.written().len(), 3); + + let output = compile("engine"); + + assert!(output.status.success(), "{output:?}"); + assert!(scratch.written().is_empty()); + assert!( + stdout(&output).contains("wrote 0 shortcuts to "), + "{output:?}" + ); + assert!( + stdout(&output).contains("(0 new, 0 changed, 3 removed), 5 bindings need the engine"), + "{output:?}" + ); +} + +#[test] +fn strict_refuses_a_file_with_a_warning_and_writes_nothing() { + let scratch = Scratch::new(); + let skhdrc = scratch.file("skhdrc", SKHDRC); + + let output = scratch.komorebic(&[ + "hotkeys", + "compile", + "--strict", + "--mode", + "auto", + skhdrc.to_str().unwrap(), + "--output", + scratch.shortcuts().to_str().unwrap(), + ]); + + assert!(!output.status.success(), "{output:?}"); + assert!(scratch.written().is_empty()); + assert!(stderr(&output).contains("--strict is set"), "{output:?}"); + + let clean = scratch.file("clean-skhdrc", "alt - h : komorebic focus left\n"); + let output = scratch.komorebic(&[ + "hotkeys", + "compile", + "--strict", + "--mode", + "auto", + clean.to_str().unwrap(), + "--output", + scratch.shortcuts().to_str().unwrap(), + ]); + assert!(output.status.success(), "{output:?}"); + assert_eq!(scratch.written(), ["komorebi-focus-left.desktop"]); +} + +#[test] +fn a_file_whose_name_says_no_format_needs_one() { + let scratch = Scratch::new(); + let file = scratch.file("bindings.conf", "alt + h\n komorebic focus left\n"); + let shortcuts = scratch.shortcuts(); + let compile = |extra: &[&str]| { + let mut args = vec!["hotkeys", "compile", "--mode", "static"]; + args.extend_from_slice(extra); + args.extend([ + file.to_str().unwrap(), + "--output", + shortcuts.to_str().unwrap(), + ]); + scratch.komorebic(&args) + }; + + let output = compile(&[]); + assert!(!output.status.success(), "{output:?}"); + assert!(stderr(&output).contains("give its --format"), "{output:?}"); + + let output = compile(&["--format", "sxhkd"]); + assert!(output.status.success(), "{output:?}"); + assert_eq!(scratch.written(), ["komorebi-focus-left.desktop"]); +} diff --git a/nix/tests/vm/lib/komorebi_vm/__init__.py b/nix/tests/vm/lib/komorebi_vm/__init__.py index 8365311d..1c487209 100644 --- a/nix/tests/vm/lib/komorebi_vm/__init__.py +++ b/nix/tests/vm/lib/komorebi_vm/__init__.py @@ -8,6 +8,7 @@ A suite imports what it needs from here: and the komorebi daemon that runs in it. * [`Outputs`](komorebi_vm.kde.Outputs) are the session's outputs, which a suite disables, enables and scales to change the monitors under the daemon. +* [`Keys`](komorebi_vm.keys.Keys) presses keys on the machine's keyboard. * [`daemon`](komorebi_vm.daemon) reads what the daemon logs about the events it handles and the frames it asks for. * [`pixels`](komorebi_vm.pixels) reads a screenshot: the color of a pixel, and @@ -25,12 +26,14 @@ against a fake machine (the `vm-lib` check does). from komorebi_vm import daemon, latency, pixels, uinput from komorebi_vm.checks import Checks from komorebi_vm.kde import Kde, Outputs, Rect +from komorebi_vm.keys import Keys from komorebi_vm.machine import Machine from komorebi_vm.pointer import Pointer __all__ = [ "Checks", "Kde", + "Keys", "Machine", "Outputs", "Pointer", diff --git a/nix/tests/vm/lib/komorebi_vm/keys.py b/nix/tests/vm/lib/komorebi_vm/keys.py new file mode 100644 index 00000000..0b31b8f8 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/keys.py @@ -0,0 +1,49 @@ +"""Key presses on the test machine's keyboard, as a person types them.""" + +from komorebi_vm.machine import Machine + +# QEMU names the left Super key `meta_l`; the others are named as KDE writes them +_MODIFIERS = { + "alt": "alt", + "ctrl": "ctrl", + "shift": "shift", + "meta": "meta_l", + "super": "meta_l", +} + + +class Keys: + """The keyboard of a test machine. + + A key press goes through QEMU's virtual keyboard (`machine.send_key`), so it + reaches the guest's kernel as a key of a real keyboard and KWin sees it as + it sees any other: a global shortcut fires on it, and a key that is not one + goes to the focused window. QEMU holds the keys for 100 ms, less than the + delay before a key repeats. + + A combo is written as in KDE, in lower case, with `-` between the keys: + `alt-h`, `meta-shift-j`, `esc`. The key names after the modifiers are + QEMU's (`h`, `1`, `esc`, `ret`, `bracket_left`). + """ + + def __init__(self, machine: Machine) -> None: + self.machine = machine + + @staticmethod + def qemu(combo: str) -> str: + """Returns `combo` as QEMU's `sendkey` writes it. + + A modifier is any of `alt`, `ctrl`, `shift`, `meta` and `super`; the + last word is the key, which QEMU must know. + """ + *modifiers, key = combo.lower().split("-") + for modifier in modifiers: + if modifier not in _MODIFIERS: + raise ValueError(f"{modifier!r} in {combo!r} is not a modifier") + if not key: + raise ValueError(f"{combo!r} has no key") + return "-".join([*(_MODIFIERS[m] for m in modifiers), key]) + + def send(self, combo: str) -> None: + """Presses the keys of `combo` together, and releases them.""" + self.machine.send_key(self.qemu(combo)) diff --git a/nix/tests/vm/lib/komorebi_vm/machine.py b/nix/tests/vm/lib/komorebi_vm/machine.py index 17a17e12..8552c630 100644 --- a/nix/tests/vm/lib/komorebi_vm/machine.py +++ b/nix/tests/vm/lib/komorebi_vm/machine.py @@ -34,3 +34,7 @@ class Machine(Protocol): def screenshot(self, filename: str, /) -> None: """Saves a PNG of the machine's display as `filename` in `out_dir`.""" ... + + def send_key(self, key: str, /) -> None: + """Presses the keys `key` names together on the machine's keyboard (QEMU's `sendkey`).""" + ... diff --git a/nix/tests/vm/lib/tests/conftest.py b/nix/tests/vm/lib/tests/conftest.py index 67827553..fd327c31 100644 --- a/nix/tests/vm/lib/tests/conftest.py +++ b/nix/tests/vm/lib/tests/conftest.py @@ -14,6 +14,7 @@ class FakeMachine: self.out_dir = out_dir self.commands: list[str] = [] + self.keys: list[str] = [] self.replies: list[tuple[Callable[[str], bool], tuple[int, str]]] = [] def reply(self, contains: str, status: int = 0, output: str = "") -> None: @@ -27,6 +28,9 @@ class FakeMachine: return answer return 0, "" + def send_key(self, key: str, /) -> None: + self.keys.append(key) + def screenshot(self, filename: str, /) -> None: Image.new("RGB", (4, 4), (10, 20, 30)).save(self.out_dir / f"{filename}.png") diff --git a/nix/tests/vm/lib/tests/test_keys.py b/nix/tests/vm/lib/tests/test_keys.py new file mode 100644 index 00000000..efc249fe --- /dev/null +++ b/nix/tests/vm/lib/tests/test_keys.py @@ -0,0 +1,24 @@ +import pytest + +from komorebi_vm import Keys + +from .conftest import FakeMachine + + +def test_a_combo_is_sent_as_qemu_names_it(machine: FakeMachine) -> None: + keys = Keys(machine) + + keys.send("alt-h") + keys.send("Meta-Shift-j") + keys.send("super-1") + keys.send("esc") + + assert machine.keys == ["alt-h", "meta_l-shift-j", "meta_l-1", "esc"] + + +def test_a_word_that_is_not_a_modifier_is_refused(machine: FakeMachine) -> None: + with pytest.raises(ValueError, match="'hyper' in 'hyper-h' is not a modifier"): + Keys(machine).send("hyper-h") + with pytest.raises(ValueError, match="has no key"): + Keys(machine).send("alt-") + assert machine.keys == [] diff --git a/nix/tests/vm/suites/check/test.py b/nix/tests/vm/suites/check/test.py index e570a759..8386bd6a 100644 --- a/nix/tests/vm/suites/check/test.py +++ b/nix/tests/vm/suites/check/test.py @@ -3,9 +3,10 @@ # own, komorebi without its script in KWin, komorebi not running, no KWin on the bus. What only a # real KWin can tell: that its version is read from what KWin says of itself, that the effects are # komorebi's builds because of what they contain, that a daemon is told from its script by KWin's -# own answer, and that a bus with no KWin on it is an error with an exit status that says so. The -# configuration and the exit status are covered by `komorebi/src/check.rs` and -# `komorebic/tests/check.rs`, against no desktop. +# own answer, that a bus with no KWin on it is an error with an exit status that says so, and that +# the shortcut files the check compares with are in the directory `komorebic hotkeys compile` +# writes to in a session. The configuration and the exit status are covered by +# `komorebi/src/check.rs` and `komorebic/tests/check.rs`, against no desktop. import base64 import json import re @@ -166,5 +167,55 @@ checks.check( and "komorebi is not running" not in out, ) +print("== 6. the key bindings") +KEYS_HOME = "/tmp/check-keys-home" +SHORTCUTS = "~/.local/share/kglobalaccel" +STALE = "[Desktop Entry]\nX-Komorebi-Generated=true\n" + + +def check_keys() -> tuple[int, str]: + """Runs `komorebic check` on the key bindings alone, in a config home of their own.""" + status, out = kde.run(f"KOMOREBI_CONFIG_HOME={KEYS_HOME} komorebic check --configuration-only") + print(out) + return status, out + + +kde.sh(f"mkdir -p {KEYS_HOME}") +status, out = check_keys() +checks.check( + "without a key binding file it is a note, not an error", + status == 0 and re.search(r"note +there is no skhdrc, whkdrc or sxhkdrc in ", out) is not None, +) + +kde.sh( + "printf %s " + + shlex.quote("alt - h : komorebic focus left\nalt - nosuchkey : komorebic focus up\n") + + f" > {KEYS_HOME}/skhdrc" +) +status, out = check_keys() +checks.check( + "the file is read, and the line it cannot read is a warning that does not fail the check", + status == 0 + and "skhdrc has 1 key binding" in out + and re.search(r"warning +1 line of it cannot be read and left out", out) is not None, +) + +# a shortcut file komorebi wrote that the file does not call for, in the directory of the session +kde.sh( + f"mkdir -p {SHORTCUTS} && printf %s {shlex.quote(STALE)} > {SHORTCUTS}/komorebi-stale.desktop" +) +status, out = check_keys() +checks.check( + "it says the shortcut files are not the ones `hotkeys compile` would write", + status == 0 + and "the shortcut files are not the ones `komorebic hotkeys compile` would write" in out, +) +kde.sh(f"KOMOREBI_CONFIG_HOME={KEYS_HOME} komorebic hotkeys compile") +status, out = check_keys() +checks.check( + "after `hotkeys compile` it does not: both use the directory of the session", + status == 0 and "are not the ones" not in out, +) + kde.stop() checks.finish() diff --git a/nix/tests/vm/suites/keys-static/default.nix b/nix/tests/vm/suites/keys-static/default.nix new file mode 100644 index 00000000..95fa6a2f --- /dev/null +++ b/nix/tests/vm/suites/keys-static/default.nix @@ -0,0 +1,21 @@ +{ + tier = "slow"; + kind = "session"; + timeoutMinutes = 10; + node = + { config, pkgs, ... }: + { + # static shortcuts work with no komorebi process, and this test runs none + services.komorebi.enable = false; + + # The shortcut files of keys.skhdrc, as `komorebic hotkeys compile` writes them, in the system + # profile, where KWin finds them when the session starts + environment.systemPackages = [ + config.services.komorebi.package + (pkgs.runCommand "komorebi-keys-static" { } '' + ${config.services.komorebi.package}/bin/komorebic hotkeys compile --mode auto \ + ${./keys.skhdrc} --output $out/share/kglobalaccel + '') + ]; + }; +} diff --git a/nix/tests/vm/suites/keys-static/keys.skhdrc b/nix/tests/vm/suites/keys-static/keys.skhdrc new file mode 100644 index 00000000..f1c33b77 --- /dev/null +++ b/nix/tests/vm/suites/keys-static/keys.skhdrc @@ -0,0 +1,5 @@ +# vm-keys-static: shortcut files in the system profile, each leaving a file behind when it runs +alt - j : touch /tmp/keys-static-alt-j +alt + shift - k : echo pressed >> /tmp/keys-static-alt-shift-k +# a % is a field code in a desktop entry's Exec line: the shortcut file writes it as %% +alt - p : date +%s > /tmp/keys-static-alt-p diff --git a/nix/tests/vm/suites/keys-static/test.py b/nix/tests/vm/suites/keys-static/test.py new file mode 100644 index 00000000..f33e666e --- /dev/null +++ b/nix/tests/vm/suites/keys-static/test.py @@ -0,0 +1,49 @@ +# Static shortcuts in a real Plasma session: what `komorebic hotkeys compile` and +# `komorebic export-kde-shortcuts` write is run by KWin itself, with no komorebi +# process. The Rust tests check the files; only a KWin can say that it reads them +# and runs their commands on a key: the files in the system profile when the +# session starts, and a file written later once `--reload` has handed it over. +from komorebi_vm import Checks, Kde, Keys + +start_all() +machine.wait_for_unit("multi-user.target") + +checks = Checks() +kde = Kde.session(machine, scale=SCALE) +keys = Keys(machine) + + +def ran(marker: str) -> bool: + return machine.execute(f"test -e /tmp/{marker}")[0] == 0 + + +def press(combo: str, marker: str) -> bool: + keys.send(combo) + return kde.wait_for(lambda: ran(marker), timeout=10) + + +print(kde.sh("ls /run/current-system/sw/share/kglobalaccel")) +checks.check("Alt+J runs its command", press("alt-j", "keys-static-alt-j")) +checks.check( + "Alt+Shift+K runs a command that needs a shell", + press("alt-shift-k", "keys-static-alt-shift-k"), +) +checks.check("Alt+P runs a command with a %", press("alt-p", "keys-static-alt-p")) +date = machine.succeed("cat /tmp/keys-static-alt-p").strip() +checks.check(f"the % reached the command as one % ({date!r})", date.isdigit()) + +# a binding written in the middle of the session, into the user's directory +kde.sh("mkdir -p ~/.config/komorebi") +kde.sh("echo 'alt - u : touch /tmp/keys-static-alt-u' > ~/.config/komorebi/skhdrc") +print(kde.sh("komorebic export-kde-shortcuts --reload")) +written = "/home/komorebi/.local/share/kglobalaccel/komorebi-touch-tmp-keys-static-alt-u.desktop" +checks.check( + "the file is in the user's kglobalaccel directory", + machine.execute(f"test -e {written}")[0] == 0, +) +checks.check( + "Alt+U runs its command once --reload has handed it over", + press("alt-u", "keys-static-alt-u"), +) + +checks.finish()