From 47d3a471d7429e1e2f308ce1ee792b20e70c987b Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 16:31:39 -0700 Subject: [PATCH] feat(kwin): per-application key bindings follow the focus skhd and whkd can give one key a different action in each application, or none (skhd's ~, whkd's Ignore), and skhd has a blacklist of applications in which no key is taken. The engine decides from the focused application whether such a key is active: inactive, it reaches the application, which is how a key passes through. What it needs is to be told which application has the focus. The bridge reports the desktop entry of every window with its class, and the table now keeps it. Table::focused_application returns the executable, the app id (or X11 class) and the desktop entry of the window KWin activated last, a dialog included, or nothing once that window is gone. The KWin backend hands it to kwin::hotkeys::focus after every event of the bridge; only a change reaches the engine's thread, and an engine that starts begins with the focus as it was last seen. The engine matches the names of the file against the three, ignoring case. The names in an skhdrc or a whkdrc are those of macOS and Windows applications, so the daemon takes --app-alias NAME=ALIAS[,ALIAS]..., more than once, for the engine's app_aliases. Unit tests cover the focus of the table and the calls of a scoped key as the focus moves, an alias included. The VM test vm-keys-engine grows a section with wev and foot open and --app-alias terminal=foot: in wev, Alt+G (for the terminal only) and Alt+N (which wev ignores) reach wev and run nothing; in foot both run their bindings; back in wev, Alt+G reaches wev again. --- docs/dev/ARCHITECTURE.md | 7 ++ docs/usage/running-komorebi.md | 11 ++++ komorebi/src/kwin/hotkeys.rs | 87 ++++++++++++++++++++++++- komorebi/src/kwin/mod.rs | 12 +++- komorebi/src/kwin/state.rs | 45 +++++++++++++ komorebi/src/main.rs | 53 ++++++++++++++- nix/tests/vm/suites/keys-engine/test.py | 50 +++++++++++++- 7 files changed, 258 insertions(+), 7 deletions(-) diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index deac0509..0f3a4dc9 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -1678,6 +1678,11 @@ plan needs no engine. A failure to start is logged, and the window manager runs 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. +- **Focus**: after every event of the bridge, the KWin backend gives the engine the + application of the window KWin activated (`Table::focused_application`: its executable, app id + and desktop entry), and a change makes the engine grab the keys of the bindings that do + something there and let the others go. The aliases of `--app-alias` are names of an + application too. - **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. @@ -1717,6 +1722,8 @@ plan needs no engine. A failure to start is logged, and the window manager runs | 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 | +| 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 | | 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 182d41b3..b264a7cb 100644 --- a/docs/usage/running-komorebi.md +++ b/docs/usage/running-komorebi.md @@ -88,6 +88,17 @@ of an sxhkdrc (`alt + w ; h`) works the same way: after `alt + w`, only the keys 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 binding that does something else in each application (skhd's `[ ... ]` list, whkd's +per-application list) takes its key only while an application it names has the focus, or +any application for a `*` or `Default` entry; everywhere else the key reaches the application. +A name matches the executable, the Wayland app id (`org.kde.konsole`) or the desktop entry of +the focused window, whatever the case. skhd and whkd name applications as macOS and Windows +do, so give the daemon the names they have on KDE: + +```sh +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. diff --git a/komorebi/src/kwin/hotkeys.rs b/komorebi/src/kwin/hotkeys.rs index 2f2444a3..520382b2 100644 --- a/komorebi/src/kwin/hotkeys.rs +++ b/komorebi/src/kwin/hotkeys.rs @@ -46,6 +46,17 @@ //! 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`). //! +//! # Per-application bindings +//! +//! A binding that does something else in each application (a scope) is grabbed only while the +//! focused application has an action for it, so that elsewhere the key reaches the application. +//! The KWin backend tells the engine which application has the focus ([`focus`]) after every +//! event of the bridge that changes it: the executable, the Wayland app id (or X11 class) and +//! the desktop entry of the window KWin activated, a dialog included. The engine matches a name +//! of the key binding file against each of the three, ignoring case, and against the aliases +//! the daemon is given (`--app-alias`). skhd's blacklist works the same way: while a +//! blacklisted application has the focus, every key is let go. +//! //! # Start and stop //! //! kglobalaccel keeps an action, and the grab of its key, until it is unregistered: a komorebi @@ -66,6 +77,7 @@ use komorebi_hotkeys::Keymap; use komorebi_hotkeys::engine::Effect; use komorebi_hotkeys::engine::Engine; use komorebi_hotkeys::engine::EngineOptions; +use komorebi_hotkeys::engine::Focus; use komorebi_hotkeys::qt::Combo; use komorebi_hotkeys::qt::Key; use komorebi_hotkeys::qt::Mods; @@ -363,9 +375,31 @@ fn spawn(effect: &Effect) { /// What the thread of the keys is told enum Message { + Focus(Option), Stop(std::sync::mpsc::Sender<()>), } +/// The application that has the focus, as [`focus`] was last told +static FOCUS: Mutex> = Mutex::new(None); + +/// Tells the engine which application has the focus, `None` for none. +/// +/// The KWin backend calls this after every event of the bridge; only a change reaches the engine, +/// which then grabs the keys of the bindings that do something in that application and lets the +/// others go. The focus is remembered when no engine runs, and an engine that starts begins with +/// it. +pub fn focus(focus: Option) { + let mut last = FOCUS.lock(); + if *last == focus { + return; + } + *last = focus.clone(); + drop(last); + if let Some(messages) = RUNNING.lock().as_ref() { + let _ = messages.send(Message::Focus(focus)); + } +} + /// The engine that runs, if one does: the way to its thread (`kwin-hotkeys`) static RUNNING: Mutex>> = Mutex::new(None); @@ -427,6 +461,8 @@ pub fn start(keymap: Keymap, options: EngineOptions) -> eyre::Result<()> { wait.recv() .map_err(|_| eyre::Report::msg("the thread of the keys exited before starting"))??; + // a change of focus while the engine was starting reached no engine + let _ = messages.send(Message::Focus(FOCUS.lock().clone())); *RUNNING.lock() = Some(messages); Ok(()) } @@ -513,6 +549,8 @@ async fn serve( let known = combos(&keymap); let mut engine = Engine::new(keymap, options); let mut registry = Registry::default(); + // 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(""),)) @@ -521,7 +559,7 @@ async fn serve( .into_iter() .filter_map(|id| id.get(1).cloned()) .collect(); - let start = engine.start(); + start.extend(engine.start()); let calls = registry.startup(&existing, &known, &start); let registered = calls.iter().filter(|c| matches!(c, Call::Grab(_))).count(); execute(&kglobalaccel, calls).await; @@ -572,6 +610,18 @@ async fn serve( } () = until(engine.deadline()) => engine.on_tick(Instant::now()), message = messages.recv() => match message { + Some(Message::Focus(focus)) => { + match &focus { + Some(focus) => tracing::debug!( + "key bindings: the focus is now {} ({}, {})", + focus.exe, + focus.app_id, + focus.desktop_entry + ), + None => tracing::debug!("key bindings: nothing has the focus"), + } + engine.on_focus(focus) + } Some(Message::Stop(done)) => { let mut calls = registry.calls(&engine.stop()); calls.extend(registry.unregister_all()); @@ -760,6 +810,41 @@ mod tests { ); } + #[test] + fn a_scoped_key_is_grabbed_only_while_its_application_has_the_focus() { + let keymap = keymap("alt - g [\n \"foot\" : echo foot\n]\nalt - h : echo h\n"); + let known = combos(&keymap); + let options = EngineOptions { + app_aliases: BTreeMap::from([("foot".into(), vec!["footclient".into()])]), + ..EngineOptions::default() + }; + let mut engine = Engine::new(keymap, options); + let mut registry = Registry::default(); + let alt_g = known["Alt+G"]; + let focus = |name: &str| { + Some(Focus { + app_id: name.into(), + ..Focus::default() + }) + }; + + // nothing has the focus: only the binding that is for every application is grabbed + let calls = registry.startup(&[], &known, &engine.start()); + assert!(!calls.contains(&Call::Grab(alt_g)), "{calls:?}"); + + let calls = registry.calls(&engine.on_focus(focus("Foot"))); + assert_eq!(calls, [Call::Register(alt_g), Call::Grab(alt_g)]); + let calls = registry.calls(&engine.on_focus(focus("wev"))); + assert_eq!(calls, [Call::Release(alt_g)]); + // an alias is the application too + let calls = registry.calls(&engine.on_focus(focus("footclient"))); + assert_eq!(calls, [Call::Grab(alt_g)]); + assert_eq!( + engine.on_pressed(alt_g, Instant::now()), + [Effect::Shell("echo foot".into())] + ); + } + #[test] fn a_press_runs_the_command_and_changes_no_key() { let keymap = keymap("alt - h : komorebic retile\n"); diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index f487e943..d6762a7c 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -59,7 +59,9 @@ //! under it) is found in the first snapshot, its windows are sent home and it is removed. //! //! The engine of the key bindings reaches KWin's global shortcut daemon in [`hotkeys`], on a -//! connection and a thread of its own. +//! connection and a thread of its own. After each event of the bridge, the backend tells it +//! which application has the focus ([`hotkeys::focus`], from +//! [`state::Table::focused_application`]). //! //! [`WorkspaceChange`]: crate::window_manager_event::WindowManagerEvent::WorkspaceChange //! [`WorkspaceMove`]: crate::window_manager_event::WindowManagerEvent::WorkspaceMove @@ -234,8 +236,14 @@ impl Events { }; let is_snapshot = value["type"] == "snapshot"; - let outputs = self.shared.table.lock().handle(&value, Instant::now()); + let (outputs, focus) = { + let mut table = self.shared.table.lock(); + let outputs = table.handle(&value, Instant::now()); + (outputs, table.focused_application()) + }; self.shared.dispatch(outputs); + // the key bindings that are for one application follow the focus + hotkeys::focus(focus); if is_snapshot { self.shared.mark_ready(); diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index 39841417..8a28d7db 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -73,6 +73,7 @@ use crate::window::Window; use crate::window_manager_event::KWinNotification; use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; +use komorebi_hotkeys::engine::Focus; use serde_json::Value; use serde_json::json; use std::collections::HashMap; @@ -97,6 +98,8 @@ enum Drag { struct Entry { uuid: String, info: WindowInfo, + /// The name of the window's desktop entry, without `.desktop`, as KWin says + desktop_file: String, /// What KWin says: a normal window, as opposed to a dialog, splash, panel, popup... kwin_normal: bool, desktops: Vec, @@ -279,6 +282,20 @@ impl Table { .filter(|id| self.windows.get(id).is_some_and(|e| e.info.alive)) } + /// Returns the application of the window that has the focus, as key bindings name + /// applications, or `None` when no window that is open has the focus. + /// + /// The window can be one komorebi does not manage, such as a dialog: a key binding for an + /// application is for its dialogs too. + pub fn focused_application(&self) -> Option { + let entry = self.windows.get(&self.foreground()?)?; + Some(Focus { + exe: entry.info.exe.clone(), + app_id: entry.info.class.clone(), + desktop_entry: entry.desktop_file.clone(), + }) + } + /// Returns where the pointer was the last time the script said. pub fn cursor(&self) -> Option<(i32, i32)> { self.cursor @@ -619,6 +636,7 @@ impl Table { let entry = Entry { uuid, info, + desktop_file: w["desktopFile"].as_str().unwrap_or_default().to_string(), kwin_normal: w["normal"].as_bool().unwrap_or(false), desktops: strings(&w["desktops"]), drag: None, @@ -1548,6 +1566,33 @@ mod tests { assert_eq!(t.current_workspaces(), vec![(t.monitors()[0].id, 0)]); } + #[test] + fn the_focused_application_is_the_one_of_the_window_kwin_activated() { + let mut dialog = win("b", &["d1"]); + dialog["normal"] = json!(false); + dialog["desktopFile"] = json!("org.codeberg.dnkl.foot"); + let mut t = table(vec![win("a", &["d1"]), dialog]); + assert_eq!(t.focused_application(), None); + + // a dialog is its application's too + t.handle(&json!({ "type": "activated", "id": "b" }), Instant::now()); + assert_eq!( + t.focused_application(), + Some(Focus { + // pid 0 has no executable to read: the class stands in for it + exe: "foot".into(), + app_id: "foot".into(), + desktop_entry: "org.codeberg.dnkl.foot".into(), + }) + ); + + t.handle(&json!({ "type": "activated", "id": null }), Instant::now()); + assert_eq!(t.focused_application(), None); + t.handle(&json!({ "type": "activated", "id": "b" }), Instant::now()); + t.handle(&json!({ "type": "removed", "id": "b" }), Instant::now()); + assert_eq!(t.focused_application(), None); + } + #[test] fn monitors_get_a_stable_identity_from_the_serial_not_the_port() { let t = table(vec![]); diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 9ced8169..a8e40679 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -22,7 +22,8 @@ //! 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. +//! 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. @@ -55,6 +56,7 @@ use komorebi_hotkeys::plan::PlanMode; use komorebi_hotkeys::plan::PlanOptions; use parking_lot::Mutex; use serde::Deserialize; +use std::collections::BTreeMap; use std::net::Shutdown; use std::os::unix::net::UnixStream; use std::path::PathBuf; @@ -244,6 +246,27 @@ struct Opts { /// 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, + /// Other names of an application, for the bindings of the key binding file that are for one + /// application: `--app-alias firefox=firefox-esr,librewolf` makes a binding for firefox work + /// in either of the two. May be given more than once + #[clap(long, value_name = "NAME=ALIAS[,ALIAS]...", value_parser = app_alias)] + app_alias: Vec<(String, Vec)>, +} + +/// Reads `NAME=ALIAS[,ALIAS]...`, for `--app-alias` +fn app_alias(value: &str) -> Result<(String, Vec), String> { + let refused = || format!("{value:?} is not NAME=ALIAS[,ALIAS]..."); + let (name, aliases) = value.split_once('=').ok_or_else(refused)?; + let aliases: Vec = aliases + .split(',') + .map(str::trim) + .filter(|alias| !alias.is_empty()) + .map(String::from) + .collect(); + if name.trim().is_empty() || aliases.is_empty() { + return Err(refused()); + } + Ok((name.trim().to_string(), aliases)) } /// Reads the key binding file, and starts the engine for the bindings that are not static @@ -308,9 +331,16 @@ fn keybindings(opts: &Opts) -> eyre::Result<()> { 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), - ..EngineOptions::default() + app_aliases, }; if plan.needs_engine() && let Err(error) = komorebi::kwin::hotkeys::start(plan.engine, options) @@ -432,3 +462,22 @@ fn main() -> eyre::Result<()> { std::process::exit(130); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_app_alias_is_a_name_and_its_other_names() { + assert_eq!( + app_alias("firefox=firefox-esr, librewolf"), + Ok(( + "firefox".to_string(), + vec!["firefox-esr".to_string(), "librewolf".to_string()] + )) + ); + assert!(app_alias("firefox").is_err()); + assert!(app_alias("firefox=").is_err()); + assert!(app_alias("=librewolf").is_err()); + } +} diff --git a/nix/tests/vm/suites/keys-engine/test.py b/nix/tests/vm/suites/keys-engine/test.py index 0dee07c5..de58438a 100644 --- a/nix/tests/vm/suites/keys-engine/test.py +++ b/nix/tests/vm/suites/keys-engine/test.py @@ -25,12 +25,12 @@ def press(combo: str, marker: str) -> bool: return kde.wait_for(lambda: ran(marker), timeout=10) -def start(skhdrc: str) -> None: +def start(skhdrc: str, *args: str) -> None: kde.sh( f"mkdir -p ~/.config/komorebi && printf '%s' {shlex.quote(skhdrc)} > ~/.config/komorebi/skhdrc" ) # no --keybindings: the daemon finds the skhdrc in the config directory - kde.spawn_komorebi("--log-level", "debug") + 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()}") @@ -144,4 +144,50 @@ checks.check("after Alt+W and the timeout, L reaches the window", reaches_wev("l checks.check("and runs nothing", not ran("keys-chords-l")) kde.komorebic("stop") +# per-application bindings: a key is grabbed only while the focused application has an action +start( + 'alt - g [\n "terminal" : touch /tmp/keys-scopes-terminal\n]\n' + 'alt - n [\n "wev" ~\n * : touch /tmp/keys-scopes-other\n]\n', + "--app-alias", + "terminal=foot", +) +kde.spawn("foot") +if not kde.wait_for(lambda: kde.wid_by_class("foot") != "", timeout=30): + raise AssertionError("foot did not open") +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 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): + raise AssertionError(f"the engine did not see {app_id} take the focus") + + +focus(wev, "wev") +g_before, n_before = typed("g"), typed("n") +keys.send("alt-g") +checks.check("in wev, Alt+G (for the terminal only) reaches wev", reaches_wev("g", g_before + 1)) +keys.send("alt-n") +checks.check("in wev, Alt+N (which wev ignores) reaches wev", reaches_wev("n", n_before + 1)) +checks.check("and runs nothing", not ran("keys-scopes-other")) +focus(foot, "foot") +checks.check( + "in foot, Alt+G runs the terminal's binding, by the alias", + press("alt-g", "keys-scopes-terminal"), +) +checks.check( + "in foot, Alt+N runs the binding for every other application", + press("alt-n", "keys-scopes-other"), +) +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") + checks.finish()