From 260d8ff03ebe757184c1049e8e55257839327b90 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 16:28:23 -0700 Subject: [PATCH] feat(kwin): end a chord chain at its timeout An sxhkd chain (alt + w ; h) is realized by the engine: after the prefix only the keys that can come next and Escape are grabbed, because KWin 6.8's own key sequences never fire. What ends a chain that nobody finishes is the chord timeout, and the engine has no clock: it is told the time with on_tick. Rather than ticking on a timer forever, the engine now says when its pending chain times out (Engine::deadline, in komorebi-hotkeys) and the transport sleeps until then, calls on_tick, and grabs the keys of the mode again. With no chain pending it does not wake up at all. The daemon takes --chord-timeout in milliseconds, 3000 by default, the engine's default and the module's chordTimeout to come. A unit test follows the calls of a chain from its prefix to its deadline. The VM test vm-keys-engine grows a section with an sxhkdrc passed as --keybindings and a timeout of 1.5 s: Alt+W, H runs the binding and H does not reach wev; Alt+W, Escape lets the next H reach wev; Alt+W and two seconds later L reaches wev and runs nothing. --- docs/dev/ARCHITECTURE.md | 5 ++ docs/usage/running-komorebi.md | 5 +- komorebi-hotkeys/src/engine.rs | 38 ++++++++++++- komorebi/src/kwin/hotkeys.rs | 73 +++++++++++++++++++++++++ komorebi/src/main.rs | 13 ++++- nix/tests/vm/suites/keys-engine/test.py | 23 ++++++++ 6 files changed, 153 insertions(+), 4 deletions(-) diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 4237ff79..deac0509 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -1674,6 +1674,10 @@ plan needs no engine. A failure to start is logged, and the window manager runs daemon does not wait for. - **Modes**: a mode switch is the engine's deactivations and activations, carried out like any others; the daemon logs the mode after each change. +- **Chord chains**: after the prefix of a chain, only the keys that can come next and Escape + are grabbed. The transport sleeps until `Engine::deadline` (the chord timeout after the last + combo of the chain, `--chord-timeout`, 3 seconds by default) and calls `Engine::on_tick` + then, which abandons the chain; there is no timer otherwise. - **Start**: the component's actions that the keymap names are taken over, and released unless the default mode wants them; the others are unregistered. The engine starts in the default mode. @@ -1712,6 +1716,7 @@ plan needs no engine. A failure to start is logged, and the window manager runs | A stop of the daemon unregisters every action | framework path: `KWinBackend::shutdown` calls `kwin::hotkeys::stop`, and both ways to stop call it; VM test | `vm-keys-engine` (`komorebic stop`) | `SIGKILL` leaves the keys until the next start | | A press of a grabbed key runs its binding's command, `komorebic` without a shell where it needs none | test, of the process; VM test | `command` doctest, `a_press_runs_the_command_and_changes_no_key`, `vm-keys-engine` | none | | Entering a mode lets go of the keys of the mode it leaves and grabs its own, a bare key among them | test, of the calls; VM test | `entering_a_mode_lets_the_keys_of_the_other_go_and_grabs_its_own`, `vm-keys-engine` | none | +| 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 | | 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 diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md index 142fb149..182d41b3 100644 --- a/docs/usage/running-komorebi.md +++ b/docs/usage/running-komorebi.md @@ -83,7 +83,10 @@ komorebic start -- --keybindings-mode auto The daemon realizes the modes of an skhdrc (and the chains of an sxhkdrc that stay open) itself: while a mode is active, only its keys are taken, and every other key reaches the -window as usual. The log says which mode the daemon is in after each change. +window as usual. The log says which mode the daemon is in after each change. A chord chain +of an sxhkdrc (`alt + w ; h`) works the same way: after `alt + w`, only the keys that can +come next and Escape are taken, until one of them is pressed or 3 seconds pass +(`--chord-timeout 1500` waits 1.5 seconds instead). A daemon that is killed leaves its keys swallowed until it is started again; `komorebic stop` gives them back. diff --git a/komorebi-hotkeys/src/engine.rs b/komorebi-hotkeys/src/engine.rs index 878edcd3..c262f178 100644 --- a/komorebi-hotkeys/src/engine.rs +++ b/komorebi-hotkeys/src/engine.rs @@ -59,7 +59,8 @@ //! active. //! - **Chord chains**: the first combo of a chain is an active key. When it is pressed, only the //! combos that can come next, and Escape, are active, until one of them is pressed or the chord -//! timeout ([`EngineOptions::chord_timeout`]) passes, which [`Engine::on_tick`] checks. Escape, +//! timeout ([`EngineOptions::chord_timeout`]) passes, which [`Engine::on_tick`] checks +//! ([`Engine::deadline`] says when it passes). Escape, //! unless a chain is bound to it, abandons the chain. A key that is not the next of the chain is //! not active, so it reaches the application and does not end the chain. //! - **Per-application bindings**: a scoped binding's key is active if and only if a [`Scope`] @@ -222,6 +223,41 @@ impl Engine { .map_or(DEFAULT_MODE, |mode| mode.name.as_str()) } + /// Returns when the chord chain being typed times out, or `None` when no chain is pending. + /// + /// [`Engine::on_tick`] at that instant or later abandons the chain, so a caller can sleep + /// until then instead of calling it on a timer. Each combo of the chain that is pressed + /// moves the deadline. + /// + /// # Example + /// + /// ```rust + /// use std::time::{Duration, Instant}; + /// use komorebi_hotkeys::engine::{Engine, EngineOptions}; + /// use komorebi_hotkeys::qt::{Combo, Key, Mods, key_to_qt}; + /// use komorebi_hotkeys::{Format, ParseOptions, parse}; + /// + /// let text = "super + w ; h\n komorebic focus left\n"; + /// let keymap = parse(Format::Sxhkd, text, &ParseOptions::default()).keymap; + /// let mut engine = Engine::new(keymap, EngineOptions::default()); + /// engine.start(); + /// assert_eq!(engine.deadline(), None); + /// + /// let start = Instant::now(); + /// let super_w = Combo::new(Mods::META, key_to_qt(Format::Sxhkd, "w").unwrap()); + /// engine.on_pressed(super_w, start); + /// assert_eq!(engine.deadline(), Some(start + Duration::from_millis(3000))); + /// + /// engine.on_tick(start + Duration::from_millis(3000)); + /// assert_eq!(engine.deadline(), None); + /// assert!(engine.active().all(|combo| combo.key() != Key::ESCAPE)); + /// ``` + pub fn deadline(&self) -> Option { + self.pending + .as_ref() + .map(|pending| pending.since + self.options.chord_timeout) + } + /// Returns the combos that are active, in order. pub fn active(&self) -> impl Iterator + '_ { self.active.iter().copied() diff --git a/komorebi/src/kwin/hotkeys.rs b/komorebi/src/kwin/hotkeys.rs index c05c3a59..2f2444a3 100644 --- a/komorebi/src/kwin/hotkeys.rs +++ b/komorebi/src/kwin/hotkeys.rs @@ -36,6 +36,16 @@ //! the engine is in. A start puts the engine in the default mode, whatever mode an earlier //! komorebi was in. //! +//! # Chord chains +//! +//! The first combo of a chain is a key like any other. When it is pressed, the engine lets go +//! of every key but those that can come next and Escape, and the transport sleeps until the +//! chain's [deadline](Engine::deadline), the chord timeout after the last combo of the chain: +//! then [`Engine::on_tick`] abandons the chain and the keys of the mode are grabbed again. A key +//! that is not the next of the chain is not grabbed, so it reaches the focused window and the +//! chain goes on until the timeout. kglobalaccel's own key sequences are not used: they do not +//! fire on KWin 6.8 (`docs/dev/PLATFORM.md`). +//! //! # Start and stop //! //! kglobalaccel keeps an action, and the grab of its key, until it is unregistered: a komorebi @@ -430,6 +440,14 @@ fn action_id(action: &str) -> Vec { ] } +/// Returns at `deadline`, or never +async fn until(deadline: Option) { + match deadline { + Some(deadline) => tokio::time::sleep_until(deadline.into()).await, + None => std::future::pending().await, + } +} + /// Sends the calls, those of different actions without waiting for each other async fn execute(kglobalaccel: &Proxy<'_>, calls: Vec) { let mut by_action: BTreeMap> = BTreeMap::new(); @@ -552,6 +570,7 @@ async fn serve( _ => continue, } } + () = until(engine.deadline()) => engine.on_tick(Instant::now()), message = messages.recv() => match message { Some(Message::Stop(done)) => { let mut calls = registry.calls(&engine.stop()); @@ -687,6 +706,60 @@ mod tests { ); } + #[test] + fn a_chain_grabs_its_next_keys_until_its_deadline() { + let keymap = parse( + Format::Sxhkd, + "alt + w ; h\n komorebic focus left\nalt + q\n komorebic close\n", + &ParseOptions::default(), + ) + .keymap; + let known = combos(&keymap); + let options = EngineOptions { + chord_timeout: Duration::from_millis(1500), + ..EngineOptions::default() + }; + let mut engine = Engine::new(keymap, options); + let mut registry = Registry::default(); + registry.startup(&[], &known, &engine.start()); + let (alt_q, alt_w, h, escape) = (known["Alt+Q"], known["Alt+W"], known["H"], known["Esc"]); + let start = Instant::now(); + + let effects = engine.on_pressed(alt_w, start); + + assert_eq!( + registry.calls(&effects), + [ + Call::Release(alt_q), + Call::Release(alt_w), + Call::Register(h), + Call::Grab(h), + Call::Register(escape), + Call::Grab(escape), + ] + ); + let deadline = engine.deadline().unwrap(); + assert_eq!(deadline, start + Duration::from_millis(1500)); + assert!( + engine + .on_tick(deadline - Duration::from_millis(1)) + .is_empty() + ); + + let effects = engine.on_tick(deadline); + + assert_eq!(engine.deadline(), None); + assert_eq!( + registry.calls(&effects), + [ + Call::Release(h), + Call::Release(escape), + Call::Grab(alt_q), + Call::Grab(alt_w), + ] + ); + } + #[test] fn a_press_runs_the_command_and_changes_no_key() { let keymap = keymap("alt - h : komorebic retile\n"); diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index deddb9d5..9ced8169 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -21,7 +21,8 @@ //! 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. +//! static shortcuts in. `--chord-timeout` is how long the next key of a chord chain is waited +//! for. //! //! It logs to standard output and to a file a day in [`struct@LOG_DIR`], which `komorebic log` //! follows. @@ -58,6 +59,7 @@ use std::net::Shutdown; use std::os::unix::net::UnixStream; use std::path::PathBuf; use std::sync::Arc; +use std::time::Duration; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::EnvFilter; use tracing_subscriber::layer::SubscriberExt; @@ -239,6 +241,9 @@ struct Opts { /// the same mode does not write as static shortcuts #[clap(long, value_enum, default_value_t = PlanMode::default().into())] keybindings_mode: KeyPlanMode, + /// How long, in milliseconds, the next key of a chord chain is waited for + #[clap(long, default_value_t = EngineOptions::default().chord_timeout.as_millis() as u64)] + chord_timeout: u64, } /// Reads the key binding file, and starts the engine for the bindings that are not static @@ -303,8 +308,12 @@ fn keybindings(opts: &Opts) -> eyre::Result<()> { plan.static_files.len(), diagnostics.count() ); + let options = EngineOptions { + chord_timeout: Duration::from_millis(opts.chord_timeout), + ..EngineOptions::default() + }; if plan.needs_engine() - && let Err(error) = komorebi::kwin::hotkeys::start(plan.engine, EngineOptions::default()) + && let Err(error) = komorebi::kwin::hotkeys::start(plan.engine, options) { tracing::error!("the key bindings are not active: {error}"); } diff --git a/nix/tests/vm/suites/keys-engine/test.py b/nix/tests/vm/suites/keys-engine/test.py index c373f550..0dee07c5 100644 --- a/nix/tests/vm/suites/keys-engine/test.py +++ b/nix/tests/vm/suites/keys-engine/test.py @@ -4,6 +4,7 @@ # that the keys of a killed daemon stay registered until the next start takes them over, and that # a stop gives them back. import shlex +import time from komorebi_vm import Checks, Kde, Keys @@ -121,4 +122,26 @@ keys.send("h") checks.check("back in the default mode H reaches the window again", reaches_wev("h", 2)) kde.komorebic("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") +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()}") +h_before = typed("h") +keys.send("alt-w") +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") +keys.send("esc") +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) +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") + checks.finish()