From 8f5d4a32ef42477df0b66140762577e1290b4090 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 12:35:45 -0700 Subject: [PATCH] feat(hotkeys): plan the bindings and write the plain ones as KDE shortcut files A binding can reach KDE in two ways. A `.desktop` file in a kglobalaccel directory is a static shortcut that KDE runs by itself: it shows in System Settings and survives a dead komorebi, but it is one combo that runs one command. Modes, chord chains, release bindings, per-application bindings, a blacklist and a pause binding need the engine, where komorebi registers the keys and decides what each press does. `plan::plan` sorts a keymap into the two: a binding is static when it is in the default mode, a single combo, unscoped and pressed, in a file with no modes, blacklist or pause binding. Notes say why each other binding goes through the engine. The static shortcut was meant to be the default unless it proved slow, and it did: on KWin 6.8.1 a static shortcut ran its command 233 ms after the key at the median, while the engine heard of it after 3 ms. `PlanMode::Engine` is therefore the default, and `Auto` and `Static` (no engine; what needs it is left out with a warning) stay selectable. `kde` is the skhdrc exporter of the first KDE prototype, moved: the same file names, the same `Exec` quoting for the desktop entry specification (`%%` included), the same `X-KDE-GlobalAccel-CommandShortcut` and `X-KDE-Shortcuts` keys, and `write` and `diff`, which replace the generated files and leave every other file alone. For the sample configuration the files are byte for byte the prototype's; its tests come along, and the corpus test checks that the sample plans into the same 50 files from each format. --- README.md | 5 +- docs/dev/ARCHITECTURE.md | 22 +- docs/dev/DESIGN.md | 24 ++ komorebi-hotkeys/src/kde.rs | 404 ++++++++++++++++++++++++++++ komorebi-hotkeys/src/lib.rs | 32 ++- komorebi-hotkeys/src/plan.rs | 442 +++++++++++++++++++++++++++++++ komorebi-hotkeys/tests/corpus.rs | 44 +++ 7 files changed, 969 insertions(+), 4 deletions(-) create mode 100644 komorebi-hotkeys/src/kde.rs create mode 100644 komorebi-hotkeys/src/plan.rs diff --git a/README.md b/README.md index c1bc9233..31aee9fe 100644 --- a/README.md +++ b/README.md @@ -92,8 +92,9 @@ without a checkout of the toolchain. daemon, reads its answers, subscribes to its notifications, and re-exports the types they are made of. - [`komorebi-hotkeys`](komorebi-hotkeys): reads the key binding files of skhd, - whkd and sxhkd into one model, with the keys as KDE stores them. It does not - depend on the daemon. Its tests read the files in + whkd and sxhkd into one model, with the keys as KDE stores them, and plans + each binding as a KDE shortcut file or as a key komorebi registers itself. It + does not depend on the daemon. Its tests read the files in [`komorebi-hotkeys/tests/fixtures`](komorebi-hotkeys/tests/fixtures), where each case is written in every format that can express it. - [`komorebic`](komorebic): the command line. A subcommand that asks something diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 66b3fd77..b735f301 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -1585,6 +1585,13 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11). its severity (error, warning, note) and how faithfully the construct is realized (exactly, approximated, not at all). - **Parsed**: a file, read: the keymap and the diagnostics. +- **Static shortcut**: a binding KDE realizes from a `.desktop` file, with no komorebi process: + one combo, pressed, the same in every application, in a file without modes, blacklist or pause + binding. +- **Engine**: the part of komorebi that registers keys with KDE and decides what each press does, + for everything a static shortcut cannot be. +- **Plan**: the bindings of a keymap sorted into static shortcuts and the engine's keymap, with + notes on why each binding goes where it goes. ### The parts @@ -1604,6 +1611,13 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11). a chain that stays open (`a : b`) is a mode named after its prefix, entered by the prefix and left by Escape. - [`parse`](../../komorebi-hotkeys/src/lib.rs) picks the reader by format. +- [`plan`](../../komorebi-hotkeys/src/plan.rs): sorts a keymap into static shortcuts and the + engine's keymap, by mode: `Auto` (static where it can be), `Engine` (the default: everything + through the engine) or `Static` (no engine; what needs it is left out with a warning). +- [`kde`](../../komorebi-hotkeys/src/kde.rs): writes static shortcuts as `.desktop` files for + kglobalacceld (`X-KDE-Shortcuts`, `X-KDE-GlobalAccel-CommandShortcut`, an `Exec` line quoted as + the desktop entry specification requires), and replaces the files it wrote before, and no + other. - [`text`](../../komorebi-hotkeys/src/text.rs): what the readers share: line numbers, comments, continued lines and the diagnostics' wording. - [`tests/fixtures`](../../komorebi-hotkeys/tests/fixtures): the corpus, `.skhdrc`, @@ -1620,6 +1634,10 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11). | Text that is left out has a diagnostic that points at it | test | `what_cannot_be_read_is_reported_and_left_out`, `reading_goes_on_after_an_error`, `diagnostics_point_at_the_text_they_are_about` | none | | A fixture reads, without errors, into the keymap of its case | test | `every_file_reads_without_errors_into_the_keymap_of_its_case` | none | | The files of a case read into the same keymap, apart from where each binding was written | test | `the_files_of_a_case_read_into_the_same_keymap` | none | +| A static shortcut is a single combo, pressed, the same in every application, in the default mode of a file with no modes, blacklist or pause binding | test | `a_plain_binding_is_static_and_the_rest_goes_through_the_engine`, `modes_a_blacklist_or_a_pause_binding_send_every_binding_through_the_engine` | `PlanMode::Engine` sends every binding through the engine | +| A rewrite of the shortcut files removes only the files it generated | test | `rewriting_replaces_our_files_and_nothing_else` | none | +| An `Exec` line runs the command as written (quoting, `%%`) | test | `exec_lines_are_quoted_for_the_desktop_entry_spec` | none | +| The sample configuration plans into the same 50 shortcut files from each format | test | `the_sample_plans_into_the_same_shortcut_files_in_every_format` | none | | The whkd reader reads a whkdrc as whkd does | test, on the files it is given | `every_whkdrc_of_the_corpus_reads_as_whkd_reads_it`, `the_example_of_whkds_readme_reads_as_whkd_reads_it` | none | ## Where to look in the code @@ -1800,7 +1818,9 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11). [`komorebi-hotkeys/src/qt.rs`](../../komorebi-hotkeys/src/qt.rs) the keys, and one module per format, [`skhd.rs`](../../komorebi-hotkeys/src/skhd.rs), [`whkd.rs`](../../komorebi-hotkeys/src/whkd.rs) and - [`sxhkd.rs`](../../komorebi-hotkeys/src/sxhkd.rs). + [`sxhkd.rs`](../../komorebi-hotkeys/src/sxhkd.rs); + [`plan.rs`](../../komorebi-hotkeys/src/plan.rs) and [`kde.rs`](../../komorebi-hotkeys/src/kde.rs) + for the shortcuts. - [`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 7b644101..21513f9e 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -722,3 +722,27 @@ recorded; this entry needs one. What is not plain syntax is expanded while the file is read: sxhkd's braces become one binding per alternative, and skhd's `.define` templates and application groups are replaced where they are used, so the model has only expanded bindings in it. + +## Why are some bindings shortcut files, and the others the engine's? + +A KDE global shortcut can be a `.desktop` file that KDE reads by itself. Such a static +shortcut is robust: it shows in System Settings, where it can be changed, and it survives a +komorebi process that has died. But it is one combo that runs one command: it cannot be in a +mode, wait for the second key of a chord, fire on release, or do something else in each +application. So a binding is a static shortcut when it is in the default mode, a single combo, +unscoped and a press binding, and the file declares no modes; everything else goes through +the engine, in which komorebi registers the keys itself and decides what each press does. A +blacklist and a pause binding apply to every binding, so a file with either is the engine's +too. + +## Why does the engine handle every binding by default? + +The plan was to make static shortcuts the default and to switch the default if a static +shortcut turned out to be slow to start its command. It did: on KWin 6.8.1 (in a virtual +machine, on 2026-10-27) a static shortcut ran its command 165 to 436 ms after the key, 233 ms +at the median, while the engine was told of the key 3 ms after it. So the default is +`PlanMode::Engine`, and `PlanMode::Auto` and `PlanMode::Static` stay selectable. + +The cost is the robustness of static shortcuts: the engine works only while komorebi runs, +and a komorebi process that was killed leaves its keys registered and dead until they are +released. diff --git a/komorebi-hotkeys/src/kde.rs b/komorebi-hotkeys/src/kde.rs new file mode 100644 index 00000000..0653a1ff --- /dev/null +++ b/komorebi-hotkeys/src/kde.rs @@ -0,0 +1,404 @@ +//! KDE global shortcuts as `.desktop` files. +//! +//! KDE has a place for "run this command when I press that": a `.desktop` file in a +//! `kglobalaccel` directory (`$XDG_DATA_HOME/kglobalaccel/`, or `share/kglobalaccel/` of a system +//! profile) whose `X-KDE-Shortcuts` key is the default shortcut of its launch action. KWin reads +//! the directory when it starts; the shortcuts then show up, and can be changed, in System +//! Settings, and they work wherever KWin sees the keys, with no komorebi process running. A file +//! added while KWin runs is not read until KWin is asked to register it, and a changed file not +//! until the next session. +//! +//! [`desktop_files`] writes one file per [`Shortcut`]; [`write()`] replaces the files it wrote +//! before with new ones, and [`diff`] says what a [`write()`] would change. Every generated file has +//! the key `X-Komorebi-Generated=true`, and [`write()`] removes no other file. +//! +//! ```rust +//! use komorebi_hotkeys::Format; +//! use komorebi_hotkeys::kde::{Shortcut, desktop_files}; +//! use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; +//! +//! let files = desktop_files(&[Shortcut { +//! combo: Combo::new(Mods::ALT, key_to_qt(Format::Skhd, "h").unwrap()), +//! command: "komorebic focus left".into(), +//! comment: "from the skhdrc: alt - h : komorebic focus left".into(), +//! }]); +//! assert_eq!(files[0].name, "komorebi-focus-left.desktop"); +//! assert!(files[0].content.contains("\nExec=komorebic focus left\n")); +//! assert!(files[0].content.contains("\nX-KDE-Shortcuts=Alt+H\n")); +//! ``` + +use crate::qt::Combo; +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::path::Path; + +/// The key every generated file has, so that a rewrite replaces them and nothing else. +const GENERATED: &str = "X-Komorebi-Generated"; + +/// A command on a key, to be written as a `.desktop` file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Shortcut { + /// The keys. + pub combo: Combo, + /// The command to run. + pub command: String, + /// The file's `Comment`: where the binding came from, as its user wrote it. + pub comment: String, +} + +/// A `.desktop` file: its name in the directory, and its content. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DesktopFile { + /// The file name, `komorebi-.desktop`. + pub name: String, + /// The content. + pub content: String, +} + +/// Returns the files for the shortcuts, with a different name each. +/// +/// A file is named after its command, without a leading `komorebic `: `komorebic focus left` is +/// `komorebi-focus-left.desktop`. When two commands make the same name, the second file is +/// `-2`, the third `-3`, in the order of `shortcuts`. +/// +/// The `Exec` line is the command when it has only letters, digits and ` _./:=,+@-%` in it, and +/// `sh -c ""` otherwise, quoted as the desktop entry specification requires. `%` is a +/// field code there, so it is written `%%`. +/// +/// # Example +/// +/// ```rust +/// use komorebi_hotkeys::Format; +/// use komorebi_hotkeys::kde::{Shortcut, desktop_files}; +/// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; +/// +/// let shortcut = |key, command: &str| Shortcut { +/// combo: Combo::new(Mods::ALT, key_to_qt(Format::Skhd, key).unwrap()), +/// command: command.into(), +/// comment: String::new(), +/// }; +/// let files = desktop_files(&[ +/// shortcut("a", "komorebic retile"), +/// shortcut("b", "komorebic retile"), +/// shortcut("c", "echo $HOME"), +/// ]); +/// assert_eq!(files[0].name, "komorebi-retile.desktop"); +/// assert_eq!(files[1].name, "komorebi-retile-2.desktop"); +/// assert!(files[2].content.contains("\nExec=sh -c \"echo \\\\$HOME\"\n")); +/// ``` +pub fn desktop_files(shortcuts: &[Shortcut]) -> Vec { + let mut used: Vec = Vec::new(); + shortcuts + .iter() + .map(|shortcut| { + let base = format!("komorebi-{}", slug(&shortcut.command)); + let mut stem = base.clone(); + let mut n = 2; + while used.contains(&stem) { + stem = format!("{base}-{n}"); + n += 1; + } + used.push(stem.clone()); + desktop_file(shortcut, &stem) + }) + .collect() +} + +/// `komorebic focus left` -> `focus-left`; anything else is flattened the same way. +fn slug(command: &str) -> String { + let words = command.strip_prefix("komorebic ").unwrap_or(command); + let mut slug = String::new(); + for c in words.chars() { + if c.is_ascii_alphanumeric() { + slug.push(c.to_ascii_lowercase()); + } else if !slug.ends_with('-') && !slug.is_empty() { + slug.push('-'); + } + } + slug.trim_end_matches('-').chars().take(48).collect() +} + +/// A command as an `Exec=` value. The desktop entry spec quotes with `"` and escapes `"`, `` ` ``, +/// `$` and `\` inside them (and then again for the file format), and `%` is a field code. +fn exec_line(command: &str) -> String { + let command = command.replace('%', "%%"); + let plain = command + .chars() + .all(|c| c.is_ascii_alphanumeric() || " _./:=,+@-%".contains(c)); + if plain { + return command; + } + + let mut quoted = String::from("sh -c \""); + for c in command.chars() { + match c { + '"' | '`' | '$' => { + quoted.push_str("\\\\"); + quoted.push(c); + } + '\\' => quoted.push_str("\\\\\\\\"), + c => quoted.push(c), + } + } + quoted.push('"'); + quoted +} + +/// One shortcut as a file. +fn desktop_file(shortcut: &Shortcut, file_stem: &str) -> DesktopFile { + let words = shortcut + .command + .strip_prefix("komorebic ") + .unwrap_or(&shortcut.command); + + let mut content = String::new(); + let _ = writeln!(content, "[Desktop Entry]"); + let _ = writeln!(content, "Type=Application"); + let _ = writeln!(content, "Name=komorebi: {words}"); + let _ = writeln!(content, "Comment={}", shortcut.comment); + let _ = writeln!(content, "Exec={}", exec_line(&shortcut.command)); + let _ = writeln!(content, "Icon=preferences-system-windows"); + let _ = writeln!(content, "Terminal=false"); + let _ = writeln!(content, "StartupNotify=false"); + let _ = writeln!(content, "X-KDE-GlobalAccel-CommandShortcut=true"); + let _ = writeln!(content, "X-KDE-Shortcuts={}", shortcut.combo); + let _ = writeln!(content, "{GENERATED}=true"); + + DesktopFile { + name: format!("{file_stem}.desktop"), + content, + } +} + +/// What a [`write()`] did, or what it would do, by file name. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Written { + /// Files that were not there before. + pub added: Vec, + /// Files that were there, with different content. + pub changed: Vec, + /// Files that were there and are not any more. + pub removed: Vec, + /// Files that are exactly as they were. + pub unchanged: Vec, +} + +/// Returns what [`write()`] would do to `dir`, without doing it. +/// +/// A directory that does not exist has no files, so every file would be added. +/// +/// # Errors +/// +/// Fails when `dir` exists and cannot be listed. A file that cannot be read as text is not a +/// generated one, and is left alone. +pub fn diff(dir: &Path, files: &[DesktopFile]) -> std::io::Result { + let before = if dir.is_dir() { + generated(dir)? + } else { + BTreeMap::new() + }; + Ok(compare(before, files)) +} + +/// Replaces the generated files in `dir` with `files`, leaving every other file alone, and +/// returns what changed. +/// +/// A generated file is one whose name starts with `komorebi-`, ends in `.desktop`, and whose +/// content has `X-Komorebi-Generated=true`. `dir` is created if it does not exist. +/// +/// # Errors +/// +/// Fails when `dir` cannot be created or listed, a generated file cannot be removed, or a new one +/// cannot be written. What was removed or written before the failure stays so. +pub fn write(dir: &Path, files: &[DesktopFile]) -> std::io::Result { + std::fs::create_dir_all(dir)?; + let before = generated(dir)?; + for name in before.keys() { + std::fs::remove_file(dir.join(name))?; + } + for file in files { + std::fs::write(dir.join(&file.name), &file.content)?; + } + Ok(compare(before, files)) +} + +/// The generated files of a directory, by name. +fn generated(dir: &Path) -> std::io::Result> { + let mut found = BTreeMap::new(); + for entry in std::fs::read_dir(dir)? { + let path = entry?.path(); + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); + if !(name.starts_with("komorebi-") && name.ends_with(".desktop")) { + continue; + } + if let Ok(content) = std::fs::read_to_string(&path) + && content.contains(&format!("{GENERATED}=true")) + { + found.insert(name.to_string(), content); + } + } + Ok(found) +} + +fn compare(mut before: BTreeMap, files: &[DesktopFile]) -> Written { + let mut written = Written::default(); + for file in files { + match before.remove(&file.name) { + None => written.added.push(file.name.clone()), + Some(old) if old == file.content => written.unchanged.push(file.name.clone()), + Some(_) => written.changed.push(file.name.clone()), + } + } + written.removed = before.into_keys().collect(); + written +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Format; + use crate::ParseOptions; + use crate::plan::PlanMode; + use crate::plan::PlanOptions; + use crate::plan::plan; + + /// The files for the plain bindings of an skhdrc. + fn files(skhdrc: &str) -> Vec { + let parsed = crate::parse(Format::Skhd, skhdrc, &ParseOptions::default()); + let options = PlanOptions { + mode: PlanMode::Auto, + }; + desktop_files(&plan(&parsed.keymap, &options).static_files) + } + + fn temp_dir(name: &str) -> std::path::PathBuf { + let dir = + std::env::temp_dir().join(format!("komorebi-hotkeys-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + #[test] + fn the_diff_says_what_a_write_would_do_and_does_not_do_it() { + let dir = temp_dir("diff"); + let files = files("alt - h : komorebic focus left\nalt - l : komorebic focus right\n"); + + // nothing there yet + let before = diff(&dir, &files).unwrap(); + assert_eq!(before.added.len(), 2); + assert!(!dir.exists(), "the diff wrote something"); + + write(&dir, &files).unwrap(); + let after = diff(&dir, &files).unwrap(); + assert_eq!(after.unchanged.len(), 2); + assert!(after.added.is_empty() && after.changed.is_empty() && after.removed.is_empty()); + + // one binding gone from the skhdrc, one file of the user's own left alone + std::fs::write(dir.join("mine.desktop"), "[Desktop Entry]\n").unwrap(); + let fewer = diff(&dir, &files[..1]).unwrap(); + assert_eq!(fewer.removed.len(), 1); + assert!(dir.join("mine.desktop").exists()); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn files_have_unique_names_and_the_default_shortcut() { + let files = files("alt - a : komorebic retile\nalt - b : komorebic retile\n"); + assert_eq!(files[0].name, "komorebi-retile.desktop"); + assert_eq!(files[1].name, "komorebi-retile-2.desktop"); + assert!(files[0].content.contains("Exec=komorebic retile\n")); + assert!(files[0].content.contains("X-KDE-Shortcuts=Alt+A\n")); + assert!(files[1].content.contains("X-KDE-Shortcuts=Alt+B\n")); + // kglobalacceld ignores desktop files marked NoDisplay + assert!(!files[0].content.contains("NoDisplay")); + } + + #[test] + fn a_file_is_written_as_kglobalacceld_reads_it() { + let files = files("alt + shift - 0x21 : komorebic cycle-focus previous # 0x21 is [\n"); + assert_eq!( + files[0].content, + "[Desktop Entry]\n\ + Type=Application\n\ + Name=komorebi: cycle-focus previous\n\ + Comment=from the skhdrc: alt + shift - 0x21 : komorebic cycle-focus previous # 0x21 is [\n\ + Exec=komorebic cycle-focus previous\n\ + Icon=preferences-system-windows\n\ + Terminal=false\n\ + StartupNotify=false\n\ + X-KDE-GlobalAccel-CommandShortcut=true\n\ + X-KDE-Shortcuts=Alt+{\n\ + X-Komorebi-Generated=true\n" + ); + } + + #[test] + fn exec_lines_are_quoted_for_the_desktop_entry_spec() { + assert_eq!(exec_line("komorebic focus left"), "komorebic focus left"); + assert_eq!( + exec_line("komorebic focus-workspace 0"), + "komorebic focus-workspace 0" + ); + assert_eq!(exec_line("notify-send 100%"), "notify-send 100%%"); + assert_eq!(exec_line("echo $HOME"), "sh -c \"echo \\\\$HOME\""); + assert_eq!(exec_line("a | b"), "sh -c \"a | b\""); + } + + #[test] + fn slugs_are_short_and_plain() { + assert_eq!(slug("komorebic focus left"), "focus-left"); + assert_eq!(slug("notify-send 'a b'"), "notify-send-a-b"); + assert_eq!(slug(&"x ".repeat(40)).len(), 48); + } + + #[test] + fn rewriting_replaces_our_files_and_nothing_else() { + let dir = temp_dir("rewrite"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("someone-elses.desktop"), + "[Desktop Entry]\nName=x\n", + ) + .unwrap(); + // looks like ours by name, but was not generated + std::fs::write( + dir.join("komorebi-by-hand.desktop"), + "[Desktop Entry]\nName=mine\n", + ) + .unwrap(); + + let first = files("alt - a : komorebic retile\nalt - b : komorebic stop\n"); + let first_run = write(&dir, &first).unwrap(); + assert_eq!(first_run.added.len(), 2); + assert!(first_run.removed.is_empty()); + + // one binding goes, one stays, and one is rebound to another key + let second = files("alt - c : komorebic retile\n"); + let second_run = write(&dir, &second).unwrap(); + assert_eq!(second_run.removed, ["komorebi-stop.desktop"]); + assert_eq!(second_run.changed, ["komorebi-retile.desktop"]); + + let third_run = write(&dir, &second).unwrap(); + assert_eq!(third_run.unchanged, ["komorebi-retile.desktop"]); + assert!(third_run.added.is_empty() && third_run.changed.is_empty()); + + let mut names: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .map(|e| e.unwrap().file_name().into_string().unwrap()) + .collect(); + names.sort(); + assert_eq!( + names, + [ + "komorebi-by-hand.desktop", + "komorebi-retile.desktop", + "someone-elses.desktop" + ] + ); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/komorebi-hotkeys/src/lib.rs b/komorebi-hotkeys/src/lib.rs index 0702363a..9c662307 100644 --- a/komorebi-hotkeys/src/lib.rs +++ b/komorebi-hotkeys/src/lib.rs @@ -1,4 +1,4 @@ -//! One model for the key bindings of skhd, whkd and sxhkd files, with the keys as KDE stores them. +//! Reads the key binding files of skhd, whkd and sxhkd, and plans them as KDE global shortcuts. //! //! skhd (macOS), whkd (Windows) and sxhkd (X11) are hotkey daemons: each reads a file of key //! bindings and runs a command when a combination of keys is pressed. komorebi users keep their @@ -91,10 +91,40 @@ //! assert_eq!(diagnostic.span.line, 2); //! assert_eq!(&text[diagnostic.span.start..diagnostic.span.end], "lalt"); //! ``` +//! +//! # Planning: static shortcuts and the engine +//! +//! KDE can run a command on a key by itself, from a `.desktop` file: a static shortcut, which +//! [`kde`] writes. It works with no komorebi process and shows in System Settings, but it can only +//! be one combo, pressed, the same in every application. Everything else (modes, chord chains, +//! release bindings, per-application bindings, a blacklist, a pause binding) needs komorebi to +//! register the keys and decide what each press does: the engine. [`plan::plan`] sorts a keymap's +//! bindings into the two, by [`plan::PlanMode`]; by default the engine handles all of them. +//! +//! ```rust +//! use komorebi_hotkeys::{Format, ParseOptions, parse}; +//! use komorebi_hotkeys::kde::desktop_files; +//! use komorebi_hotkeys::plan::{PlanMode, PlanOptions, plan}; +//! +//! let parsed = parse(Format::Whkd, "alt + h : komorebic focus left\n", &ParseOptions::default()); +//! let plan = plan(&parsed.keymap, &PlanOptions { mode: PlanMode::Auto }); +//! let files = desktop_files(&plan.static_files); +//! assert_eq!(files[0].name, "komorebi-focus-left.desktop"); +//! assert!(files[0].content.contains("\nX-KDE-Shortcuts=Alt+H\n")); +//! assert!(!plan.needs_engine()); +//! ``` +//! +//! # Diagnostics +//! +//! The diagnostics of reading and of planning say everything that is not realized the way the +//! file's own daemon does it. A front end with a strict option fails when any of them is a +//! warning or an error; notes never matter for that. #![deny(missing_docs)] mod ir; +pub mod kde; +pub mod plan; pub mod qt; pub mod skhd; pub mod sxhkd; diff --git a/komorebi-hotkeys/src/plan.rs b/komorebi-hotkeys/src/plan.rs new file mode 100644 index 00000000..33b627b9 --- /dev/null +++ b/komorebi-hotkeys/src/plan.rs @@ -0,0 +1,442 @@ +//! Planning: which bindings become KDE shortcut files, and which komorebi handles itself. +//! +//! A binding can be realized in two ways: +//! +//! - As a **static shortcut**: a `.desktop` file ([`kde`](crate::kde)) that KDE runs the command +//! of. It is visible and can be changed in System Settings, and it works with no komorebi process +//! running. It can only be one combo, pressed, that runs a command in every application. +//! - Through the **engine**: komorebi registers the keys with KDE itself and decides what a key +//! does when it is pressed, so it can realize modes, chord chains, release bindings, +//! per-application bindings, a blacklist and a pause binding. It is only as robust as the +//! komorebi process. +//! +//! [`plan`] sorts the bindings of a keymap into the two, by [`PlanMode`]. With +//! [`PlanMode::Auto`], a binding is a static shortcut when it is in the default mode, a single +//! combo, pressed and the same in every application, and the file declares no modes, no blacklist +//! and no pause binding; everything else goes through the engine. +//! +//! ```rust +//! use komorebi_hotkeys::{Format, ParseOptions, parse}; +//! use komorebi_hotkeys::plan::{PlanMode, PlanOptions, plan}; +//! +//! let parsed = parse( +//! Format::Skhd, +//! "alt - h : komorebic focus left\nalt - n [\n \"firefox\" : komorebic retile\n]\n", +//! &ParseOptions::default(), +//! ); +//! let plan = plan(&parsed.keymap, &PlanOptions { mode: PlanMode::Auto }); +//! +//! assert_eq!(plan.static_files.len(), 1); +//! assert_eq!(plan.static_files[0].combo.to_string(), "Alt+H"); +//! assert_eq!(plan.engine.modes[0].bindings.len(), 1); +//! assert_eq!( +//! plan.diagnostics[0].to_string(), +//! "line 2: note: Alt+N goes through the engine: it does something else in each application", +//! ); +//! ``` + +use crate::Binding; +use crate::Body; +use crate::DEFAULT_MODE; +use crate::Diagnostic; +use crate::Edge; +use crate::Keymap; +use crate::Mode; +use crate::Run; +use crate::Support; +use crate::kde::Shortcut; +use crate::text; + +/// How [`plan`] realizes the bindings. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum PlanMode { + /// Every binding that can be a static shortcut is one, and the engine handles the rest. + Auto, + /// The engine handles every binding. + /// + /// This is the default. On KWin 6.8.1 a static shortcut ran its command 165 to 436 ms after + /// the key (a median of 233 ms over 8 presses, in a virtual machine), while the engine was + /// told of the key 3 ms after it (measured on 2026-10-27). + #[default] + Engine, + /// Every binding that can be a static shortcut is one, and the rest are left out, with a + /// warning each. No komorebi process needs to run for the keys to work. + Static, +} + +/// Options for [`plan`]. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PlanOptions { + /// How the bindings are realized. + /// + /// The default for this is [`PlanMode::Engine`]. + pub mode: PlanMode, +} + +/// The bindings of a keymap, sorted into static shortcuts and the engine's. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Plan { + /// The bindings that become `.desktop` files, which [`kde::desktop_files`] writes. + /// + /// [`kde::desktop_files`]: crate::kde::desktop_files + pub static_files: Vec, + /// The keymap the engine realizes: the modes of the original, each with the bindings that go + /// through the engine, and its blacklist and pause binding, unless the plan is + /// [`PlanMode::Static`]. + pub engine: Keymap, + /// Why a binding goes where it goes, or is left out. + pub diagnostics: Vec, +} + +impl Plan { + /// Returns true if and only if the engine has a binding or a pause binding to realize. + /// + /// # Example + /// + /// ```rust + /// use komorebi_hotkeys::{Format, ParseOptions, parse}; + /// use komorebi_hotkeys::plan::{PlanMode, PlanOptions, plan}; + /// + /// let parsed = parse(Format::Skhd, "alt - h : komorebic focus left\n", &ParseOptions::default()); + /// assert!(!plan(&parsed.keymap, &PlanOptions { mode: PlanMode::Auto }).needs_engine()); + /// assert!(plan(&parsed.keymap, &PlanOptions::default()).needs_engine()); + /// ``` + pub fn needs_engine(&self) -> bool { + self.engine.pause.is_some() || self.engine.modes.iter().any(|m| !m.bindings.is_empty()) + } +} + +/// Sorts the bindings of a keymap into static shortcuts and the engine's. +/// +/// The [module documentation](self) says which binding goes where. Bindings keep their order. The +/// diagnostics are notes that say why a binding goes through the engine under +/// [`PlanMode::Auto`], and warnings for what [`PlanMode::Static`] leaves out. +/// +/// # Example +/// +/// ```rust +/// use komorebi_hotkeys::{Format, ParseOptions, Severity, Support, parse}; +/// use komorebi_hotkeys::plan::{PlanMode, PlanOptions, plan}; +/// +/// let parsed = parse( +/// Format::Sxhkd, +/// "super + h\n komorebic focus left\nsuper + w ; h\n komorebic move left\n", +/// &ParseOptions::default(), +/// ); +/// let plan = plan(&parsed.keymap, &PlanOptions { mode: PlanMode::Static }); +/// assert_eq!(plan.static_files.len(), 1); +/// assert!(!plan.needs_engine()); +/// // the chain needs the engine, so a static plan leaves it out +/// assert_eq!(plan.diagnostics[0].severity, Severity::Warning); +/// assert_eq!(plan.diagnostics[0].support, Support::Unsupported); +/// ``` +pub fn plan(keymap: &Keymap, options: &PlanOptions) -> Plan { + let mut engine = Keymap { + format: keymap.format, + modes: keymap + .modes + .iter() + .map(|mode| Mode { + bindings: Vec::new(), + ..mode.clone() + }) + .collect(), + blacklist: keymap.blacklist.clone(), + pause: keymap.pause.clone(), + defines: keymap.defines.clone(), + }; + let mut static_files = Vec::new(); + let mut diagnostics = Vec::new(); + + let first_span = keymap + .modes + .iter() + .flat_map(|mode| &mode.bindings) + .map(|binding| binding.span) + .next() + .unwrap_or_default(); + let whole_file = if keymap.declares_modes() { + Some("the file declares modes") + } else if !keymap.blacklist.is_empty() { + Some("the file has a blacklist") + } else if keymap.pause.is_some() { + Some("the file has a pause binding") + } else { + None + }; + + match options.mode { + PlanMode::Engine => { + for (index, mode) in keymap.modes.iter().enumerate() { + engine.modes[index].bindings = mode.bindings.clone(); + } + } + PlanMode::Auto => { + if let Some(reason) = whole_file { + diagnostics.push(text::note( + first_span, + Support::Exact, + format!("every binding goes through the engine: {reason}"), + )); + } + for (index, mode) in keymap.modes.iter().enumerate() { + for binding in &mode.bindings { + match (whole_file, needs_engine(&mode.name, binding)) { + (None, None) => static_files.push(shortcut(keymap, binding)), + (Some(_), _) => engine.modes[index].bindings.push(binding.clone()), + (None, Some(reason)) => { + diagnostics.push(text::note( + binding.span, + Support::Exact, + format!("{} goes through the engine: {reason}", chord(binding)), + )); + engine.modes[index].bindings.push(binding.clone()); + } + } + } + } + } + PlanMode::Static => { + if !keymap.blacklist.is_empty() { + diagnostics.push(text::approximated( + first_span, + "the blacklist is not applied: a static shortcut works in every application", + )); + } + if let Some(pause) = &keymap.pause { + diagnostics.push(text::unsupported( + pause.span, + "the pause binding is left out: it needs the engine", + )); + } + for mode in &keymap.modes { + for binding in &mode.bindings { + match needs_engine(&mode.name, binding) { + None => static_files.push(shortcut(keymap, binding)), + Some(reason) => diagnostics.push(text::unsupported( + binding.span, + format!( + "{} is left out: {reason}, which needs the engine", + chord(binding) + ), + )), + } + } + } + engine = Keymap::new(keymap.format); + } + } + + diagnostics.sort_by_key(|d| d.span.start); + Plan { + static_files, + engine, + diagnostics, + } +} + +/// Why a binding cannot be a static shortcut, if it cannot. +fn needs_engine(mode: &str, binding: &Binding) -> Option { + if mode != DEFAULT_MODE { + return Some(format!("it is in the mode `{mode}`")); + } + if binding.chord.len() > 1 { + return Some("it is a chord chain".to_string()); + } + if binding.edge == Edge::Release { + return Some("it fires when the key is released".to_string()); + } + match &binding.body { + Body::Scoped(_) => Some("it does something else in each application".to_string()), + Body::Run(Run::Mode(_)) => Some("it switches modes".to_string()), + Body::Run(Run::Command(_)) if binding.chord[0].key().code() == u32::from(',') => { + Some("a comma cannot be written in `X-KDE-Shortcuts`".to_string()) + } + Body::Run(Run::Command(_)) => None, + } +} + +fn shortcut(keymap: &Keymap, binding: &Binding) -> Shortcut { + let command = match &binding.body { + Body::Run(Run::Command(command)) => command.clone(), + _ => String::new(), + }; + Shortcut { + combo: binding.chord[0], + command, + comment: format!("from the {}: {}", keymap.format.file_name(), binding.source), + } +} + +/// The keys of a binding, as the diagnostics write them. +fn chord(binding: &Binding) -> String { + binding + .chord + .iter() + .map(ToString::to_string) + .collect::>() + .join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Format; + use crate::ParseOptions; + use crate::Severity; + use crate::parse; + + fn planned(format: Format, text: &str, mode: PlanMode) -> Plan { + let parsed = parse(format, text, &ParseOptions::default()); + plan(&parsed.keymap, &PlanOptions { mode }) + } + + fn keys(plan: &Plan) -> (Vec, Vec) { + let files = plan + .static_files + .iter() + .map(|s| s.combo.to_string()) + .collect(); + let engine = plan + .engine + .modes + .iter() + .flat_map(|mode| &mode.bindings) + .map(chord) + .collect(); + (files, engine) + } + + fn messages(plan: &Plan) -> Vec { + plan.diagnostics.iter().map(ToString::to_string).collect() + } + + #[test] + fn a_plain_binding_is_static_and_the_rest_goes_through_the_engine() { + let plan = planned( + Format::Sxhkd, + "super + h\n a\nsuper + w ; h\n b\nsuper + @x\n c\nsuper + comma\n d\n", + PlanMode::Auto, + ); + assert_eq!( + keys(&plan), + ( + vec!["Meta+H".to_string()], + vec![ + "Meta+W, H".to_string(), + "Meta+X".to_string(), + "Meta+,".to_string() + ] + ) + ); + assert_eq!( + messages(&plan), + [ + "line 3: note: Meta+W, H goes through the engine: it is a chord chain", + "line 5: note: Meta+X goes through the engine: it fires when the key is released", + "line 7: note: Meta+, goes through the engine: a comma cannot be written in \ + `X-KDE-Shortcuts`", + ] + ); + assert!( + plan.diagnostics + .iter() + .all(|d| d.severity == Severity::Note) + ); + } + + #[test] + fn modes_a_blacklist_or_a_pause_binding_send_every_binding_through_the_engine() { + for (format, text, reason) in [ + ( + Format::Skhd, + ":: resize\nalt - h : a\nalt - r ; resize\nresize < h : b\n", + "the file declares modes", + ), + ( + Format::Skhd, + ".blacklist [ \"steam\" ]\nalt - h : a\n", + "the file has a blacklist", + ), + ( + Format::Whkd, + ".pause alt + p\nalt + h : a\n", + "the file has a pause binding", + ), + ] { + let plan = planned(format, text, PlanMode::Auto); + assert!(plan.static_files.is_empty(), "{text}"); + assert!(plan.needs_engine(), "{text}"); + assert_eq!( + plan.diagnostics + .iter() + .map(|d| d.msg.clone()) + .collect::>(), + [format!("every binding goes through the engine: {reason}")], + "{text}" + ); + } + } + + #[test] + fn the_engine_plan_takes_everything() { + let plan = planned( + Format::Skhd, + ":: resize\nalt - h : a\nalt - r ; resize\nresize < h : b\n", + PlanMode::Engine, + ); + assert!(plan.static_files.is_empty()); + assert!(plan.diagnostics.is_empty()); + assert_eq!(plan.engine.modes.len(), 2); + assert_eq!(plan.engine.modes[0].bindings.len(), 2); + assert_eq!(plan.engine.modes[1].bindings.len(), 1); + assert_eq!(plan.engine.modes[1].name, "resize"); + } + + #[test] + fn the_static_plan_leaves_out_what_needs_the_engine() { + let plan = planned( + Format::Skhd, + ".blacklist [ \"steam\" ]\n:: resize\nalt - h : a\nalt - r ; resize\nresize < h : b\n", + PlanMode::Static, + ); + assert_eq!(keys(&plan), (vec!["Alt+H".to_string()], vec![])); + assert!(!plan.needs_engine()); + assert_eq!( + messages(&plan), + [ + "line 3: warning: the blacklist is not applied: a static shortcut works in every \ + application", + "line 4: warning: Alt+R is left out: it switches modes, which needs the engine", + "line 5: warning: H is left out: it is in the mode `resize`, which needs the engine", + ] + ); + } + + #[test] + fn the_comment_says_where_the_binding_came_from() { + let plan = planned( + Format::Whkd, + "alt + h : komorebic focus left # left\n", + PlanMode::Auto, + ); + assert_eq!( + plan.static_files[0].comment, + "from the whkdrc: alt + h : komorebic focus left # left" + ); + let plan = planned( + Format::Sxhkd, + "super + h\n komorebic focus left\n", + PlanMode::Auto, + ); + assert_eq!( + plan.static_files[0].comment, + "from the sxhkdrc: super + h: komorebic focus left" + ); + } + + #[test] + fn the_default_is_the_engine() { + assert_eq!(PlanOptions::default().mode, PlanMode::Engine); + } +} diff --git a/komorebi-hotkeys/tests/corpus.rs b/komorebi-hotkeys/tests/corpus.rs index 8f6a9d19..e3e20bee 100644 --- a/komorebi-hotkeys/tests/corpus.rs +++ b/komorebi-hotkeys/tests/corpus.rs @@ -17,6 +17,10 @@ use komorebi_hotkeys::Run; use komorebi_hotkeys::Severity; use komorebi_hotkeys::Span; use komorebi_hotkeys::Then; +use komorebi_hotkeys::kde::desktop_files; +use komorebi_hotkeys::plan::PlanMode; +use komorebi_hotkeys::plan::PlanOptions; +use komorebi_hotkeys::plan::plan; use std::path::PathBuf; /// Every case, and the formats it is written in. @@ -342,3 +346,43 @@ fn the_files_of_a_case_read_into_the_same_keymap() { } } } + +#[test] +fn the_sample_plans_into_the_same_shortcut_files_in_every_format() { + let mut planned = Vec::new(); + for extension in ["skhdrc", "whkdrc", "sxhkdrc"] { + let parsed = parse(extension, &read("sample", extension)).unwrap(); + let plan = plan( + &parsed.keymap, + &PlanOptions { + mode: PlanMode::Auto, + }, + ); + assert!(!plan.needs_engine(), "{extension}"); + assert!( + plan.diagnostics.is_empty(), + "{extension}: {:#?}", + plan.diagnostics + ); + + let files = desktop_files(&plan.static_files); + assert_eq!(files.len(), 50, "{extension}"); + // everything but the comment, which quotes the file + let files: Vec<(String, Vec)> = files + .into_iter() + .map(|file| { + let lines = file + .content + .lines() + .filter(|line| !line.starts_with("Comment=")) + .map(str::to_string) + .collect(); + (file.name, lines) + }) + .collect(); + planned.push((extension, files)); + } + for pair in planned.windows(2) { + assert_eq!(pair[0].1, pair[1].1, "{} and {}", pair[0].0, pair[1].0); + } +}