From 2f61b62276ccfee977d6ce68a9ff34c7977acb62 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 16:35:46 -0700 Subject: [PATCH] feat(kwin): survive restarts of the daemon and KWin kglobalaccel keeps the actions of a client that died, and their keys: a daemon that is killed leaves its keys swallowed and running nothing until they are unregistered. And kglobalaccel runs inside KWin, so a KWin that restarts forgets every key komorebi registered. Neither should leave a user without keys. kwin::hotkeys::release unregisters every action of the component, whatever registered it, and komorebic hotkeys release runs it, with or without a daemon. The NixOS module's unit runs it after the daemon stops (ExecStopPost), however it stops, and a start already takes over what is left. The KWin backend's NameOwnerChanged watch now also follows org.kde.kglobalaccel: when it has an owner again, kwin::hotkeys::rebind loads the key bindings into the new one, trying for 15 seconds. Loading moves from the daemon's main into kwin::hotkeys::load, which keeps its settings (Keybindings: file, format, plan mode, engine options), so that reload can read the file again: the message ReloadHotkeys, komorebic hotkeys reload. A new engine replaces the running one without unregistering its keys, and takes them over as a start does, so the keys both files have stay grabbed. The message HotkeysState answers with the engine's mode, the combos it holds and whether a chain is pending (null without an engine); komorebic hotkeys state prints it with the actions kglobalaccel has for the component. komorebic now depends on komorebi for the two calls to kglobalaccel, and on serde_json for the state. Tests: the socket messages without key bindings, state and release without a session bus, reload without a daemon, and a nixos-module-eval check of ExecStopPost. The VM test vm-restart-survival runs the module's unit in a Plasma session: a key works, hotkeys state shows it; with the daemon stopped by SIGSTOP the key runs nothing until hotkeys release gives it back; after SIGKILL the unit's journal shows the release and the restarted daemon has the key; after the KWin process is killed, the daemon registers the key with the new KWin; and a reload of a changed file swaps the key. vm-keys-engine asks the engine and does not sleep. A key that is not grabbed yet reaches the focused window, which showed as a binding that does not run, so the suite presses one once komorebic hotkeys state answers, which it does when the engine has made the calls of its last event: for a mode, for a chord chain beginning and ending, and for the keys of the application that takes the focus. It waits for the old daemon to exit before it starts the next (a daemon started meanwhile failed to load its KWin script), and activates a window until KWin has it (KWin lists a window before it can have the focus). The last check reloads the key bindings with komorebic hotkeys reload while wev has the focus and every binding is for the terminal, a start with no key to grab. --- Cargo.lock | 1 + docs/cli/hotkeys-release.md | 10 + docs/cli/hotkeys-reload.md | 10 + docs/cli/hotkeys-state.md | 10 + docs/cli/hotkeys.md | 6 +- docs/dev/ARCHITECTURE.md | 25 +- docs/dev/DESIGN.md | 10 + docs/dev/PLATFORM.md | 13 +- docs/installation.md | 4 + docs/usage/running-komorebi.md | 10 +- komorebi/src/core/mod.rs | 2 + komorebi/src/kwin/hotkeys.rs | 288 ++++++++++++++++-- komorebi/src/kwin/mod.rs | 11 +- komorebi/src/main.rs | 114 ++----- komorebi/src/process_command.rs | 19 ++ komorebic/Cargo.toml | 1 + komorebic/src/hotkeys.rs | 53 +++- komorebic/src/main.rs | 7 +- komorebic/tests/cli.rs | 3 + komorebic/tests/hotkeys.rs | 43 +++ nix/nixos-module.nix | 3 + nix/tests/nixos-module.nix | 7 + nix/tests/vm/suites/keys-engine/test.py | 147 +++++++-- .../vm/suites/restart-survival/default.nix | 5 + nix/tests/vm/suites/restart-survival/test.py | 119 ++++++++ 25 files changed, 771 insertions(+), 150 deletions(-) create mode 100644 docs/cli/hotkeys-release.md create mode 100644 docs/cli/hotkeys-reload.md create mode 100644 docs/cli/hotkeys-state.md create mode 100644 nix/tests/vm/suites/restart-survival/default.nix create mode 100644 nix/tests/vm/suites/restart-survival/test.py diff --git a/Cargo.lock b/Cargo.lock index 4e2ca157..96aa77cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2581,6 +2581,7 @@ dependencies = [ "color-eyre", "dirs 6.0.0", "fs-tail", + "komorebi", "komorebi-client", "komorebi-hotkeys", "lazy_static", diff --git a/docs/cli/hotkeys-release.md b/docs/cli/hotkeys-release.md new file mode 100644 index 00000000..d419338e --- /dev/null +++ b/docs/cli/hotkeys-release.md @@ -0,0 +1,10 @@ +```text +Unregister every key komorebi has registered with KDE, whether a daemon runs or not + +Usage: release + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/hotkeys-reload.md b/docs/cli/hotkeys-reload.md new file mode 100644 index 00000000..a93c30a3 --- /dev/null +++ b/docs/cli/hotkeys-reload.md @@ -0,0 +1,10 @@ +```text +Have the daemon read its key binding file again + +Usage: reload + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/hotkeys-state.md b/docs/cli/hotkeys-state.md new file mode 100644 index 00000000..a3bdc164 --- /dev/null +++ b/docs/cli/hotkeys-state.md @@ -0,0 +1,10 @@ +```text +Show the keys komorebi has registered with KDE, and what the engine of the daemon is doing + +Usage: state + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/hotkeys.md b/docs/cli/hotkeys.md index 391a0816..768ffae6 100644 --- a/docs/cli/hotkeys.md +++ b/docs/cli/hotkeys.md @@ -1,11 +1,15 @@ ```text -Turn a key binding file (skhdrc, whkdrc, sxhkdrc) into KDE global shortcuts +Key bindings: KDE global shortcuts from a key binding file, and the keys of the daemon Usage: hotkeys Commands: compile Plan the bindings of a key binding file, and write those that are static shortcuts as KDE shortcut files + state Show the keys komorebi has registered with KDE, and what the engine of the daemon is + doing + reload Have the daemon read its key binding file again + release Unregister every key komorebi has registered with KDE, whether a daemon runs or not help Print this message or the help of the given subcommand(s) Options: diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 0f3a4dc9..1c6886b8 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -1196,6 +1196,8 @@ With `services.komorebi.enable`, the module: - runs `execStart` in it, with `Restart=on-failure`, the exit status of a `SIGTERM` (130) counted as success, and a `PATH` of `/run/wrappers/bin`, `/etc/profiles/per-user/%u/bin` and `/run/current-system/sw/bin` instead of the store paths NixOS gives a unit; +- runs `komorebic hotkeys release` after the daemon has stopped (`ExecStopPost`), which + unregisters the keys a daemon that was killed left in kglobalaccel; - asserts that Plasma 6 is enabled. The VM tests run on machines built with it ([vm-tests.md](vm-tests.md)). Their headless node @@ -1217,6 +1219,7 @@ module's unit. | The animation effect is installed with komorebi, and not loaded until komorebi asks | the module installs `effects.animation.package` when `effects.animation.enable` is set, and the package's metadata says `EnabledByDefault` false | `nixos-module-eval` ("the animation effect is installed in the system profile", "with the animation effect off, ..."), the `kwin-effect-geometry-change-komorebi-install` check, `vm-look` | `effects.animation.enable = false` | | 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 | +| The keys of a daemon that was killed are given back | systemd: `ExecStopPost` runs `komorebic hotkeys release` | `nixos-module-eval` ("the unit releases the keys of the daemon when it stops"), `vm-restart-survival` | none | | A daemon that is told to stop stays stopped, and the unit is not failed | systemd: the exit statuses of `Stop` (0) and of `SIGTERM` (130) are successes | `vm-module` | none | | The daemon has the `PATH` of a terminal in the session | the unit's environment, with NixOS's default `PATH` turned off | `nixos-module-eval`, `vm-module` | none | | The VM suites run komorebi as the module installs it | framework path: the test nodes import the module, and `komorebi@NAME` runs its `execStart` | every VM suite | a suite's `node` can set `services.komorebi.enable = false` (`vm-render-smoke` does) | @@ -1687,7 +1690,19 @@ plan needs no engine. A failure to start is logged, and the window manager runs unless the default mode wants them; the others are unregistered. The engine starts in the default mode. - **Stop**: every key is released and every action unregistered, from - `KWinBackend::shutdown`, which every way the daemon stops goes through. + `KWinBackend::shutdown`, which every way the daemon stops goes through. A daemon that is + killed cannot: `kwin::hotkeys::release` (`komorebic hotkeys release`, the module's + `ExecStopPost`) unregisters every action of the component, with or without a daemon. +- **Reload**: `kwin::hotkeys::load` reads the file, plans it and starts the engine, and keeps + its settings; `reload` (the message `ReloadHotkeys`, `komorebic hotkeys reload`) does it again. + A new engine replaces the running one without unregistering its keys first, and takes them + over as a start does. +- **KWin restarting**: kglobalaccel runs in KWin. The KWin backend's watch of + `NameOwnerChanged` also follows `org.kde.kglobalaccel`, and when it has an owner again, + `kwin::hotkeys::rebind` loads the key bindings into it, trying for 15 seconds. +- **State**: the message `HotkeysState` is answered with the engine's mode, the combos it + holds and whether a chain is pending, or `null` when no engine runs; `komorebic hotkeys + state` adds the actions kglobalaccel has for the component. ### What is guaranteed, and by what @@ -1724,6 +1739,10 @@ plan needs no engine. A failure to start is logged, and the window manager runs | After the prefix of a chain only its next keys and Escape are grabbed, until a key ends the chain or its deadline passes, and the keys of the mode come back then | test, of the calls; VM test | `a_chain_grabs_its_next_keys_until_its_deadline`, the `Engine::deadline` doctest, `vm-keys-engine` | none | | The application of the focus is the one of the window KWin activated, a dialog included, and none once that window is gone | test | `the_focused_application_is_the_one_of_the_window_kwin_activated` | none | | A per-application key is grabbed only while the focused application (or an alias of it) has an action for it, and reaches the application otherwise | test, of the calls; VM test | `a_scoped_key_is_grabbed_only_while_its_application_has_the_focus`, `vm-keys-engine` | none | +| A key of a daemon that stopped answering is given back by `hotkeys release`, and a new daemon registers it again | VM test | `vm-restart-survival` | none | +| After KWin restarts, the keys are registered with the new kglobalaccel | framework path: the KWin backend's name-owner watch calls `kwin::hotkeys::rebind`; VM test | `vm-restart-survival` | none | +| A reload reads the file again, and the keys both files have stay grabbed | framework path: `start` replaces an engine without unregistering, and `Registry::startup` takes over; VM test | `a_start_takes_over_the_keys_of_a_killed_komorebi_and_drops_the_rest`, `vm-restart-survival` | none | +| Without key bindings, the daemon shows no engine and refuses a reload | test | `without_key_bindings_there_is_no_engine_to_show_or_reload` | none | | Holding a key runs its binding once | convention only: the transport listens to `globalShortcutPressed` and not to `globalShortcutRepeated` | none (measured in PLATFORM.md) | none | ## Where to look in the code @@ -1916,7 +1935,9 @@ plan needs no engine. A failure to start is logged, and the window manager runs - [`komorebi/src/kwin/hotkeys.rs`](../../komorebi/src/kwin/hotkeys.rs): the engine against kglobalaccel, and [`nix/tests/vm/suites/keys-engine`](../../nix/tests/vm/suites/keys-engine/test.py), keys - pressed in a real KWin with the daemon running. + pressed in a real KWin with the daemon running; + [`nix/tests/vm/suites/restart-survival`](../../nix/tests/vm/suites/restart-survival/test.py), + the keys when the daemon and KWin go away. - [`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 5c0d2f13..19501b51 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -772,3 +772,13 @@ engine acts on the pressed signal only, so holding a key runs its binding once. The engine itself does no I/O: it returns what to do, and the daemon does it. This entry needs the reason for that split. + +## Why does the unit release the keys after the daemon stops? + +Because nothing else does when a daemon dies. kglobalaccel keeps the actions of a client +that was killed, and their keys with them: on KWin 6.8.1 (2026-10-27) a killed client's key +stayed swallowed, and its signal was sent to nobody, until the action was unregistered. A +daemon that stops on its own unregisters its keys, but one that crashes or is killed cannot, +and the next start may never come. So the NixOS module's unit runs `komorebic hotkeys +release` after the daemon stops, however it stops (`ExecStopPost`), and a start takes over +what is still registered. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 405af9e4..1b6791ac 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -190,7 +190,11 @@ of the old KWin out of its layout, as if each had been closed: the bridge went w nothing reports them closing. When the name has an owner again, komorebi loads the bridge into the new KWin, trying again for up to 15 seconds while KWin is not ready for it, and the bridge reports the new KWin's windows and outputs as it does at start. A window that opens in the new -KWin is tiled. In the spikes the bridge was loaded again 1.0 to 1.1 seconds after the name had +KWin is tiled. kglobalaccel runs in KWin, so the keys of the engine go with the old KWin: +komorebi watches `org.kde.kglobalaccel` the same way, and when it has an owner again, it reads +its key binding file again and registers the keys with the new one, trying for up to 15 +seconds. The VM test `vm-restart-survival` kills the KWin of a Plasma session under the +daemon and presses a key afterwards. In the spikes the bridge was loaded again 1.0 to 1.1 seconds after the name had an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a running daemon. #### What komorebi leaves behind @@ -210,8 +214,9 @@ on, and the parking desktop with the hidden windows on it, until the next start script and the socket, sends the windows on the parking desktop to the first workspace's desktop and removes the desktop, and its stop puts the setting back (the backup in the runtime directory keeps the user's value), or the session ends. It also leaves the keys of its engine -grabbed: they are swallowed, and run nothing, until the next start takes them over and unregisters -those its key bindings no longer have. +grabbed: they are swallowed, and run nothing, until `komorebic hotkeys release` unregisters them, or +the next start takes them over and unregisters those its key bindings no longer have. The NixOS +module's unit runs `komorebic hotkeys release` after the daemon stops, however it stops. ### A headless KWin @@ -255,7 +260,7 @@ What komorebi calls: |---|---|---|---|---| | `org.kde.KWin` | `/Scripting` | `org.kde.kwin.Scripting` | `unloadScript(s)`, `loadScript(ss) -> i` | at start, and when KWin is back after a restart; `unloadScript` again at exit | | `org.kde.KWin` | `/Scripting/Script` | `org.kde.kwin.Script` | `run()` | after `loadScript` | -| `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `AddMatch(s)`, for the signal `NameOwnerChanged` | at start, to see KWin leave the bus and come back | +| `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `AddMatch(s)`, for the signal `NameOwnerChanged` | at start, to see KWin (`org.kde.KWin`, and `org.kde.kglobalaccel`, which it owns too) leave the bus and come back | | `org.kde.kglobalaccel` | `/component/kwin` | `org.kde.kglobalaccel.Component` | `invokeShortcut(s)`, with `MoveMouseToFocus` | when the pointer follows the focus | | `org.kde.KWin` | `/Effects` | `org.kde.kwin.Effects` | `isEffectSupported(s)`, `isEffectLoaded(s)`, `loadEffect(s)`, `unloadEffect(s)`, `reconfigureEffect(s)`, with `kwin4_effect_shapecorners` and `kwin4_effect_geometry_change` | when the look changes (the border is turned on, off or changed), and at exit | | `org.kde.KWin` | `/org/komorebi/BorderColours` | `org.komorebi.BorderColours1` | `SetColours(asau)`: the UUID of each window and its color, `0xRRGGBB` | when the color of a window's border changes; the object is komorebi's build of the border effect ([The patches](#the-patches)) | diff --git a/docs/installation.md b/docs/installation.md index 1d9ebdd4..4f662c7a 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -67,6 +67,9 @@ the repository's `rust-toolchain.toml` selects, whatever nixpkgs your system use - systemd starts the daemon again when it fails or is killed. When it is stopped (`komorebic stop`, or `systemctl --user stop komorebi`), it stays stopped until the next login or `systemctl --user start komorebi`. +- After the daemon stops, however it stops, the unit runs `komorebic hotkeys release`, which + gives back to KDE the keys the daemon had registered for its key bindings: a daemon that was + killed could not, and KDE would keep them, doing nothing, until the next start. - Without `services.desktopManager.plasma6.enable`, the configuration does not evaluate: an assertion of the module fails, and its message names the option to set. @@ -179,6 +182,7 @@ After=plasma-core.target [Service] ExecStart=%h/.cargo/bin/komorebi +ExecStopPost=%h/.cargo/bin/komorebic hotkeys release Restart=on-failure SuccessExitStatus=130 diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md index b264a7cb..8cab3147 100644 --- a/docs/usage/running-komorebi.md +++ b/docs/usage/running-komorebi.md @@ -99,8 +99,14 @@ do, so give the daemon the names they have on KDE: komorebic start -- --app-alias firefox=firefox-esr,librewolf --app-alias Terminal=konsole ``` -A daemon that is killed leaves its keys swallowed until it is started again; `komorebic stop` -gives them back. +[`komorebic hotkeys state`](../cli/hotkeys-state.md) shows the keys komorebi has registered +with KDE and what the daemon's engine is doing (its mode, and the keys it holds), and +[`komorebic hotkeys reload`](../cli/hotkeys-reload.md) has the daemon read its key binding +file again. A daemon that is killed leaves its keys swallowed until it is started again; +`komorebic stop` gives them back, and so does +[`komorebic hotkeys release`](../cli/hotkeys-release.md), with or without a daemon, which the +NixOS module's unit runs after the daemon stops. When KWin restarts, the daemon registers the +keys again with the new KWin. ## Asking komorebi what it is doing diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index bddcb02c..7f950c3a 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -748,6 +748,8 @@ pub enum SocketMessage { StaticConfigSchema, GenerateStaticConfig, DebugWindow(u32), + ReloadHotkeys, + HotkeysState, } impl SocketMessage { diff --git a/komorebi/src/kwin/hotkeys.rs b/komorebi/src/kwin/hotkeys.rs index 520382b2..b0c2c87c 100644 --- a/komorebi/src/kwin/hotkeys.rs +++ b/komorebi/src/kwin/hotkeys.rs @@ -65,23 +65,40 @@ //! names are taken over, and released unless the default mode wants them, and every other action //! of the component is unregistered. A stop ([`stop`]) releases every key and unregisters every //! action, so that nothing is left behind; [`KWinBackend`](super::KWinBackend) stops the engine -//! when it shuts down, which every way the daemon stops goes through. +//! when it shuts down, which every way the daemon stops goes through. A daemon that is killed +//! cannot: [`release`] (`komorebic hotkeys release`, which the NixOS module's unit runs after +//! the daemon stops) unregisters what it left. +//! +//! # Reloading, and KWin restarting +//! +//! [`load`] reads the key binding file, plans it and starts the engine; [`reload`] +//! (`komorebic hotkeys reload`) does it again with the same settings. A new engine takes over +//! the keys of the one it replaces, as a start does, so the keys both have stay grabbed and the +//! others are unregistered. kglobalaccel lives in KWin, so when KWin restarts the keys go with +//! it: the KWin backend watches `org.kde.kglobalaccel` on the session bus, and when it has an +//! owner again, [`rebind`] loads the key bindings into the new one. //! //! `docs/dev/PLATFORM.md` has what was measured of kglobalaccel, and the VM test `vm-keys-engine` //! presses keys in a Plasma session with the daemon running. +use crate::HOME_DIR; use color_eyre::eyre; use futures_util::StreamExt; use futures_util::future::join_all; +use komorebi_hotkeys::Format; use komorebi_hotkeys::Keymap; +use komorebi_hotkeys::ParseOptions; use komorebi_hotkeys::engine::Effect; use komorebi_hotkeys::engine::Engine; use komorebi_hotkeys::engine::EngineOptions; use komorebi_hotkeys::engine::Focus; +use komorebi_hotkeys::plan::PlanMode; +use komorebi_hotkeys::plan::PlanOptions; use komorebi_hotkeys::qt::Combo; use komorebi_hotkeys::qt::Key; use komorebi_hotkeys::qt::Mods; use parking_lot::Mutex; +use serde::Serialize; use std::collections::BTreeMap; use std::collections::BTreeSet; use std::path::PathBuf; @@ -376,7 +393,10 @@ fn spawn(effect: &Effect) { /// What the thread of the keys is told enum Message { Focus(Option), - Stop(std::sync::mpsc::Sender<()>), + State(std::sync::mpsc::Sender), + /// `true`: release and unregister every key first; `false`: leave them to the engine that + /// replaces this one + Stop(std::sync::mpsc::Sender<()>, bool), } /// The application that has the focus, as [`focus`] was last told @@ -414,18 +434,155 @@ pub fn is_running() -> bool { /// Releases every key, unregisters every action of the component and ends the engine's thread, /// and returns when that is done, or after 2 seconds. Does nothing when no engine runs. pub fn stop() { + end(true); +} + +fn end(release: bool) { let Some(messages) = RUNNING.lock().take() else { return; }; let (done, wait) = std::sync::mpsc::channel(); - if messages.send(Message::Stop(done)).is_ok() { + if messages.send(Message::Stop(done, release)).is_ok() { let _ = wait.recv_timeout(Duration::from_secs(2)); } } +/// What the engine that runs is doing, as `komorebic hotkeys state` shows it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct State { + /// The mode the engine is in. + pub mode: String, + /// The combos it holds, as KDE writes them, in order. + pub active: Vec, + /// Whether a chord chain is being typed. + pub chain: bool, +} + +/// Returns what the engine that runs is doing, or `None` when no engine runs. +pub fn state() -> Option { + let (answer, wait) = std::sync::mpsc::channel(); + RUNNING.lock().as_ref()?.send(Message::State(answer)).ok()?; + wait.recv_timeout(Duration::from_secs(2)).ok() +} + +/// Where the daemon's key bindings come from, and how the engine runs them. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Keybindings { + /// The key binding file. `None` is the first of `skhdrc`, `whkdrc` and `sxhkdrc` in + /// [`struct@HOME_DIR`], if there is one. + pub file: Option, + /// The format of the file. `None` is the format the end of its name says. + pub format: Option, + /// The mode the file is planned in: the engine takes the bindings the plan gives it, and + /// leaves the static shortcuts to KDE. + pub mode: PlanMode, + /// The options of the engine. + pub options: EngineOptions, +} + +/// The key bindings [`load`] was last given +static KEYBINDINGS: Mutex> = Mutex::new(None); + +/// Reads the key binding file, plans it, and runs the engine for the bindings the plan gives it, +/// in place of the engine that runs; stops the engine when there is no file or nothing in it for +/// the engine. Remembers `keybindings` for [`reload`]. +/// +/// An engine that replaces another takes over its keys, as a start does ([`Registry::startup`]), +/// so the keys the two have in common stay grabbed. The diagnostics of reading and planning are +/// logged at debug level, and one line at info level says what the file gave. +/// +/// # Errors +/// +/// - The file cannot be read, or its format is neither given nor in its name. +/// - The engine cannot start, for one of the reasons [`start`] gives. +pub fn load(keybindings: Keybindings) -> eyre::Result<()> { + *KEYBINDINGS.lock() = Some(keybindings.clone()); + + let file = match keybindings.file { + Some(file) => file, + None => { + let found = [Format::Skhd, Format::Whkd, Format::Sxhkd] + .iter() + .map(|format| HOME_DIR.join(format.file_name())) + .find(|path| path.is_file()); + match found { + Some(file) => file, + None => { + stop(); + return Ok(()); + } + } + } + }; + let format = match keybindings.format { + Some(format) => format, + None => { + let name = file + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); + [Format::Skhd, Format::Whkd, Format::Sxhkd] + .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 \ + (--keybindings-format)", + file.display() + )) + })? + } + }; + + 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(format, &text, &ParseOptions::default()); + let plan = komorebi_hotkeys::plan::plan( + &parsed.keymap, + &PlanOptions { + mode: keybindings.mode, + }, + ); + let diagnostics = parsed.diagnostics.iter().chain(&plan.diagnostics); + for diagnostic in diagnostics.clone() { + tracing::debug!("{}: {diagnostic}", file.display()); + } + let engine: usize = plan.engine.modes.iter().map(|m| m.bindings.len()).sum(); + tracing::info!( + "read {}: {engine} bindings for the engine, {} static shortcuts, {} diagnostics \ + (`komorebic hotkeys compile --dry-run` shows them)", + file.display(), + plan.static_files.len(), + diagnostics.count() + ); + + if plan.needs_engine() { + start(plan.engine, keybindings.options) + } else { + stop(); + Ok(()) + } +} + +/// Runs [`load`] again with the key bindings it was last given, which reads the file again: +/// `komorebic hotkeys reload`, and a kglobalaccel that has come back. +/// +/// # Errors +/// +/// - [`load`] has not been called. +/// - [`load`] fails. +pub fn reload() -> eyre::Result<()> { + let keybindings = KEYBINDINGS + .lock() + .clone() + .ok_or_else(|| eyre::Report::msg("the daemon was started without key bindings"))?; + load(keybindings) +} + /// Starts the engine for `keymap` against kglobalaccel on the session bus, on a thread of its /// own (`kwin-hotkeys`), and returns once its keys are registered. An engine that runs already -/// is [stopped](stop) first. +/// ends first, and the new one takes over its keys. /// /// The engine runs until [`stop`] or until the session bus goes away. /// @@ -435,7 +592,7 @@ pub fn stop() { /// - kglobalaccel is not on it (a KWin started with `--no-global-shortcuts`, or no KWin), or /// refuses a call. pub fn start(keymap: Keymap, options: EngineOptions) -> eyre::Result<()> { - stop(); + end(false); let (messages, receiver) = mpsc::unbounded_channel(); let (started, wait) = std::sync::mpsc::channel::>(); @@ -467,6 +624,91 @@ pub fn start(keymap: Keymap, options: EngineOptions) -> eyre::Result<()> { Ok(()) } +/// Loads the key bindings again into a kglobalaccel that has come back on the session bus: KWin +/// restarted, and the keys went with the old one. Tries for up to 15 seconds while kglobalaccel +/// is not ready. Does nothing when [`load`] has not been called. +/// +/// The KWin backend calls this when `org.kde.kglobalaccel` has an owner again. +pub fn rebind() { + if KEYBINDINGS.lock().is_none() { + return; + } + let started = Instant::now(); + loop { + match reload() { + Ok(()) => return, + Err(error) if started.elapsed() < Duration::from_secs(15) => { + tracing::debug!("kglobalaccel is not ready for the keys yet: {error}"); + std::thread::sleep(Duration::from_millis(250)); + } + Err(error) => { + tracing::error!("could not register the keys with the new kglobalaccel: {error}"); + return; + } + } + } +} + +/// Returns the names of the actions of the component in kglobalaccel, whether a komorebi runs or +/// not: the keys `komorebic hotkeys state` shows as registered. +/// +/// # Errors +/// +/// The session bus cannot be reached, or kglobalaccel is not on it. +pub fn registered() -> eyre::Result> { + block_on(async { + let (_connection, kglobalaccel) = connect().await?; + actions(&kglobalaccel).await + }) +} + +/// Unregisters every action of the component, whatever komorebi registered it, and returns their +/// names. +/// +/// This is `komorebic hotkeys release`, which the NixOS module's unit runs after the daemon has +/// stopped (`ExecStopPost`): a daemon that was killed could not give its keys back, and +/// kglobalaccel keeps them, swallowed, until they are unregistered. +/// +/// # Errors +/// +/// The session bus cannot be reached, kglobalaccel is not on it, or it refuses a call. +pub fn release() -> eyre::Result> { + block_on(async { + let (_connection, kglobalaccel) = connect().await?; + let names = actions(&kglobalaccel).await?; + for name in &names { + kglobalaccel + .call_method("unRegister", &(action_id(name),)) + .await?; + } + Ok(names) + }) +} + +fn block_on(future: impl std::future::Future>) -> eyre::Result { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()? + .block_on(future) +} + +async fn connect() -> eyre::Result<(Connection, Proxy<'static>)> { + let connection = Connection::session().await?; + let kglobalaccel = Proxy::new(&connection, SERVICE, PATH, IFACE).await?; + Ok((connection, kglobalaccel)) +} + +/// The names of the component's actions +async fn actions(kglobalaccel: &Proxy<'_>) -> eyre::Result> { + let ids: Vec> = kglobalaccel + .call("allActionsForComponent", &(action_id(""),)) + .await?; + Ok(ids + .into_iter() + .filter_map(|id| id.get(1).cloned()) + .collect()) +} + fn action_id(action: &str) -> Vec { vec![ COMPONENT.to_string(), @@ -533,12 +775,7 @@ async fn serve( mut messages: mpsc::UnboundedReceiver, started: std::sync::mpsc::Sender>, ) -> eyre::Result<()> { - let setup = async { - let connection = Connection::session().await?; - let kglobalaccel = Proxy::new(&connection, SERVICE, PATH, IFACE).await?; - Ok::<_, eyre::Report>((connection, kglobalaccel)) - }; - let (connection, kglobalaccel) = match setup.await { + let (connection, kglobalaccel) = match connect().await { Ok(setup) => setup, Err(error) => { let _ = started.send(Err(error)); @@ -552,13 +789,8 @@ async fn serve( // the bindings of the application that has the focus are the ones to grab at start let mut start = engine.on_focus(FOCUS.lock().clone()); - let existing: Vec = kglobalaccel - .call::<_, _, Vec>>("allActionsForComponent", &(action_id(""),)) - .await - .unwrap_or_default() - .into_iter() - .filter_map(|id| id.get(1).cloned()) - .collect(); + // a component kglobalaccel does not know yet has no actions + let existing = actions(&kglobalaccel).await.unwrap_or_default(); start.extend(engine.start()); let calls = registry.startup(&existing, &known, &start); let registered = calls.iter().filter(|c| matches!(c, Call::Grab(_))).count(); @@ -622,11 +854,21 @@ async fn serve( } engine.on_focus(focus) } - Some(Message::Stop(done)) => { - let mut calls = registry.calls(&engine.stop()); - calls.extend(registry.unregister_all()); - execute(&kglobalaccel, calls).await; - tracing::info!("gave every key back to kglobalaccel"); + Some(Message::State(answer)) => { + let _ = answer.send(State { + mode: engine.mode().to_string(), + active: engine.active().map(|combo| combo.to_string()).collect(), + chain: engine.deadline().is_some(), + }); + continue; + } + Some(Message::Stop(done, release)) => { + if release { + let mut calls = registry.calls(&engine.stop()); + calls.extend(registry.unregister_all()); + execute(&kglobalaccel, calls).await; + tracing::info!("gave every key back to kglobalaccel"); + } let _ = done.send(()); return Ok(()); } diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index d6762a7c..a4eed240 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -32,7 +32,8 @@ //! when nobody does, every window of the old KWin is gone, and nothing will report it closing, so //! the table reports each as destroyed ([`state::Table::compositor_lost`]); when the name has an //! owner again, the daemon loads the script into the new KWin, which reports its desktop as it -//! does at start. +//! does at start. The same watch sees `org.kde.kglobalaccel`, which KWin owns too, come back, +//! and has [`hotkeys::rebind`] register the keys with it again. //! //! The script also reports the outputs when KWin's list of them changes, when a panel (a dock //! window) opens, closes or moves, and once a second, because KWin has no signal for the room a @@ -565,6 +566,14 @@ async fn supervise(shared: Arc) { while let Some(signal) = owner_changes.next().await { let Ok(args) = signal.args() else { continue }; + // the global shortcut daemon runs in KWin, and its keys go with it + if args.name().as_str() == "org.kde.kglobalaccel" { + if args.new_owner().is_some() { + tracing::info!("kglobalaccel is back; registering the keys again"); + tokio::task::spawn_blocking(hotkeys::rebind); + } + continue; + } if args.name().as_str() != "org.kde.KWin" { continue; } diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index a8e40679..4546f748 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -19,11 +19,11 @@ //! With a key binding file (`--keybindings`, or the first of `skhdrc`, `whkdrc` and `sxhkdrc` in //! [`struct@HOME_DIR`]), the daemon also runs the engine of [`komorebi_hotkeys`]: it registers the //! keys of the bindings that are not static shortcuts with KWin's global shortcut daemon and runs -//! their commands ([`komorebi::kwin::hotkeys`]). The bindings it takes are the engine's part of -//! the file's plan in `--keybindings-mode`, the mode `komorebic hotkeys compile --mode` wrote the -//! static shortcuts in. `--chord-timeout` is how long the next key of a chord chain is waited -//! for, and `--app-alias` gives an application other names for the bindings that are for one -//! application. +//! their commands ([`komorebi::kwin::hotkeys::load`]). A file that cannot be read is logged, and +//! the window manager runs without keys. The bindings it takes are the engine's part of the file's +//! plan in `--keybindings-mode`, the mode `komorebic hotkeys compile --mode` wrote the static +//! shortcuts in. `--chord-timeout` is how long the next key of a chord chain is waited for, and +//! `--app-alias` gives an application other names for the bindings that are for one application. //! //! It logs to standard output and to a file a day in [`struct@LOG_DIR`], which `komorebic log` //! follows. @@ -43,6 +43,7 @@ use komorebi::backend; use komorebi::backend::fake::FakeBackend; use komorebi::border_manager; use komorebi::core::pathext::replace_env_in_path; +use komorebi::kwin::hotkeys::Keybindings; use komorebi::monitor_reconciliator; use komorebi::process_command::listen_for_commands; use komorebi::process_event::listen_for_events; @@ -50,10 +51,8 @@ use komorebi::static_config::StaticConfig; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event_listener; use komorebi_hotkeys::Format; -use komorebi_hotkeys::ParseOptions; use komorebi_hotkeys::engine::EngineOptions; use komorebi_hotkeys::plan::PlanMode; -use komorebi_hotkeys::plan::PlanOptions; use parking_lot::Mutex; use serde::Deserialize; use std::collections::BTreeMap; @@ -269,87 +268,6 @@ fn app_alias(value: &str) -> Result<(String, Vec), String> { Ok((name.trim().to_string(), aliases)) } -/// Reads the key binding file, and starts the engine for the bindings that are not static -/// shortcuts. Does nothing when there is no file, or nothing in it for the engine. An engine that -/// cannot start is logged, and the window manager runs without keys. -/// -/// # Errors -/// -/// The file cannot be read, or its format is neither given nor in its name. -fn keybindings(opts: &Opts) -> eyre::Result<()> { - let file = match &opts.keybindings { - Some(file) => file.clone(), - None => { - let found = [Format::Skhd, Format::Whkd, Format::Sxhkd] - .iter() - .map(|format| HOME_DIR.join(format.file_name())) - .find(|path| path.is_file()); - match found { - Some(file) => file, - None => return Ok(()), - } - } - }; - let format = match opts.keybindings_format { - Some(format) => format.into(), - None => { - let name = file - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or_default(); - [Format::Skhd, Format::Whkd, Format::Sxhkd] - .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 --keybindings-format", - file.display() - )) - })? - } - }; - - 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(format, &text, &ParseOptions::default()); - let plan = komorebi_hotkeys::plan::plan( - &parsed.keymap, - &PlanOptions { - mode: opts.keybindings_mode.into(), - }, - ); - let diagnostics = parsed.diagnostics.iter().chain(&plan.diagnostics); - for diagnostic in diagnostics.clone() { - tracing::debug!("{}: {diagnostic}", file.display()); - } - let engine: usize = plan.engine.modes.iter().map(|m| m.bindings.len()).sum(); - tracing::info!( - "read {}: {engine} bindings for the engine, {} static shortcuts, {} diagnostics \ - (`komorebic hotkeys compile --dry-run` shows them)", - file.display(), - plan.static_files.len(), - diagnostics.count() - ); - let mut app_aliases: BTreeMap> = BTreeMap::new(); - for (name, aliases) in &opts.app_alias { - app_aliases - .entry(name.clone()) - .or_default() - .extend(aliases.iter().cloned()); - } - let options = EngineOptions { - chord_timeout: Duration::from_millis(opts.chord_timeout), - app_aliases, - }; - if plan.needs_engine() - && let Err(error) = komorebi::kwin::hotkeys::start(plan.engine, options) - { - tracing::error!("the key bindings are not active: {error}"); - } - Ok(()) -} - fn main() -> eyre::Result<()> { let opts: Opts = Opts::parse(); let (_guard, _color_guard) = setup(opts.log_level.clone())?; @@ -430,7 +348,25 @@ fn main() -> eyre::Result<()> { // the keys need KWin's global shortcut daemon, and the in-memory desktop has none if !opts.fake_backend { - keybindings(&opts)?; + let mut app_aliases: BTreeMap> = BTreeMap::new(); + for (name, aliases) in &opts.app_alias { + app_aliases + .entry(name.clone()) + .or_default() + .extend(aliases.iter().cloned()); + } + let keybindings = Keybindings { + file: opts.keybindings.clone(), + format: opts.keybindings_format.map(Format::from), + mode: opts.keybindings_mode.into(), + options: EngineOptions { + chord_timeout: Duration::from_millis(opts.chord_timeout), + app_aliases, + }, + }; + if let Err(error) = komorebi::kwin::hotkeys::load(keybindings) { + tracing::error!("the key bindings are not active: {error}"); + } } let (quit_sender, quit_receiver) = std::sync::mpsc::channel(); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 2cbc246a..436ef927 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -420,6 +420,7 @@ impl WindowManager { /// [`WindowManager::retile_all`] gives. /// - The answer cannot be written to `reply`. /// - `Stop` or `StopIgnoreRestore` fails, for the reason [`WindowManager::stop`] gives. + /// - `ReloadHotkeys` fails, for one of the reasons [`crate::kwin::hotkeys::reload`] gives. /// - The notification cannot be sent, for one of the reasons [`notify_subscribers`] gives. #[tracing::instrument(skip(self, reply, message))] pub fn process_command( @@ -2074,6 +2075,11 @@ impl WindowManager { ANIMATION_STYLE_PER_ANIMATION.lock().clear(); } }, + SocketMessage::ReloadHotkeys => crate::kwin::hotkeys::reload()?, + SocketMessage::HotkeysState => { + let state = serde_json::to_string_pretty(&crate::kwin::hotkeys::state())?; + reply.write_all(state.as_bytes())?; + } } self.update_known_window_ids(); @@ -2286,6 +2292,19 @@ mod tests { Ok(()) } + #[test] + fn without_key_bindings_there_is_no_engine_to_show_or_reload() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(751)); + + assert_eq!(daemon.ask(SocketMessage::HotkeysState)?, "null"); + let error = daemon.ask(SocketMessage::ReloadHotkeys).unwrap_err(); + assert!( + error.to_string().contains("started without key bindings"), + "{error}" + ); + Ok(()) + } + #[test] fn a_query_is_answered_with_one_value() -> eyre::Result<()> { let daemon = Daemon::new(two_windows(711)); diff --git a/komorebic/Cargo.toml b/komorebic/Cargo.toml index e86aa410..23963548 100644 --- a/komorebic/Cargo.toml +++ b/komorebic/Cargo.toml @@ -5,6 +5,7 @@ description = "The command-line interface for Komorebi, a tiling window manager edition = "2024" [dependencies] +komorebi = { path = "../komorebi", default-features = false } komorebi-client = { path = "../komorebi-client", default-features = false } komorebi-hotkeys = { path = "../komorebi-hotkeys" } version = { path = "../version" } diff --git a/komorebic/src/hotkeys.rs b/komorebic/src/hotkeys.rs index b49d4b3d..d0ddd6a7 100644 --- a/komorebic/src/hotkeys.rs +++ b/komorebic/src/hotkeys.rs @@ -1,17 +1,24 @@ //! 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`]. +//! `export-kde-shortcuts` and `hotkeys compile` 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`]. +//! +//! The other `hotkeys` subcommands are about the engine of the daemon. `hotkeys state` prints the +//! keys komorebi has registered with KDE ([`komorebi::kwin::hotkeys::registered`]) and what the +//! engine is doing (the daemon's answer to `HotkeysState`), `hotkeys reload` has the daemon read +//! its key binding file again (`ReloadHotkeys`), and `hotkeys release` unregisters every key +//! komorebi registered ([`komorebi::kwin::hotkeys::release`]), with or without a daemon. use crate::HOME_DIR; use clap::Parser; use clap::Subcommand; use clap::ValueEnum; use color_eyre::eyre; +use komorebi_client::SocketMessage; use komorebi_client::check::Finding; use komorebi_hotkeys::Diagnostic; use komorebi_hotkeys::Format; @@ -54,6 +61,12 @@ enum HotkeysCommand { /// Plan the bindings of a key binding file, and write those that are static shortcuts as KDE /// shortcut files Compile(Compile), + /// Show the keys komorebi has registered with KDE, and what the engine of the daemon is doing + State, + /// Have the daemon read its key binding file again + Reload, + /// Unregister every key komorebi has registered with KDE, whether a daemon runs or not + Release, } #[derive(Parser)] @@ -175,6 +188,34 @@ pub fn hotkeys(args: Hotkeys) -> eyre::Result<()> { dry_run: args.dry_run, }) } + HotkeysCommand::State => { + let registered = komorebi::kwin::hotkeys::registered().map_err(|error| { + eyre::Report::msg(format!("could not ask KDE for the keys: {error}")) + })?; + // no daemon: no engine + let engine = komorebi_client::send_query(&SocketMessage::HotkeysState) + .ok() + .and_then(|answer| serde_json::from_str(&answer).ok()) + .unwrap_or(serde_json::Value::Null); + let state = serde_json::json!({ "registered": registered, "engine": engine }); + println!("{}", serde_json::to_string_pretty(&state)?); + Ok(()) + } + HotkeysCommand::Reload => { + komorebi_client::send_message(&SocketMessage::ReloadHotkeys)?; + Ok(()) + } + HotkeysCommand::Release => { + let released = komorebi::kwin::hotkeys::release().map_err(|error| { + eyre::Report::msg(format!("could not release the keys: {error}")) + })?; + if released.is_empty() { + println!("komorebi had no key registered"); + } else { + println!("released {} keys: {}", released.len(), released.join(", ")); + } + Ok(()) + } } } diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index cbf4c37c..414c528d 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -112,8 +112,9 @@ //! 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. +//! sxhkdrc) and write the bindings KDE can run by itself as shortcut files. `hotkeys state`, +//! `hotkeys reload` and `hotkeys release` look after the keys the daemon registers with KDE; the +//! [`hotkeys`] module has the details. use chrono::Utc; use clap::CommandFactory; @@ -869,7 +870,7 @@ enum SubCommand { 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 + /// Key bindings: KDE global shortcuts from a key binding file, and the keys of the daemon #[clap(arg_required_else_help = true)] Hotkeys(hotkeys::Hotkeys), /// Start komorebi as a background process diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index c5d9d6c5..2e2775c3 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -1161,6 +1161,9 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "global-state.md", "global-work-area-offset.md", "hotkeys-compile.md", + "hotkeys-release.md", + "hotkeys-reload.md", + "hotkeys-state.md", "hotkeys.md", "ignore-rule.md", "initial-named-workspace-rule.md", diff --git a/komorebic/tests/hotkeys.rs b/komorebic/tests/hotkeys.rs index 933fd6b4..b0c55a67 100644 --- a/komorebic/tests/hotkeys.rs +++ b/komorebic/tests/hotkeys.rs @@ -299,3 +299,46 @@ fn a_file_whose_name_says_no_format_needs_one() { assert!(output.status.success(), "{output:?}"); assert_eq!(scratch.written(), ["komorebi-focus-left.desktop"]); } + +#[test] +fn state_and_release_without_a_session_bus_say_that_kde_cannot_be_reached() { + let scratch = Scratch::new(); + let run = |args: &[&str]| { + Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(args) + .env( + "DBUS_SESSION_BUS_ADDRESS", + "unix:path=/nonexistent/komorebic-test.bus", + ) + .env("XDG_RUNTIME_DIR", &scratch.0) + .output() + .unwrap() + }; + + let output = run(&["hotkeys", "release"]); + assert!(!output.status.success(), "{output:?}"); + assert!( + stderr(&output).contains("could not release the keys"), + "{output:?}" + ); + + let output = run(&["hotkeys", "state"]); + assert!(!output.status.success(), "{output:?}"); + assert!( + stderr(&output).contains("could not ask KDE for the keys"), + "{output:?}" + ); +} + +#[test] +fn reload_without_a_daemon_fails() { + let scratch = Scratch::new(); + + let output = Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(["hotkeys", "reload"]) + .env("XDG_RUNTIME_DIR", &scratch.0) + .output() + .unwrap(); + + assert!(!output.status.success(), "{output:?}"); +} diff --git a/nix/nixos-module.nix b/nix/nixos-module.nix index 95bb6c47..cf5ffa56 100644 --- a/nix/nixos-module.nix +++ b/nix/nixos-module.nix @@ -354,6 +354,9 @@ in ]; serviceConfig = { ExecStart = cfg.execStart; + # kglobalaccel keeps the keys of a daemon that died until they are unregistered: without + # this they would stay swallowed, running nothing, until the next start + ExecStopPost = "${lib.getExe' cfg.package "komorebic"} hotkeys release"; Restart = "on-failure"; # what komorebi exits with when it is stopped with SIGTERM, as systemd stops a unit SuccessExitStatus = 130; diff --git a/nix/tests/nixos-module.nix b/nix/tests/nixos-module.nix index ae3209db..d85c7d43 100644 --- a/nix/tests/nixos-module.nix +++ b/nix/tests/nixos-module.nix @@ -349,6 +349,13 @@ let name = "the unit counts the exit status of a SIGTERM (130) as success"; ok = (unit enabled).serviceConfig.SuccessExitStatus == 130; } + { + name = "the unit releases the keys of the daemon when it stops"; + ok = + (unit enabled).serviceConfig.ExecStopPost + == "${enabled.services.komorebi.package}/bin/komorebic hotkeys release"; + got = (unit enabled).serviceConfig.ExecStopPost; + } { name = "the unit runs execStart"; ok = (unit enabled).serviceConfig.ExecStart == enabled.services.komorebi.execStart; diff --git a/nix/tests/vm/suites/keys-engine/test.py b/nix/tests/vm/suites/keys-engine/test.py index de58438a..daaeedc5 100644 --- a/nix/tests/vm/suites/keys-engine/test.py +++ b/nix/tests/vm/suites/keys-engine/test.py @@ -3,8 +3,9 @@ # engine's effects become; only KWin can say that a grabbed key reports its presses to the daemon, # that the keys of a killed daemon stay registered until the next start takes them over, and that # a stop gives them back. +import json import shlex -import time +from typing import Any from komorebi_vm import Checks, Kde, Keys @@ -25,16 +26,52 @@ def press(combo: str, marker: str) -> bool: return kde.wait_for(lambda: ran(marker), timeout=10) -def start(skhdrc: str, *args: str) -> None: +def engine() -> dict[str, Any]: + """What the engine is doing: its `mode`, the keys it holds (`active`) and whether a chord + `chain` is being typed. It is empty when no engine answers. + + The engine answers once it has told kglobalaccel everything its last event needed, so what it + says it holds is what KWin has grabbed. A key pressed before that is not the engine's yet and + goes to the window, and how long the grab takes is how slow the machine is: the engine is + asked, and no fixed time is waited. + """ + status, out = kde.run("komorebic hotkeys state") + return (json.loads(out).get("engine") or {}) if status == 0 else {} + + +def in_mode(mode: str) -> bool: + """Waits for the engine to be in `mode`, with the keys of the mode grabbed.""" + return kde.wait_for(lambda: engine().get("mode") == mode, timeout=10) + + +def chain_is(on: bool, within: float = 10) -> bool: + """Waits for the engine to be in a chord chain (or, with `on` false, to be done with it, and to + hold the keys of the mode again), for up to `within` seconds.""" + return kde.wait_for(lambda: engine().get("chain") is on, timeout=within) + + +def write(skhdrc: str) -> None: kde.sh( f"mkdir -p ~/.config/komorebi && printf '%s' {shlex.quote(skhdrc)} > ~/.config/komorebi/skhdrc" ) + + +def start(skhdrc: str, *args: str) -> None: + write(skhdrc) # no --keybindings: the daemon finds the skhdrc in the config directory kde.spawn_komorebi("--log-level", "debug", *args) if not kde.wait_for(lambda: "keys in kglobalaccel" in kde.komorebi_log(), timeout=60): raise AssertionError(f"the keys were not registered:\n{kde.komorebi_log()}") +def stop() -> None: + """Stops the daemon, and waits until it is gone: it takes its KWin script and its keys with + it when it exits, and a daemon started before that would find them taken from it.""" + kde.komorebic("stop") + if not kde.wait_for(lambda: machine.execute("pgrep -x komorebi")[0] != 0, timeout=10): + raise AssertionError("the daemon did not stop") + + start( "alt - h : touch /tmp/keys-engine-alt-h\n" "alt - r : komorebic retile\n" @@ -83,7 +120,20 @@ checks.check( kde.spawn("stdbuf -oL wev", log="/tmp/wev.log") if not kde.wait_for(lambda: kde.wid_by_class("wev") != "", timeout=30): raise AssertionError("wev did not open") -kde.activate(kde.wid_by_class("wev")) + + +def activate(wid: str) -> None: + """Gives the window the focus, asking again until KWin has: it lists a window before it + can have the focus, and refuses to activate it until then.""" + if not kde.wait_for( + lambda: kde.run(f"kdotool windowactivate {shlex.quote(wid)}")[0] == 0 + and kde.active() == wid, + timeout=30, + ): + raise AssertionError(f"{wid} did not take the focus") + + +activate(kde.wid_by_class("wev")) def typed(key: str) -> int: @@ -108,41 +158,75 @@ keys.send("h") checks.check("in the default mode H reaches the focused window", reaches_wev("h", 1)) checks.check("Alt+R enters the mode and runs its command", press("alt-r", "keys-modes-entered")) checks.check( - "the daemon logs the mode it is in", - kde.wait_for(lambda: "the mode is now resize" in kde.komorebi_log()), + "the daemon logs the mode it is in, and holds the keys of the mode", + kde.wait_for(lambda: "the mode is now resize" in kde.komorebi_log()) and in_mode("resize"), ) checks.check("in the mode H runs its binding", press("h", "keys-modes-h")) checks.check("and does not reach the window", typed("h") == 1) keys.send("esc") checks.check( - "Escape goes back to the default mode", - kde.wait_for(lambda: "the mode is now default" in kde.komorebi_log()), + "Escape goes back to the default mode, and gives the keys of the mode back", + kde.wait_for(lambda: "the mode is now default" in kde.komorebi_log()) and in_mode("default"), ) keys.send("h") checks.check("back in the default mode H reaches the window again", reaches_wev("h", 2)) -kde.komorebic("stop") +stop() # chord chains: the prefix grabs the keys that can come next, until a key, Escape or the timeout sxhkdrc = "/home/komorebi/.config/komorebi/sxhkdrc" chain = "alt + w ; {h,l}\n touch /tmp/keys-chords-{h,l}\n" kde.sh(f"printf '%s' {shlex.quote(chain)} > {sxhkdrc}") -kde.spawn_komorebi("--log-level", "debug", "--keybindings", sxhkdrc, "--chord-timeout", "1500") +# The timeout is long, and is scaled like every wait, so that the keys of a chain are sent well +# inside it however slowly the machine grabs them, and that Escape can be told from the timeout. +CHORD_TIMEOUT = 3 +kde.spawn_komorebi( + "--log-level", + "debug", + "--keybindings", + sxhkdrc, + "--chord-timeout", + str(int(CHORD_TIMEOUT * 1000 * SCALE)), +) if not kde.wait_for(lambda: "keys in kglobalaccel" in kde.komorebi_log(), timeout=60): raise AssertionError(f"the keys were not registered:\n{kde.komorebi_log()}") + + +def chain_begins() -> None: + """Presses Alt+W and waits until the engine has grabbed the keys that can come next. + + A key pressed before that goes to the window, not to the chain. + """ + keys.send("alt-w") + if not chain_is(True): + raise AssertionError(f"Alt+W did not begin the chain ({engine()}):\n{kde.komorebi_log()}") + + +def chain_ends() -> None: + """Waits until the chain is over and the engine holds Alt+W again, which a key pressed + before that would not find.""" + if not chain_is(False): + raise AssertionError(f"the chain did not end ({engine()}):\n{kde.komorebi_log()}") + + h_before = typed("h") -keys.send("alt-w") +chain_begins() checks.check("Alt+W, H runs the binding of the chain", press("h", "keys-chords-h")) checks.check("the H of the chain does not reach the window", typed("h") == h_before) -keys.send("alt-w") +chain_ends() +chain_begins() keys.send("esc") +checks.check( + "Escape ends the chain, which the timeout has not yet done", + chain_is(False, within=CHORD_TIMEOUT / 2), +) keys.send("h") checks.check("after Alt+W, Escape, H reaches the window", reaches_wev("h", h_before + 1)) -keys.send("alt-w") -time.sleep(2 * SCALE) +chain_begins() +checks.check("the chain ends at its timeout", chain_is(False, within=CHORD_TIMEOUT + 1)) keys.send("l") checks.check("after Alt+W and the timeout, L reaches the window", reaches_wev("l", 1)) checks.check("and runs nothing", not ran("keys-chords-l")) -kde.komorebic("stop") +stop() # per-application bindings: a key is grabbed only while the focused application has an action start( @@ -157,16 +241,26 @@ if not kde.wait_for(lambda: kde.wid_by_class("foot") != "", timeout=30): wev, foot = kde.wid_by_class("wev"), kde.wid_by_class("foot") -def focus(wid: str, app_id: str) -> None: - """Activates the window and waits for the engine to see its application take the focus.""" - kde.activate(wid) +def sees_focus(wid: str, app_id: str) -> bool: + """Activates the window and waits for the engine to log that its application has the focus.""" + activate(wid) def seen() -> bool: lines = [x for x in kde.komorebi_log().splitlines() if "the focus is now" in x] return bool(lines) and f"({app_id}, " in lines[-1] - if not kde.wait_for(seen, timeout=10): + return kde.wait_for(seen, timeout=10) + + +def focus(wid: str, app_id: str) -> None: + """Activates the window, and returns once the engine has grabbed the keys that its + application has an action for, and given the others back.""" + if not sees_focus(wid, app_id): raise AssertionError(f"the engine did not see {app_id} take the focus") + # the engine logs the focus before it grabs and gives back the keys of the application, and + # answers once it has: a key pressed before that would find the keys of the other window + if not engine(): + raise AssertionError("the engine does not answer") focus(wev, "wev") @@ -188,6 +282,21 @@ checks.check( focus(wev, "wev") keys.send("alt-g") checks.check("back in wev, Alt+G reaches wev again", reaches_wev("g", g_before + 2)) -kde.komorebic("stop") + +# An engine that starts while the focused application has nothing to grab starts all the same: +# the key bindings are read again with wev focused, and every binding is for the terminal. +write('alt - j [\n "terminal" : touch /tmp/keys-scopes-reload\n]\n') +reads = kde.komorebi_log().count("bindings for the engine") +kde.komorebic("hotkeys", "reload") +kde.wait_for(lambda: kde.komorebi_log().count("bindings for the engine") > reads, timeout=10) +checks.check( + "an engine that starts with nothing to grab goes on to see foot take the focus", + sees_focus(foot, "foot") and bool(engine()), +) +checks.check( + "and in foot, Alt+J runs the terminal's binding", + press("alt-j", "keys-scopes-reload"), +) +stop() checks.finish() diff --git a/nix/tests/vm/suites/restart-survival/default.nix b/nix/tests/vm/suites/restart-survival/default.nix new file mode 100644 index 00000000..91ff32cb --- /dev/null +++ b/nix/tests/vm/suites/restart-survival/default.nix @@ -0,0 +1,5 @@ +{ + tier = "slow"; + kind = "session"; + timeoutMinutes = 15; +} diff --git a/nix/tests/vm/suites/restart-survival/test.py b/nix/tests/vm/suites/restart-survival/test.py new file mode 100644 index 00000000..263084d2 --- /dev/null +++ b/nix/tests/vm/suites/restart-survival/test.py @@ -0,0 +1,119 @@ +# The keys of the engine survive the daemon and KWin going away. kglobalaccel keeps the keys of a +# client that died, swallowed and running nothing, until they are unregistered; and it runs inside +# KWin, so a KWin that restarts forgets them. Only a real session can say that the module's unit +# releases the keys of a daemon that was killed, that a new daemon takes them over, and that the +# daemon registers them again with the kglobalaccel of a new KWin. +import json +import shlex + +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 presses() -> int: + """How many times a binding has run.""" + return len(machine.execute("cat /tmp/keys-restart")[1].split()) + + +def press(combo: str) -> bool: + before = presses() + keys.send(combo) + return kde.wait_for(lambda: presses() > before, timeout=10) + + +def registered(actions: list[str], timeout: float = 30) -> bool: + return kde.wait_for(lambda: kde.shortcut_actions() == actions, timeout=timeout) + + +def write(skhdrc: str) -> None: + kde.sh( + f"mkdir -p ~/.config/komorebi && printf '%s' {shlex.quote(skhdrc)}" + " > ~/.config/komorebi/skhdrc" + ) + + +def main_pid() -> str: + return kde.systemctl("show", "--property=MainPID", "--value", "komorebi.service").strip() + + +# the module's unit runs the daemon, which reads the skhdrc of the config directory at start +write("alt - h : echo h >> /tmp/keys-restart\n") +kde.systemctl("restart", "komorebi.service") +checks.check("the daemon of the unit registers Alt+H", registered(["Alt+H"])) +checks.check("Alt+H runs its binding", press("alt-h")) + +state = json.loads(kde.komorebic("hotkeys", "state")) +checks.check( + f"hotkeys state shows the key and the engine ({state})", + state["registered"] == ["Alt+H"] + and state["engine"]["mode"] == "default" + and state["engine"]["active"] == ["Alt+H"], +) + +# a daemon that does not answer leaves its keys dead, until they are released +machine.succeed("pkill -STOP -x komorebi") +before = presses() +keys.send("alt-h") +checks.check( + "the key of a stopped daemon runs nothing", + not kde.wait_for(lambda: presses() > before, timeout=3), +) +released = kde.komorebic("hotkeys", "release") +checks.check(f"hotkeys release unregisters it ({released.strip()})", "Alt+H" in released) +checks.check("no key is registered after the release", kde.shortcut_actions() == []) +machine.succeed("pkill -CONT -x komorebi") +kde.systemctl("restart", "komorebi.service") +checks.check("a new daemon registers the key again", registered(["Alt+H"])) +checks.check("Alt+H runs its binding again", press("alt-h")) + +# a daemon that is killed: the unit releases its keys, and systemd starts a new one +old = main_pid() +# the main process alone, as a crash: killing the whole unit would kill ExecStopPost too +kde.systemctl("kill", "--kill-whom=main", "--signal=SIGKILL", "komorebi.service") +checks.check( + "systemd starts the daemon again", + kde.wait_for(lambda: main_pid() not in ("0", old), timeout=30), +) + + +def journal() -> str: + """The journal of the machine since it booted: the unit's lines, ExecStopPost's among them.""" + return machine.execute("journalctl --no-pager -o cat -b")[1] + + +released = kde.wait_for(lambda: "released 1 keys: Alt+H" in journal(), timeout=10) +words = ("released", "had no key", "could not release", "komorebi.service") +seen = [line for line in journal().splitlines() if any(word in line for word in words)] +checks.check(f"the unit released the keys of the killed daemon (it logged {seen[-6:]})", released) +checks.check("the new daemon has the key", registered(["Alt+H"])) +checks.check("Alt+H runs its binding after the kill", press("alt-h")) + +# KWin restarts, and kglobalaccel with it +kwins = machine.succeed("pgrep -a kwin_wayland || true") +print(kwins) +compositors = [ + line.split()[0] + for line in kwins.splitlines() + if line.strip() and "wrapper" not in line.split()[1] +] +machine.succeed(f"kill -KILL {' '.join(compositors)}") +checks.check( + "a new KWin owns kglobalaccel", + kde.wait_for(lambda: kde.has_name("org.kde.kglobalaccel"), timeout=60), +) +checks.check("the daemon registers the key with the new KWin", registered(["Alt+H"], timeout=60)) +checks.check("Alt+H runs its binding after KWin restarted", press("alt-h")) + +# a reload reads the file again +write("alt - j : echo j >> /tmp/keys-restart\n") +kde.komorebic("hotkeys", "reload") +checks.check("after a reload the daemon has the key of the new file", registered(["Alt+J"])) +checks.check("Alt+J runs its binding", press("alt-j")) + +checks.finish()