From 0520068b488875d60c7d76dd0e8e6a3cfeeab3bc Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 11:59:19 -0700 Subject: [PATCH] feat(hotkeys): the binding IR, key names to Qt codes and a fixture corpus komorebi users keep their bindings to komorebic in the file of a hotkey daemon: an skhdrc on macOS, a whkdrc on Windows, an sxhkdrc on X11. On KDE Plasma the program that runs a command on a key is KDE's global shortcut daemon, so the bindings have to be read and turned into shortcuts. This adds `komorebi-hotkeys`, a crate of its own that does not depend on the daemon, with the model all three formats are read into: a `Keymap` of modes of bindings, each a chord, an edge and a body (a command, a mode switch, or one action per application), and `Diagnostic`s with spans. A key is a Qt key code with the modifier flags or'ed in, which is what kglobalacceld stores, so the same key is the same value whatever file named it. `qt::key_to_qt` knows the three vocabularies: skhd's literals and macOS keycodes, whkd's virtual key names and sxhkd's X keysyms, including the XF86 media keys. `Combo` applies the shifted symbol rule measured on KWin 6.8.1 (Alt+Shift+1 arrives as Alt+!), and its fields are private so that no combo skips it; a `compile_fail` example proves it. Positions are read as on a US layout. The fixture corpus writes each case in every format that can express it; the parsers are written against it. The flake's source filter keeps the fixtures, so that the nix checks can read them. --- Cargo.lock | 4 + Cargo.toml | 8 +- README.md | 5 + deny.toml | 5 + docs/dev/ARCHITECTURE.md | 42 + flake.nix | 4 +- komorebi-hotkeys/Cargo.toml | 7 + komorebi-hotkeys/src/ir.rs | 307 +++++ komorebi-hotkeys/src/lib.rs | 95 ++ komorebi-hotkeys/src/qt.rs | 1012 +++++++++++++++++ komorebi-hotkeys/tests/corpus.rs | 65 ++ .../tests/fixtures/blacklist.skhdrc | 7 + komorebi-hotkeys/tests/fixtures/braces.skhdrc | 11 + .../tests/fixtures/braces.sxhkdrc | 5 + komorebi-hotkeys/tests/fixtures/braces.whkdrc | 13 + .../tests/fixtures/chords.sxhkdrc | 7 + .../tests/fixtures/comments.skhdrc | 6 + .../tests/fixtures/comments.sxhkdrc | 8 + .../tests/fixtures/comments.whkdrc | 6 + komorebi-hotkeys/tests/fixtures/define.skhdrc | 10 + komorebi-hotkeys/tests/fixtures/define.whkdrc | 11 + .../tests/fixtures/keycodes.skhdrc | 7 + .../tests/fixtures/keycodes.sxhkdrc | 13 + .../tests/fixtures/keycodes.whkdrc | 9 + komorebi-hotkeys/tests/fixtures/modes.skhdrc | 7 + .../tests/fixtures/modifiers.skhdrc | 9 + .../tests/fixtures/modifiers.sxhkdrc | 17 + .../tests/fixtures/modifiers.whkdrc | 11 + komorebi-hotkeys/tests/fixtures/pause.whkdrc | 6 + komorebi-hotkeys/tests/fixtures/plain.skhdrc | 6 + komorebi-hotkeys/tests/fixtures/plain.sxhkdrc | 11 + komorebi-hotkeys/tests/fixtures/plain.whkdrc | 8 + .../tests/fixtures/release.sxhkdrc | 3 + komorebi-hotkeys/tests/fixtures/sample.skhdrc | 71 ++ .../tests/fixtures/sample.sxhkdrc | 121 ++ komorebi-hotkeys/tests/fixtures/sample.whkdrc | 72 ++ komorebi-hotkeys/tests/fixtures/scopes.skhdrc | 7 + komorebi-hotkeys/tests/fixtures/scopes.whkdrc | 10 + 38 files changed, 2024 insertions(+), 2 deletions(-) create mode 100644 komorebi-hotkeys/Cargo.toml create mode 100644 komorebi-hotkeys/src/ir.rs create mode 100644 komorebi-hotkeys/src/lib.rs create mode 100644 komorebi-hotkeys/src/qt.rs create mode 100644 komorebi-hotkeys/tests/corpus.rs create mode 100644 komorebi-hotkeys/tests/fixtures/blacklist.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/braces.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/braces.sxhkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/braces.whkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/chords.sxhkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/comments.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/comments.sxhkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/comments.whkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/define.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/define.whkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/keycodes.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/keycodes.sxhkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/keycodes.whkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/modes.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/modifiers.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/modifiers.sxhkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/modifiers.whkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/pause.whkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/plain.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/plain.sxhkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/plain.whkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/release.sxhkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/sample.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/sample.sxhkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/sample.whkdrc create mode 100644 komorebi-hotkeys/tests/fixtures/scopes.skhdrc create mode 100644 komorebi-hotkeys/tests/fixtures/scopes.whkdrc diff --git a/Cargo.lock b/Cargo.lock index c0565ca4..39629941 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2497,6 +2497,10 @@ dependencies = [ "serde_json_lenient", ] +[[package]] +name = "komorebi-hotkeys" +version = "0.1.0" + [[package]] name = "komorebi-layouts" version = "0.1.42" diff --git a/Cargo.toml b/Cargo.toml index 46611746..b3ac46b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,13 @@ [workspace] resolver = "2" -members = ["komorebi", "komorebi-client", "komorebic", "version"] +members = [ + "komorebi", + "komorebi-client", + "komorebi-hotkeys", + "komorebic", + "version", +] [workspace.package] version = "0.1.0" diff --git a/README.md b/README.md index ef070063..dc0db4f7 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,11 @@ without a checkout of the toolchain. - [`komorebi-client`](komorebi-client): a library that sends messages to the daemon, reads its answers, subscribes to its notifications, and re-exports the types they are made of. +- [`komorebi-hotkeys`](komorebi-hotkeys): the key bindings of skhd, whkd and + sxhkd files in one model, with the keys as KDE stores them. 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 of the daemon is one message on its socket; `quickstart`, `enable-autostart`, `disable-autostart`, `start`, `check`, `configuration`, `log`, `data-directory`, diff --git a/deny.toml b/deny.toml index 3073b13f..fa3f21b2 100644 --- a/deny.toml +++ b/deny.toml @@ -48,6 +48,11 @@ crate = "komorebi-client" expression = "LicenseRef-Komorebi-2.0" license-files = [] +[[licenses.clarify]] +crate = "komorebi-hotkeys" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "komorebi-layouts" expression = "LicenseRef-Komorebi-2.0" diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 5eec5f59..54f9c37b 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -1564,6 +1564,46 @@ A window is shown, and ends up on a tile: 6. There are no more lines, so `read_commands_uds` returns and the connection is closed. `send_query` has read to the end, and returns the JSON, which `komorebic` prints. +## Key bindings + +[`komorebi-hotkeys`](../../komorebi-hotkeys/src/lib.rs) is a crate of its own, which does not +depend on the daemon. Its model is the content of a key binding file of any of three hotkey +daemons: skhd (macOS), whkd (Windows) and sxhkd (X11). + +### The model + +- **Keymap**: one file: its modes, the applications in which no binding is active (a + blacklist), a binding that turns the others off and on (a pause binding), and the names the + file defined. +- **Mode**: bindings that are active together. A keymap starts in the mode `default`. +- **Binding**: a chord (one or more combos, pressed one after the other), whether it fires on + press or on release, and a body: an action (run a command, or switch to a mode), or an action + per application (scopes). +- **Combo**: a key and its modifiers, as the integer KDE stores (a Qt key code with the modifier + flags or'ed in) and the portable text a `.desktop` file writes (`Alt+H`). +- **Diagnostic**: something about a file its user should know: its span (byte offsets and line), + its severity (error, warning, note) and how faithfully the construct is realized (exactly, + approximated, not at all). + +### The parts + +- [`qt`](../../komorebi-hotkeys/src/qt.rs): key names to Qt key codes, in the vocabulary of each + format (skhd's literals and macOS keycodes, whkd's virtual key names, sxhkd's X keysyms), and + `Combo`, which applies the shifted symbol rule: KWin matches the character a key press + produced, so Alt+Shift+1 is registered as Alt+!. +- [`ir`](../../komorebi-hotkeys/src/ir.rs): the model. +- [`tests/fixtures`](../../komorebi-hotkeys/tests/fixtures): the corpus, `.skhdrc`, + `.whkdrc` and `.sxhkdrc`, each case in every format that can express it. + +### What is guaranteed, and by what + +| Rule | Enforced by | Proof | Escape hatch | +|---|---|---|---| +| A combo is in the form KWin matches (the shifted symbol rule is applied) | type system: `Combo`'s fields are private, and `Combo::new` applies the rule | `compile_fail,E0451` on `Combo`; `shift_on_a_symbol_key_is_the_symbol_it_types` | none | +| A key has the same code whichever vocabulary names it | test | `the_three_vocabularies_name_the_same_keys` | none | +| Positional key names (macOS keycodes, `oem_*`) are read as on a US layout | convention only | none | none | +| The files of a corpus case mean the same keymap | convention only | `the_files_of_a_case_say_what_it_is_about_in_the_same_words` checks only that they start with the same comment | none | + ## Where to look in the code - [`komorebi/src/backend/mod.rs`](../../komorebi/src/backend/mod.rs): the trait. @@ -1738,6 +1778,8 @@ A window is shown, and ends up on a tile: [`nix/tests/vm/suites/kwin-contract`](../../nix/tests/vm/suites/kwin-contract/test.py), the behavior of KWin's per-output virtual desktops komorebi relies on, with two outputs and no komorebi. +- [`komorebi-hotkeys/src/lib.rs`](../../komorebi-hotkeys/src/lib.rs): the key binding model, and + [`komorebi-hotkeys/src/qt.rs`](../../komorebi-hotkeys/src/qt.rs) the keys. - [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; [`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix), its scenarios, evaluated in real NixOS systems; and [`nix/tests/vm/suites/module`](../../nix/tests/vm/suites/module/test.py), diff --git a/flake.nix b/flake.nix index 6381f9cb..2a4d2768 100644 --- a/flake.nix +++ b/flake.nix @@ -54,7 +54,9 @@ # with the example file || (pkgs.lib.hasSuffix "docs/example-configurations.md" path) # the example a test loads, to see that the docs show one that works - || (pkgs.lib.hasSuffix "docs/usage/wallpapers.md" path); + || (pkgs.lib.hasSuffix "docs/usage/wallpapers.md" path) + # the key binding files the komorebi-hotkeys tests read + || (pkgs.lib.hasInfix "/komorebi-hotkeys/tests/fixtures/" path); }; commonArgs = { diff --git a/komorebi-hotkeys/Cargo.toml b/komorebi-hotkeys/Cargo.toml new file mode 100644 index 00000000..428d6ec6 --- /dev/null +++ b/komorebi-hotkeys/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "komorebi-hotkeys" +version.workspace = true +description = "Reads skhd, whkd and sxhkd key binding files and plans them as KDE global shortcuts" +edition = "2024" + +[dependencies] diff --git a/komorebi-hotkeys/src/ir.rs b/komorebi-hotkeys/src/ir.rs new file mode 100644 index 00000000..4413649d --- /dev/null +++ b/komorebi-hotkeys/src/ir.rs @@ -0,0 +1,307 @@ +//! The model every file is read into: a keymap of modes of bindings, and the diagnostics about it. + +use crate::Format; +use crate::qt::Combo; +use std::fmt; + +/// The name of the mode a keymap starts in. +pub const DEFAULT_MODE: &str = "default"; + +/// The key bindings read from one file. +/// +/// A keymap is a list of [modes](Mode), each with its bindings, and the settings that apply to +/// every mode: the applications in which no binding is active ([`Keymap::blacklist`]), the binding +/// that turns every other binding off and on ([`Keymap::pause`]), and the templates the file +/// defined ([`Keymap::defines`]). +/// +/// All three formats read into this one structure, so a binding means the same thing whatever +/// file it came from: `alt - h : komorebic focus left` in an skhdrc and `alt + h : komorebic focus +/// left` in a whkdrc are equal [`Binding`]s, apart from where each was written +/// ([`Binding::span`] and [`Binding::source`]); the keymaps differ only in [`Keymap::format`]. +/// +/// # Example +/// +/// ```rust +/// use komorebi_hotkeys::{Binding, Body, DEFAULT_MODE, Edge, Format, Keymap, Run, Span}; +/// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; +/// +/// let mut keymap = Keymap::new(Format::Skhd); +/// keymap.modes[0].bindings.push(Binding { +/// chord: vec![Combo::new(Mods::ALT, key_to_qt(Format::Skhd, "h").unwrap())], +/// edge: Edge::Press, +/// body: Body::Run(Run::Command("komorebic focus left".into())), +/// span: Span::default(), +/// source: "alt - h : komorebic focus left".into(), +/// }); +/// +/// let default = keymap.mode(DEFAULT_MODE).unwrap(); +/// assert_eq!(default.bindings[0].chord[0].to_string(), "Alt+H"); +/// assert!(!keymap.declares_modes()); +/// ``` +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Keymap { + /// The format of the file the keymap was read from. + pub format: Format, + /// The modes, the [default mode](DEFAULT_MODE) first. + pub modes: Vec, + /// The applications in which no binding is active, as the file names them. + pub blacklist: Vec, + /// The binding that turns every other binding off, and on again. + pub pause: Option, + /// The names the file defined. Their uses are already expanded in the bindings; they are kept + /// to be listed. + pub defines: Vec, +} + +impl Keymap { + /// Returns a keymap with an empty default mode and nothing else. + pub fn new(format: Format) -> Keymap { + Keymap { + format, + modes: vec![Mode::new(DEFAULT_MODE)], + blacklist: Vec::new(), + pause: None, + defines: Vec::new(), + } + } + + /// Returns the mode with this name. + pub fn mode(&self, name: &str) -> Option<&Mode> { + self.modes.iter().find(|mode| mode.name == name) + } + + /// Returns true if and only if the keymap has a mode other than the default one. + pub fn declares_modes(&self) -> bool { + self.modes.iter().any(|mode| mode.name != DEFAULT_MODE) + } +} + +/// A set of bindings that are active together. +/// +/// Only one mode is active at a time. A keymap starts in the [default mode](DEFAULT_MODE), and a +/// binding whose body is [`Run::Mode`] switches to another. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Mode { + /// The mode's name. + pub name: String, + /// Whether the mode swallows every key that none of its bindings is for (skhd's `@`). + pub capture: bool, + /// A command to run each time the mode is entered. + pub on_enter: Option, + /// The bindings, in the order the file has them. + pub bindings: Vec, +} + +impl Mode { + /// Returns an empty mode with this name, which does not capture and runs nothing when it is + /// entered. + pub fn new(name: impl Into) -> Mode { + Mode { + name: name.into(), + capture: false, + on_enter: None, + bindings: Vec::new(), + } + } +} + +/// One binding: the keys, when it fires, and what it does. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Binding { + /// The combos to press, one after the other. A plain binding has one; a chord chain (sxhkd's + /// `alt + w ; h`) has more. + pub chord: Vec, + /// Whether the binding fires when the last combo is pressed or when it is released. + pub edge: Edge, + /// What the binding does. + pub body: Body, + /// Where the binding was written. + pub span: Span, + /// The binding as it was written, on one line, for logs and for the comment of a generated + /// shortcut file. + pub source: String, +} + +/// When a binding fires. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Edge { + /// When the last combo of the chord is pressed. + Press, + /// When the last combo of the chord is released (sxhkd's `@`). + Release, +} + +/// What a binding does. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Body { + /// The same thing in every application. + Run(Run), + /// A different thing depending on the application that has the focus. + /// + /// The scope that names the focused application applies, the first one if several do; when + /// none does, the [`App::Other`] scope applies, wherever it is in the list. When there is no + /// such scope, or its [`Then`] is [`Then::Ignore`], the binding does nothing and the key + /// reaches the application. + Scoped(Vec), +} + +/// An action. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Run { + /// Runs a command. + Command(String), + /// Switches to the mode with this name, and runs its [`Mode::on_enter`] command. + Mode(String), +} + +/// What a scoped binding does in some applications. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Scope { + /// The applications the scope is for. + pub app: App, + /// What the binding does in them. + pub then: Then, +} + +/// The applications a [`Scope`] applies to. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum App { + /// The application with this name, as the file writes it. + Named(String), + /// Every application no other scope of the binding names (skhd's `*`, whkd's `Default`). + Other, +} + +/// What a scoped binding does in the applications of its scope. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Then { + /// It runs this action. + Run(Run), + /// Nothing: the key reaches the application (skhd's `~`, whkd's `Ignore`). + Ignore, +} + +/// The binding that turns every other binding off, and on again (whkd's `.pause`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Pause { + /// The keys. + pub combo: Combo, + /// A command to run each time the bindings are turned off or on (whkd's `.pause_hook`). + pub hook: Option, + /// Where the binding was written. + pub span: Span, +} + +/// A name the file defined (skhd's `.define`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Define { + /// The name. + pub name: String, + /// What the name stands for. + pub value: DefineValue, + /// Where it was defined. + pub span: Span, +} + +/// What a [`Define`] stands for. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DefineValue { + /// A command, with placeholders `{{1}}`, `{{2}}`... for its arguments. + Command(String), + /// A group of applications. + Apps(Vec), +} + +/// A range of the text a keymap was read from. +/// +/// The default value, all zeros, is a span that points nowhere, for a binding that was not read +/// from a file. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Span { + /// The byte offset of the first byte. + pub start: usize, + /// The byte offset one past the last byte. + pub end: usize, + /// The line of the first byte, counted from 1. + pub line: usize, +} + +/// Something about a file that its user should know. +/// +/// A diagnostic is either about text that could not be read ([`Severity::Error`]), or about a +/// binding komorebi realizes differently from the file's own daemon, or not at all +/// ([`Severity::Warning`]), or a remark ([`Severity::Note`]). [`Diagnostic::support`] says how +/// faithfully the construct it is about is realized. +/// +/// # Example +/// +/// ```rust +/// use komorebi_hotkeys::{Diagnostic, Severity, Span, Support}; +/// +/// let diagnostic = Diagnostic { +/// span: Span { start: 40, end: 47, line: 3 }, +/// severity: Severity::Warning, +/// support: Support::Approximated, +/// msg: "`lalt` is Alt: KDE does not tell left and right apart".into(), +/// }; +/// assert_eq!( +/// diagnostic.to_string(), +/// "line 3: warning: `lalt` is Alt: KDE does not tell left and right apart", +/// ); +/// ``` +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Diagnostic { + /// The text the diagnostic is about. + pub span: Span, + /// How much it matters. + pub severity: Severity, + /// How faithfully the construct is realized. + pub support: Support, + /// The message, which starts in lower case and does not end with a period. + pub msg: String, +} + +/// Writes `line N: severity: message`. +impl fmt::Display for Diagnostic { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "line {}: {}: {}", + self.span.line, self.severity, self.msg + ) + } +} + +/// How much a [`Diagnostic`] matters. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Severity { + /// A remark: nothing is lost. + Note, + /// The text is valid in its format, but komorebi does not realize it the way the format's own + /// daemon does. + Warning, + /// The text is not valid in its format, and is skipped. + Error, +} + +/// Writes `note`, `warning` or `error`. +impl fmt::Display for Severity { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Severity::Note => "note", + Severity::Warning => "warning", + Severity::Error => "error", + }) + } +} + +/// How faithfully komorebi realizes the construct a [`Diagnostic`] is about. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Support { + /// As the file's own daemon would. + Exact, + /// In a way that differs from the file's own daemon, which the message describes. + Approximated, + /// Not at all: the construct is left out. + Unsupported, +} diff --git a/komorebi-hotkeys/src/lib.rs b/komorebi-hotkeys/src/lib.rs new file mode 100644 index 00000000..298934cd --- /dev/null +++ b/komorebi-hotkeys/src/lib.rs @@ -0,0 +1,95 @@ +//! One model for the key bindings of skhd, whkd and sxhkd files, with the keys as KDE stores them. +//! +//! 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 +//! bindings to `komorebic` in such a file. On KDE Plasma under Wayland no client sees the keys of +//! another, and the program that runs a command on a key is KDE's global shortcut daemon. The +//! three files say much the same things in three syntaxes, so this crate has one model for all of +//! them, [`Keymap`], and the keys as KDE stores them, [`qt`]. +//! +//! # The model +//! +//! - A [`Keymap`] is the content of one file: its [modes](Mode), and the settings that apply to +//! every mode (a blacklist of applications, a pause binding, the names the file defined). +//! - A [`Mode`] is a set of [bindings](Binding) that are active together. A keymap starts in the +//! [default mode](DEFAULT_MODE). +//! - A [`Binding`] is a chord (one or more [combos](qt::Combo) pressed one after the other), an +//! [edge](Edge) (press or release) and a [body](Body): either an action ([`Run`]: a command or +//! a mode switch), or a different action per application ([`Scope`]s). +//! - A [`Diagnostic`] is something about the file its user should know, with the [`Span`] of the +//! text it is about, its [`Severity`] and how faithfully the construct is realized +//! ([`Support`]). +//! +//! # Keys +//! +//! Each format names keys in its own vocabulary: skhd writes `0x21` or `return`, whkd `oem_4` or +//! `return`, sxhkd `bracketleft` or `Return`. [`qt::key_to_qt`] turns a name into a Qt key code, +//! and [`qt::Combo`] holds a key with its modifiers in the form KWin matches, so that the same key +//! is the same value whatever file named it: +//! +//! ```rust +//! use komorebi_hotkeys::Format; +//! use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; +//! +//! let skhd = Combo::new(Mods::ALT | Mods::SHIFT, key_to_qt(Format::Skhd, "0x21").unwrap()); +//! let whkd = Combo::new(Mods::ALT | Mods::SHIFT, key_to_qt(Format::Whkd, "oem_4").unwrap()); +//! assert_eq!(skhd, whkd); +//! // Shift+[ types {, and KWin matches the character +//! assert_eq!(skhd.to_string(), "Alt+{"); +//! ``` +//! +//! Key names are read as on a US keyboard layout; [the `qt` module](qt#a-us-layout-only) says +//! what that means for other layouts. + +#![deny(missing_docs)] + +mod ir; +pub mod qt; + +pub use ir::App; +pub use ir::Binding; +pub use ir::Body; +pub use ir::DEFAULT_MODE; +pub use ir::Define; +pub use ir::DefineValue; +pub use ir::Diagnostic; +pub use ir::Edge; +pub use ir::Keymap; +pub use ir::Mode; +pub use ir::Pause; +pub use ir::Run; +pub use ir::Scope; +pub use ir::Severity; +pub use ir::Span; +pub use ir::Support; +pub use ir::Then; + +/// The file formats this crate reads. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Format { + /// skhd's `skhdrc`, macOS's hotkey daemon, and the dialect of skhd.zig. + Skhd, + /// whkd's `whkdrc`, the hotkey daemon komorebi for Windows uses. + Whkd, + /// sxhkd's `sxhkdrc`, the X11 hotkey daemon. + Sxhkd, +} + +impl Format { + /// Returns the name the format's daemon gives its file. + /// + /// # Example + /// + /// ```rust + /// use komorebi_hotkeys::Format; + /// + /// assert_eq!(Format::Whkd.file_name(), "whkdrc"); + /// ``` + pub const fn file_name(self) -> &'static str { + match self { + Format::Skhd => "skhdrc", + Format::Whkd => "whkdrc", + Format::Sxhkd => "sxhkdrc", + } + } +} diff --git a/komorebi-hotkeys/src/qt.rs b/komorebi-hotkeys/src/qt.rs new file mode 100644 index 00000000..77a923f2 --- /dev/null +++ b/komorebi-hotkeys/src/qt.rs @@ -0,0 +1,1012 @@ +//! Keys as KDE stores them: Qt key codes, modifier flags, and the names they are written with. +//! +//! KDE's global shortcut daemon, kglobalacceld, stores a shortcut as a `QKeySequence`. Each key of +//! the sequence is one integer: a Qt key code (`Qt::Key`) with the modifier flags +//! (`Qt::KeyboardModifier`) or'ed in, so that Alt+H is `0x0800_0000 | 0x48`. A `.desktop` file +//! writes the same sequence as portable text, `Alt+H`. This module is the bridge from the key +//! names of the three file formats to those integers and that text: +//! +//! - [`key_to_qt`] returns the [`Key`] a name stands for, in the vocabulary of one [`Format`]. +//! - [`Mods`] are the modifier flags, and [`Combo`] is a key with its modifiers, in the form KWin +//! matches. +//! - [`Combo::to_qt`] is the integer kglobalacceld stores, and [`Combo`]'s `Display` the portable +//! text. +//! +//! ```rust +//! use komorebi_hotkeys::Format; +//! use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; +//! +//! let h = key_to_qt(Format::Skhd, "h").unwrap(); +//! let alt_h = Combo::new(Mods::ALT, h); +//! assert_eq!(alt_h.to_string(), "Alt+H"); +//! assert_eq!(alt_h.to_qt(), 0x0800_0048); +//! ``` +//! +//! # The shifted symbol rule +//! +//! KWin matches the character a key press produced, with the modifiers that produced it taken +//! away. Alt+Shift+1 arrives as Alt+!, so Alt+! is what has to be registered. Shifted letters and +//! named keys keep their Shift: Alt+Shift+H and Alt+Shift+Return arrive as they are. (Measured on +//! KWin 6.8.1 with a US layout.) [`Combo::new`] applies the rule, so every [`Combo`] is already in +//! the form KWin matches: +//! +//! ```rust +//! use komorebi_hotkeys::Format; +//! use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; +//! +//! let key = |name| key_to_qt(Format::Skhd, name).unwrap(); +//! assert_eq!(Combo::new(Mods::ALT | Mods::SHIFT, key("1")).to_string(), "Alt+!"); +//! assert_eq!(Combo::new(Mods::ALT | Mods::SHIFT, key("h")).to_string(), "Alt+Shift+H"); +//! ``` +//! +//! # A US layout only +//! +//! Some names are positions on a keyboard, not characters: skhd's macOS keycodes (`0x21` is the +//! key right of `P`) and whkd's `oem_*` keys. They, and the shifted symbol rule, are read as on a +//! US layout. On another layout the key a position types, and the symbol Shift gives it, differ, and +//! a binding read from such a name may not be the key the user meant. No other layout is supported. + +use crate::Format; +use std::fmt; +use std::ops::BitOr; +use std::ops::BitOrAssign; + +/// A set of modifiers, as the flags Qt or's into a key code. +/// +/// The four modifiers are the ones KDE knows. Side-specific modifiers (left Alt, right Alt) do +/// not exist here: KDE does not tell them apart in a shortcut. +/// +/// # Example +/// +/// ```rust +/// use komorebi_hotkeys::qt::Mods; +/// +/// let mods = Mods::CTRL | Mods::ALT; +/// assert!(mods.contains(Mods::ALT)); +/// assert!(!mods.contains(Mods::SHIFT)); +/// assert_eq!(mods.bits(), 0x0c00_0000); +/// ``` +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Mods(u32); + +impl Mods { + /// No modifier. + pub const NONE: Mods = Mods(0); + /// Shift (`Qt::ShiftModifier`). + pub const SHIFT: Mods = Mods(0x0200_0000); + /// Control (`Qt::ControlModifier`). + pub const CTRL: Mods = Mods(0x0400_0000); + /// Alt (`Qt::AltModifier`). + pub const ALT: Mods = Mods(0x0800_0000); + /// The Super, Windows or Command key, which Qt calls Meta (`Qt::MetaModifier`). + pub const META: Mods = Mods(0x1000_0000); + + /// Returns the flags, as Qt or's them into a key code. + pub const fn bits(self) -> u32 { + self.0 + } + + /// Returns true if and only if every modifier in `other` is in `self`. + pub const fn contains(self, other: Mods) -> bool { + self.0 & other.0 == other.0 + } + + /// Returns true if and only if there is no modifier in the set. + pub const fn is_empty(self) -> bool { + self.0 == 0 + } + + /// Returns the modifiers of `self` that are not in `other`. + pub const fn without(self, other: Mods) -> Mods { + Mods(self.0 & !other.0) + } +} + +impl BitOr for Mods { + type Output = Mods; + + fn bitor(self, rhs: Mods) -> Mods { + Mods(self.0 | rhs.0) + } +} + +impl BitOrAssign for Mods { + fn bitor_assign(&mut self, rhs: Mods) { + self.0 |= rhs.0; + } +} + +/// A key, as a Qt key code (`Qt::Key`). +/// +/// Values come from [`key_to_qt`] or the constants. Every `Key` has a name in Qt's portable text, +/// which its `Display` writes: `H`, `[`, `Return`, `Volume Up`. +/// +/// # Example +/// +/// ```rust +/// use komorebi_hotkeys::Format; +/// use komorebi_hotkeys::qt::{Key, key_to_qt}; +/// +/// assert_eq!(key_to_qt(Format::Sxhkd, "Escape"), Some(Key::ESCAPE)); +/// assert_eq!(Key::ESCAPE.code(), 0x0100_0000); +/// assert_eq!(Key::ESCAPE.to_string(), "Esc"); +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Key(u32); + +impl Key { + /// The Escape key (`Qt::Key_Escape`). + pub const ESCAPE: Key = Key(0x0100_0000); + + /// Returns the Qt key code. + pub const fn code(self) -> u32 { + self.0 + } +} + +impl fmt::Display for Key { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + 0x20 => f.write_str("Space"), + code @ 0x21..=0x7e => { + let c = char::from_u32(code).unwrap_or('?'); + write!(f, "{c}") + } + code => { + let name = NAMED + .iter() + .find(|(c, _)| *c == code) + .map(|(_, name)| *name) + .or_else(|| function_key_name(code)); + match name { + Some(name) => f.write_str(name), + None => write!(f, "{code:#x}"), + } + } + } + } +} + +/// A key with its modifiers, in the form KWin matches. +/// +/// It is guaranteed that a `Combo` has the [shifted symbol rule](self#the-shifted-symbol-rule) +/// applied: there is no `Combo` with Shift on a key that types a different symbol with Shift. The +/// fields are private and [`Combo::new`] is the only way to make one, which is what holds the +/// guarantee. Two combos are therefore equal if and only if KWin cannot tell them apart. +/// +/// A combo written field by field, which would skip the rule, does not compile: +/// +/// ```rust,compile_fail,E0451 +/// use komorebi_hotkeys::Format; +/// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; +/// +/// let one = key_to_qt(Format::Skhd, "1").unwrap(); +/// let combo = Combo { mods: Mods::ALT | Mods::SHIFT, key: one }; +/// ``` +/// +/// [`Combo::new`] is the way to make it: +/// +/// ```rust +/// use komorebi_hotkeys::Format; +/// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; +/// +/// let one = key_to_qt(Format::Skhd, "1").unwrap(); +/// let combo = Combo::new(Mods::ALT | Mods::SHIFT, one); +/// assert_eq!(combo.to_string(), "Alt+!"); +/// ``` +/// +/// # Example +/// +/// ```rust +/// use komorebi_hotkeys::Format; +/// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; +/// +/// let one = key_to_qt(Format::Whkd, "1").unwrap(); +/// let exclam = key_to_qt(Format::Sxhkd, "exclam").unwrap(); +/// // Shift+1 types !, so the two are the same combo +/// assert_eq!( +/// Combo::new(Mods::ALT | Mods::SHIFT, one), +/// Combo::new(Mods::ALT, exclam), +/// ); +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Combo { + mods: Mods, + key: Key, +} + +impl Combo { + /// Returns the combo KWin sees when `key` is pressed with `mods` held. + /// + /// With Shift held, a key that types a different symbol with Shift (the digits and the + /// punctuation of a US layout) becomes that symbol, and Shift is taken away. Shift on the + /// symbol itself is taken away as well, since typing the symbol needs it anyway. + /// + /// # Example + /// + /// ```rust + /// use komorebi_hotkeys::Format; + /// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; + /// + /// let key = |name| key_to_qt(Format::Skhd, name).unwrap(); + /// let combo = Combo::new(Mods::CTRL | Mods::ALT | Mods::SHIFT, key("9")); + /// assert_eq!(combo.mods(), Mods::CTRL | Mods::ALT); + /// assert_eq!(combo.to_string(), "Ctrl+Alt+("); + /// // named keys keep their Shift + /// assert_eq!(Combo::new(Mods::SHIFT, key("left")).to_string(), "Shift+Left"); + /// ``` + pub fn new(mods: Mods, key: Key) -> Combo { + if mods.contains(Mods::SHIFT) { + if let Some(shifted) = shifted_symbol(key) { + return Combo { + mods: mods.without(Mods::SHIFT), + key: shifted, + }; + } + if SHIFTED + .iter() + .any(|(_, shifted)| key.0 == u32::from(*shifted)) + { + return Combo { + mods: mods.without(Mods::SHIFT), + key, + }; + } + } + Combo { mods, key } + } + + /// Returns the modifiers. + pub const fn mods(self) -> Mods { + self.mods + } + + /// Returns the key. + pub const fn key(self) -> Key { + self.key + } + + /// Returns the integer kglobalacceld stores for this combo: the key code with the modifier + /// flags or'ed in. + /// + /// # Example + /// + /// ```rust + /// use komorebi_hotkeys::Format; + /// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt}; + /// + /// let left = key_to_qt(Format::Whkd, "left").unwrap(); + /// assert_eq!(Combo::new(Mods::CTRL | Mods::ALT, left).to_qt(), 0x0c00_0000 | 0x0100_0012); + /// ``` + pub const fn to_qt(self) -> u32 { + self.mods.0 | self.key.0 + } +} + +/// Writes the combo in Qt's portable text, the form of an `X-KDE-Shortcuts` value: the modifiers +/// in Qt's order (`Meta`, `Ctrl`, `Alt`, `Shift`), each followed by `+`, then the key. +impl fmt::Display for Combo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for (flag, name) in [ + (Mods::META, "Meta"), + (Mods::CTRL, "Ctrl"), + (Mods::ALT, "Alt"), + (Mods::SHIFT, "Shift"), + ] { + if self.mods.contains(flag) { + write!(f, "{name}+")?; + } + } + write!(f, "{}", self.key) + } +} + +/// Returns the key a name stands for in the vocabulary of a format, or `None` when the name is +/// not a key this crate knows. +/// +/// Every format shares the letters (`a` or `A`), the digits and the function keys `f1` to `f24`. +/// The rest of each vocabulary is the format's own: +/// +/// - **skhd**: its literal keywords (`return`, `escape`, `pageup`, `sound_up`, `play`...), a +/// macOS keycode in hex (`0x21`, read as the key at that position on a US keyboard), and the +/// punctuation characters ``[ ] ; = - ' . / \ ` ,``. +/// - **whkd**: Windows virtual key names, with or without `VK_` (`return`, `back`, `prior`, +/// `oem_4`, `volume_up`...), read as on a US keyboard. +/// - **sxhkd**: X keysym names (`Return`, `BackSpace`, `bracketleft`, `exclam`, `XF86AudioPlay`...). +/// +/// Names are matched without regard to case. Keypad keys, mouse buttons and the keys Qt has no +/// portable name for are not known. +/// +/// # Example +/// +/// ```rust +/// use komorebi_hotkeys::Format; +/// use komorebi_hotkeys::qt::key_to_qt; +/// +/// // the key right of P, in all three vocabularies +/// let bracket = key_to_qt(Format::Skhd, "0x21"); +/// assert_eq!(bracket.map(|k| k.to_string()).as_deref(), Some("[")); +/// assert_eq!(key_to_qt(Format::Whkd, "oem_4"), bracket); +/// assert_eq!(key_to_qt(Format::Sxhkd, "bracketleft"), bracket); +/// +/// // a name means what its format says: whkd's `back` is Backspace +/// assert_eq!(key_to_qt(Format::Whkd, "back").unwrap().to_string(), "Backspace"); +/// assert_eq!(key_to_qt(Format::Sxhkd, "XF86Back").unwrap().to_string(), "Back"); +/// assert_eq!(key_to_qt(Format::Skhd, "0xFF"), None); +/// ``` +pub fn key_to_qt(format: Format, name: &str) -> Option { + let name = match format { + Format::Whkd if name.len() > 3 && name[..3].eq_ignore_ascii_case("vk_") => &name[3..], + _ => name, + }; + + let mut chars = name.chars(); + if let (Some(c), None) = (chars.next(), chars.next()) + && c.is_ascii_alphanumeric() + { + return Some(Key(u32::from(c.to_ascii_uppercase()))); + } + + let lower = name.to_ascii_lowercase(); + if let Some(digits) = lower.strip_prefix('f') + && !digits.starts_with('0') + && digits.bytes().all(|b| b.is_ascii_digit()) + && let Ok(n) = digits.parse::() + && (1..=24).contains(&n) + { + return Some(Key(F1 + n - 1)); + } + + let code = match format { + Format::Skhd => { + if let Some(hex) = lower.strip_prefix("0x") { + if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let code = u32::from_str_radix(hex, 16).ok()?; + return macos_keycode(code).map(Key); + } + lookup(SKHD, &lower) + } + Format::Whkd => lookup(WHKD, &lower), + Format::Sxhkd => lookup(SXHKD, &lower), + }; + code.map(Key) +} + +fn lookup(table: &[(&str, u32)], name: &str) -> Option { + table + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, code)| *code) +} + +/// The symbol Shift and this key type on a US keyboard, for the keys whose symbol changes. +fn shifted_symbol(key: Key) -> Option { + SHIFTED + .iter() + .find(|(plain, _)| key.0 == u32::from(*plain)) + .map(|(_, shifted)| Key(u32::from(*shifted))) +} + +/// The keys of a US keyboard that type a different symbol with Shift, and that symbol. +const SHIFTED: &[(char, char)] = &[ + ('1', '!'), + ('2', '@'), + ('3', '#'), + ('4', '$'), + ('5', '%'), + ('6', '^'), + ('7', '&'), + ('8', '*'), + ('9', '('), + ('0', ')'), + ('-', '_'), + ('=', '+'), + ('[', '{'), + (']', '}'), + (';', ':'), + ('\'', '"'), + (',', '<'), + ('.', '>'), + ('/', '?'), + ('\\', '|'), + ('`', '~'), +]; + +const F1: u32 = 0x0100_0030; +const ESCAPE: u32 = 0x0100_0000; +const TAB: u32 = 0x0100_0001; +const BACKSPACE: u32 = 0x0100_0003; +const RETURN: u32 = 0x0100_0004; +const INSERT: u32 = 0x0100_0006; +const DELETE: u32 = 0x0100_0007; +const PAUSE: u32 = 0x0100_0008; +const PRINT: u32 = 0x0100_0009; +const SYSREQ: u32 = 0x0100_000a; +const CLEAR: u32 = 0x0100_000b; +const HOME: u32 = 0x0100_0010; +const END: u32 = 0x0100_0011; +const LEFT: u32 = 0x0100_0012; +const UP: u32 = 0x0100_0013; +const RIGHT: u32 = 0x0100_0014; +const DOWN: u32 = 0x0100_0015; +const PAGE_UP: u32 = 0x0100_0016; +const PAGE_DOWN: u32 = 0x0100_0017; +const CAPS_LOCK: u32 = 0x0100_0024; +const NUM_LOCK: u32 = 0x0100_0025; +const SCROLL_LOCK: u32 = 0x0100_0026; +const MENU: u32 = 0x0100_0055; +const HELP: u32 = 0x0100_0058; +const BACK: u32 = 0x0100_0061; +const FORWARD: u32 = 0x0100_0062; +const STOP: u32 = 0x0100_0063; +const REFRESH: u32 = 0x0100_0064; +const VOLUME_DOWN: u32 = 0x0100_0070; +const VOLUME_MUTE: u32 = 0x0100_0071; +const VOLUME_UP: u32 = 0x0100_0072; +const MEDIA_PLAY: u32 = 0x0100_0080; +const MEDIA_STOP: u32 = 0x0100_0081; +const MEDIA_PREVIOUS: u32 = 0x0100_0082; +const MEDIA_NEXT: u32 = 0x0100_0083; +const MEDIA_RECORD: u32 = 0x0100_0084; +const MEDIA_PAUSE: u32 = 0x0100_0085; +const HOME_PAGE: u32 = 0x0100_0090; +const FAVORITES: u32 = 0x0100_0091; +const SEARCH: u32 = 0x0100_0092; +const LAUNCH_MAIL: u32 = 0x0100_00a0; +const LAUNCH_MEDIA: u32 = 0x0100_00a1; +const MON_BRIGHTNESS_UP: u32 = 0x0100_00b2; +const MON_BRIGHTNESS_DOWN: u32 = 0x0100_00b3; +const KEYBOARD_LIGHT_ON_OFF: u32 = 0x0100_00b4; +const KEYBOARD_BRIGHTNESS_UP: u32 = 0x0100_00b5; +const KEYBOARD_BRIGHTNESS_DOWN: u32 = 0x0100_00b6; +const POWER_OFF: u32 = 0x0100_00b7; +const WAKE_UP: u32 = 0x0100_00b8; +const EJECT: u32 = 0x0100_00b9; +const SCREEN_SAVER: u32 = 0x0100_00ba; +const WWW: u32 = 0x0100_00bb; +const AUDIO_REWIND: u32 = 0x0100_00c5; +const CALCULATOR: u32 = 0x0100_00cb; +const DISPLAY: u32 = 0x0100_00d1; +const EXPLORER: u32 = 0x0100_00d5; +const CALENDAR: u32 = 0x0100_00e4; +const TERMINAL: u32 = 0x0100_00f0; +const TOOLS: u32 = 0x0100_00f1; +const AUDIO_FORWARD: u32 = 0x0100_0102; +const MIC_MUTE: u32 = 0x0100_0113; +const SELECT: u32 = 0x0101_0000; +const SLEEP: u32 = 0x0102_0004; + +/// Qt's portable text for the keys outside printable ASCII that a vocabulary below can name. +const NAMED: &[(u32, &str)] = &[ + (ESCAPE, "Esc"), + (TAB, "Tab"), + (BACKSPACE, "Backspace"), + (RETURN, "Return"), + (INSERT, "Ins"), + (DELETE, "Del"), + (PAUSE, "Pause"), + (PRINT, "Print"), + (SYSREQ, "SysReq"), + (CLEAR, "Clear"), + (HOME, "Home"), + (END, "End"), + (LEFT, "Left"), + (UP, "Up"), + (RIGHT, "Right"), + (DOWN, "Down"), + (PAGE_UP, "PgUp"), + (PAGE_DOWN, "PgDown"), + (CAPS_LOCK, "CapsLock"), + (NUM_LOCK, "NumLock"), + (SCROLL_LOCK, "ScrollLock"), + (MENU, "Menu"), + (HELP, "Help"), + (BACK, "Back"), + (FORWARD, "Forward"), + (STOP, "Stop"), + (REFRESH, "Refresh"), + (VOLUME_DOWN, "Volume Down"), + (VOLUME_MUTE, "Volume Mute"), + (VOLUME_UP, "Volume Up"), + (MEDIA_PLAY, "Media Play"), + (MEDIA_STOP, "Media Stop"), + (MEDIA_PREVIOUS, "Media Previous"), + (MEDIA_NEXT, "Media Next"), + (MEDIA_RECORD, "Media Record"), + (MEDIA_PAUSE, "Media Pause"), + (HOME_PAGE, "Home Page"), + (FAVORITES, "Favorites"), + (SEARCH, "Search"), + (LAUNCH_MAIL, "Launch Mail"), + (LAUNCH_MEDIA, "Launch Media"), + (MON_BRIGHTNESS_UP, "Monitor Brightness Up"), + (MON_BRIGHTNESS_DOWN, "Monitor Brightness Down"), + (KEYBOARD_LIGHT_ON_OFF, "Keyboard Light On/Off"), + (KEYBOARD_BRIGHTNESS_UP, "Keyboard Brightness Up"), + (KEYBOARD_BRIGHTNESS_DOWN, "Keyboard Brightness Down"), + (POWER_OFF, "Power Off"), + (WAKE_UP, "Wake Up"), + (EJECT, "Eject"), + (SCREEN_SAVER, "Screensaver"), + (WWW, "WWW"), + (AUDIO_REWIND, "Media Rewind"), + (CALCULATOR, "Calculator"), + (DISPLAY, "Display"), + (EXPLORER, "Browser"), + (CALENDAR, "Calendar"), + (TERMINAL, "Terminal"), + (TOOLS, "Tools"), + (AUDIO_FORWARD, "Media Fast Forward"), + (MIC_MUTE, "Microphone Mute"), + (SELECT, "Select"), + (SLEEP, "Sleep"), +]; + +fn function_key_name(code: u32) -> Option<&'static str> { + const NAMES: [&str; 24] = [ + "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", + "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24", + ]; + let index = code.checked_sub(F1)?; + NAMES.get(usize::try_from(index).ok()?).copied() +} + +const fn ch(c: char) -> u32 { + c as u32 +} + +/// skhd's literal keywords and the punctuation characters, in lower case. +const SKHD: &[(&str, u32)] = &[ + ("return", RETURN), + ("enter", RETURN), + ("tab", TAB), + ("space", 0x20), + ("backspace", BACKSPACE), + ("delete", DELETE), + ("escape", ESCAPE), + ("home", HOME), + ("end", END), + ("pageup", PAGE_UP), + ("pagedown", PAGE_DOWN), + ("insert", INSERT), + ("left", LEFT), + ("right", RIGHT), + ("up", UP), + ("down", DOWN), + ("sound_up", VOLUME_UP), + ("sound_down", VOLUME_DOWN), + ("mute", VOLUME_MUTE), + ("brightness_up", MON_BRIGHTNESS_UP), + ("brightness_down", MON_BRIGHTNESS_DOWN), + ("illumination_up", KEYBOARD_BRIGHTNESS_UP), + ("illumination_down", KEYBOARD_BRIGHTNESS_DOWN), + ("play", MEDIA_PLAY), + ("previous", MEDIA_PREVIOUS), + ("next", MEDIA_NEXT), + ("rewind", AUDIO_REWIND), + ("fast", AUDIO_FORWARD), + ("[", ch('[')), + ("]", ch(']')), + (";", ch(';')), + ("=", ch('=')), + ("-", ch('-')), + ("'", ch('\'')), + (".", ch('.')), + ("/", ch('/')), + ("\\", ch('\\')), + ("`", ch('`')), + (",", ch(',')), +]; + +/// The macOS virtual keycodes (`kVK_ANSI_*` and the named keys) skhd takes in hex, as the key at +/// that position on a US keyboard. +fn macos_keycode(code: u32) -> Option { + Some(match code { + 0x00 => ch('A'), + 0x01 => ch('S'), + 0x02 => ch('D'), + 0x03 => ch('F'), + 0x04 => ch('H'), + 0x05 => ch('G'), + 0x06 => ch('Z'), + 0x07 => ch('X'), + 0x08 => ch('C'), + 0x09 => ch('V'), + 0x0B => ch('B'), + 0x0C => ch('Q'), + 0x0D => ch('W'), + 0x0E => ch('E'), + 0x0F => ch('R'), + 0x10 => ch('Y'), + 0x11 => ch('T'), + 0x12 => ch('1'), + 0x13 => ch('2'), + 0x14 => ch('3'), + 0x15 => ch('4'), + 0x16 => ch('6'), + 0x17 => ch('5'), + 0x18 => ch('='), + 0x19 => ch('9'), + 0x1A => ch('7'), + 0x1B => ch('-'), + 0x1C => ch('8'), + 0x1D => ch('0'), + 0x1E => ch(']'), + 0x1F => ch('O'), + 0x20 => ch('U'), + 0x21 => ch('['), + 0x22 => ch('I'), + 0x23 => ch('P'), + 0x24 => RETURN, + 0x25 => ch('L'), + 0x26 => ch('J'), + 0x27 => ch('\''), + 0x28 => ch('K'), + 0x29 => ch(';'), + 0x2A => ch('\\'), + 0x2B => ch(','), + 0x2C => ch('/'), + 0x2D => ch('N'), + 0x2E => ch('M'), + 0x2F => ch('.'), + 0x30 => TAB, + 0x31 => 0x20, + 0x32 => ch('`'), + 0x33 => BACKSPACE, + 0x35 => ESCAPE, + 0x73 => HOME, + 0x74 => PAGE_UP, + 0x75 => DELETE, + 0x77 => END, + 0x79 => PAGE_DOWN, + 0x7B => LEFT, + 0x7C => RIGHT, + 0x7D => DOWN, + 0x7E => UP, + 0x7A => F1, + 0x78 => F1 + 1, + 0x63 => F1 + 2, + 0x76 => F1 + 3, + 0x60 => F1 + 4, + 0x61 => F1 + 5, + 0x62 => F1 + 6, + 0x64 => F1 + 7, + 0x65 => F1 + 8, + 0x6D => F1 + 9, + 0x67 => F1 + 10, + 0x6F => F1 + 11, + _ => return None, + }) +} + +/// The Windows virtual key names whkd accepts that are not letters, digits or function keys, +/// without their `VK_` prefix. +const WHKD: &[(&str, u32)] = &[ + ("back", BACKSPACE), + ("tab", TAB), + ("clear", CLEAR), + ("return", RETURN), + ("pause", PAUSE), + ("capital", CAPS_LOCK), + ("escape", ESCAPE), + ("space", 0x20), + ("prior", PAGE_UP), + ("next", PAGE_DOWN), + ("end", END), + ("home", HOME), + ("left", LEFT), + ("up", UP), + ("right", RIGHT), + ("down", DOWN), + ("select", SELECT), + ("snapshot", PRINT), + ("insert", INSERT), + ("delete", DELETE), + ("help", HELP), + ("apps", MENU), + ("sleep", SLEEP), + ("numlock", NUM_LOCK), + ("scroll", SCROLL_LOCK), + ("browser_back", BACK), + ("browser_forward", FORWARD), + ("browser_refresh", REFRESH), + ("browser_stop", STOP), + ("browser_search", SEARCH), + ("browser_favorites", FAVORITES), + ("browser_home", HOME_PAGE), + ("volume_mute", VOLUME_MUTE), + ("volume_down", VOLUME_DOWN), + ("volume_up", VOLUME_UP), + ("media_next_track", MEDIA_NEXT), + ("media_prev_track", MEDIA_PREVIOUS), + ("media_stop", MEDIA_STOP), + ("media_play_pause", MEDIA_PLAY), + ("launch_mail", LAUNCH_MAIL), + ("launch_media_select", LAUNCH_MEDIA), + ("oem_1", ch(';')), + ("oem_plus", ch('=')), + ("oem_comma", ch(',')), + ("oem_minus", ch('-')), + ("oem_period", ch('.')), + ("oem_2", ch('/')), + ("oem_3", ch('`')), + ("oem_4", ch('[')), + ("oem_5", ch('\\')), + ("oem_6", ch(']')), + ("oem_7", ch('\'')), +]; + +/// The X keysym names sxhkd accepts that are not letters, digits or function keys, mapped the way +/// Qt maps the keysym. +const SXHKD: &[(&str, u32)] = &[ + ("Return", RETURN), + ("Tab", TAB), + ("space", 0x20), + ("BackSpace", BACKSPACE), + ("Escape", ESCAPE), + ("Delete", DELETE), + ("Insert", INSERT), + ("Home", HOME), + ("End", END), + ("Prior", PAGE_UP), + ("Page_Up", PAGE_UP), + ("Next", PAGE_DOWN), + ("Page_Down", PAGE_DOWN), + ("Left", LEFT), + ("Up", UP), + ("Right", RIGHT), + ("Down", DOWN), + ("Print", PRINT), + ("Pause", PAUSE), + ("Sys_Req", SYSREQ), + ("Scroll_Lock", SCROLL_LOCK), + ("Caps_Lock", CAPS_LOCK), + ("Num_Lock", NUM_LOCK), + ("Menu", MENU), + ("Help", HELP), + ("exclam", ch('!')), + ("quotedbl", ch('"')), + ("numbersign", ch('#')), + ("dollar", ch('$')), + ("percent", ch('%')), + ("ampersand", ch('&')), + ("apostrophe", ch('\'')), + ("quoteright", ch('\'')), + ("parenleft", ch('(')), + ("parenright", ch(')')), + ("asterisk", ch('*')), + ("plus", ch('+')), + ("comma", ch(',')), + ("minus", ch('-')), + ("period", ch('.')), + ("slash", ch('/')), + ("colon", ch(':')), + ("semicolon", ch(';')), + ("less", ch('<')), + ("equal", ch('=')), + ("greater", ch('>')), + ("question", ch('?')), + ("at", ch('@')), + ("bracketleft", ch('[')), + ("backslash", ch('\\')), + ("bracketright", ch(']')), + ("asciicircum", ch('^')), + ("underscore", ch('_')), + ("grave", ch('`')), + ("quoteleft", ch('`')), + ("braceleft", ch('{')), + ("bar", ch('|')), + ("braceright", ch('}')), + ("asciitilde", ch('~')), + ("XF86AudioRaiseVolume", VOLUME_UP), + ("XF86AudioLowerVolume", VOLUME_DOWN), + ("XF86AudioMute", VOLUME_MUTE), + ("XF86AudioMicMute", MIC_MUTE), + ("XF86AudioPlay", MEDIA_PLAY), + ("XF86AudioStop", MEDIA_STOP), + ("XF86AudioPrev", MEDIA_PREVIOUS), + ("XF86AudioNext", MEDIA_NEXT), + ("XF86AudioPause", MEDIA_PAUSE), + ("XF86AudioRecord", MEDIA_RECORD), + ("XF86AudioRewind", AUDIO_REWIND), + ("XF86AudioForward", AUDIO_FORWARD), + ("XF86AudioMedia", LAUNCH_MEDIA), + ("XF86MonBrightnessUp", MON_BRIGHTNESS_UP), + ("XF86MonBrightnessDown", MON_BRIGHTNESS_DOWN), + ("XF86KbdLightOnOff", KEYBOARD_LIGHT_ON_OFF), + ("XF86KbdBrightnessUp", KEYBOARD_BRIGHTNESS_UP), + ("XF86KbdBrightnessDown", KEYBOARD_BRIGHTNESS_DOWN), + ("XF86Back", BACK), + ("XF86Forward", FORWARD), + ("XF86Stop", STOP), + ("XF86Refresh", REFRESH), + ("XF86Favorites", FAVORITES), + ("XF86HomePage", HOME_PAGE), + ("XF86Search", SEARCH), + ("XF86Mail", LAUNCH_MAIL), + ("XF86Calculator", CALCULATOR), + ("XF86Calendar", CALENDAR), + ("XF86Explorer", EXPLORER), + ("XF86WWW", WWW), + ("XF86Terminal", TERMINAL), + ("XF86Tools", TOOLS), + ("XF86Display", DISPLAY), + ("XF86ScreenSaver", SCREEN_SAVER), + ("XF86Eject", EJECT), + ("XF86Sleep", SLEEP), + ("XF86PowerOff", POWER_OFF), + ("XF86WakeUp", WAKE_UP), +]; + +#[cfg(test)] +mod tests { + use super::*; + + fn combo(format: Format, mods: Mods, name: &str) -> String { + Combo::new(mods, key_to_qt(format, name).unwrap()).to_string() + } + + #[test] + fn modifiers_are_written_in_the_order_qt_writes_them() { + let all = Mods::SHIFT | Mods::ALT | Mods::CTRL | Mods::META; + assert_eq!(combo(Format::Skhd, all, "a"), "Meta+Ctrl+Alt+Shift+A"); + assert_eq!( + combo(Format::Skhd, Mods::ALT | Mods::SHIFT, "return"), + "Alt+Shift+Return" + ); + assert_eq!( + combo(Format::Skhd, Mods::CTRL | Mods::ALT, "left"), + "Ctrl+Alt+Left" + ); + assert_eq!(combo(Format::Skhd, Mods::ALT, "1"), "Alt+1"); + } + + #[test] + fn macos_keycodes_become_the_key_they_are() { + let alt_shift = Mods::ALT | Mods::SHIFT; + assert_eq!(combo(Format::Skhd, alt_shift, "0x21"), "Alt+{"); + assert_eq!(combo(Format::Skhd, alt_shift, "0x1E"), "Alt+}"); + assert_eq!(combo(Format::Skhd, Mods::ALT, "0x29"), "Alt+;"); + assert_eq!(combo(Format::Skhd, Mods::ALT, "0x18"), "Alt+="); + assert_eq!(combo(Format::Skhd, Mods::ALT, "0x1B"), "Alt+-"); + assert_eq!(key_to_qt(Format::Skhd, "0xFF"), None); + assert_eq!(key_to_qt(Format::Skhd, "0xzz"), None); + } + + #[test] + fn shift_on_a_symbol_key_is_the_symbol_it_types() { + let alt_shift = Mods::ALT | Mods::SHIFT; + assert_eq!(combo(Format::Skhd, alt_shift, "1"), "Alt+!"); + assert_eq!(combo(Format::Skhd, alt_shift, "0x29"), "Alt+:"); + assert_eq!(combo(Format::Skhd, alt_shift, "0x18"), "Alt++"); + assert_eq!(combo(Format::Skhd, alt_shift, "0x1B"), "Alt+_"); + assert_eq!( + combo(Format::Skhd, Mods::CTRL | alt_shift, "9"), + "Ctrl+Alt+(" + ); + // letters and named keys keep their Shift + assert_eq!(combo(Format::Skhd, alt_shift, "h"), "Alt+Shift+H"); + assert_eq!(combo(Format::Skhd, alt_shift, "return"), "Alt+Shift+Return"); + assert_eq!( + combo(Format::Skhd, Mods::CTRL | Mods::SHIFT, "left"), + "Ctrl+Shift+Left" + ); + // Shift on the symbol itself goes too + assert_eq!(combo(Format::Sxhkd, alt_shift, "exclam"), "Alt+!"); + assert_eq!(combo(Format::Sxhkd, Mods::ALT, "exclam"), "Alt+!"); + } + + #[test] + fn every_shifted_pair_follows_the_rule() { + for (plain, shifted) in SHIFTED { + let combo = Combo::new(Mods::META | Mods::SHIFT, Key(u32::from(*plain))); + assert_eq!(combo.to_string(), format!("Meta+{shifted}"), "{plain}"); + } + } + + #[test] + fn the_integer_is_the_key_with_the_flags() { + let h = key_to_qt(Format::Whkd, "h").unwrap(); + assert_eq!(Combo::new(Mods::ALT, h).to_qt(), 0x0800_0048); + let f12 = key_to_qt(Format::Sxhkd, "F12").unwrap(); + assert_eq!( + Combo::new(Mods::META, f12).to_qt(), + 0x1000_0000 | 0x0100_003b + ); + assert_eq!( + Combo::new( + Mods::ALT | Mods::SHIFT, + key_to_qt(Format::Skhd, "1").unwrap() + ) + .to_qt(), + 0x0800_0000 | 0x21 + ); + } + + #[test] + fn the_three_vocabularies_name_the_same_keys() { + for (skhd, whkd, sxhkd, text) in [ + ("return", "return", "Return", "Return"), + ("escape", "escape", "Escape", "Esc"), + ("backspace", "back", "BackSpace", "Backspace"), + ("delete", "delete", "Delete", "Del"), + ("pageup", "prior", "Prior", "PgUp"), + ("pagedown", "next", "Next", "PgDown"), + ("space", "space", "space", "Space"), + ("0x29", "oem_1", "semicolon", ";"), + ("0x27", "oem_7", "apostrophe", "'"), + ("0x32", "oem_3", "grave", "`"), + ("0x2A", "oem_5", "backslash", "\\"), + ("0x2C", "oem_2", "slash", "/"), + ("0x2F", "oem_period", "period", "."), + ("0x2B", "oem_comma", "comma", ","), + ("f1", "F1", "F1", "F1"), + ("0x6F", "f12", "F12", "F12"), + ("sound_up", "volume_up", "XF86AudioRaiseVolume", "Volume Up"), + ("play", "media_play_pause", "XF86AudioPlay", "Media Play"), + ] { + let s = key_to_qt(Format::Skhd, skhd).unwrap(); + assert_eq!(key_to_qt(Format::Whkd, whkd), Some(s), "{whkd}"); + assert_eq!(key_to_qt(Format::Sxhkd, sxhkd), Some(s), "{sxhkd}"); + assert_eq!(s.to_string(), text); + } + } + + #[test] + fn names_are_matched_without_regard_to_case() { + assert_eq!( + key_to_qt(Format::Whkd, "VK_OEM_4"), + key_to_qt(Format::Whkd, "oem_4") + ); + assert_eq!( + key_to_qt(Format::Sxhkd, "return"), + key_to_qt(Format::Sxhkd, "Return") + ); + assert_eq!(key_to_qt(Format::Skhd, "H"), key_to_qt(Format::Skhd, "h")); + // whkd takes every name with or without `VK_` + assert_eq!( + key_to_qt(Format::Whkd, "vk_a"), + key_to_qt(Format::Whkd, "a") + ); + assert_eq!( + key_to_qt(Format::Whkd, "VK_0"), + key_to_qt(Format::Whkd, "0") + ); + } + + #[test] + fn unknown_names_are_none() { + for (format, name) in [ + (Format::Skhd, "f25"), + (Format::Skhd, "f01"), + (Format::Skhd, "fn"), + (Format::Whkd, "numpad1"), + (Format::Whkd, "0x21"), + (Format::Sxhkd, "button1"), + (Format::Sxhkd, "KP_1"), + (Format::Sxhkd, "["), + (Format::Whkd, ""), + ] { + assert_eq!(key_to_qt(format, name), None, "{format:?} {name}"); + } + } + + #[test] + fn every_named_key_has_portable_text() { + let tables = [SKHD, WHKD, SXHKD]; + for (name, code) in tables.iter().flat_map(|t| t.iter()) { + let text = Key(*code).to_string(); + assert!(!text.starts_with("0x"), "{name} has no name"); + } + for n in 1..=24 { + assert_eq!( + key_to_qt(Format::Sxhkd, &format!("F{n}")) + .unwrap() + .to_string(), + format!("F{n}") + ); + } + } +} diff --git a/komorebi-hotkeys/tests/corpus.rs b/komorebi-hotkeys/tests/corpus.rs new file mode 100644 index 00000000..00b2cdaa --- /dev/null +++ b/komorebi-hotkeys/tests/corpus.rs @@ -0,0 +1,65 @@ +//! The fixture corpus: key binding files that say the same thing in each format that can say it. +//! +//! Each case is a file per format in `tests/fixtures`, `.skhdrc`, `.whkdrc` and +//! `.sxhkdrc`, for the formats that can express the case. The files of a case mean the same +//! keymap, and start with the same comment, which says what the case is about. + +use std::path::PathBuf; + +/// Every case, and the formats it is written in. +const CASES: &[(&str, &[&str])] = &[ + ("plain", &["skhdrc", "whkdrc", "sxhkdrc"]), + ("modifiers", &["skhdrc", "whkdrc", "sxhkdrc"]), + ("keycodes", &["skhdrc", "whkdrc", "sxhkdrc"]), + ("comments", &["skhdrc", "whkdrc", "sxhkdrc"]), + ("braces", &["skhdrc", "whkdrc", "sxhkdrc"]), + ("sample", &["skhdrc", "whkdrc", "sxhkdrc"]), + ("scopes", &["skhdrc", "whkdrc"]), + ("define", &["skhdrc", "whkdrc"]), + ("blacklist", &["skhdrc"]), + ("modes", &["skhdrc"]), + ("pause", &["whkdrc"]), + ("chords", &["sxhkdrc"]), + ("release", &["sxhkdrc"]), +]; + +fn fixtures() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} + +fn read(case: &str, extension: &str) -> String { + let path = fixtures().join(format!("{case}.{extension}")); + std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) +} + +#[test] +fn the_corpus_is_the_files_the_table_names() { + let mut on_disk: Vec = std::fs::read_dir(fixtures()) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + on_disk.sort(); + + let mut named: Vec = CASES + .iter() + .flat_map(|(case, extensions)| extensions.iter().map(move |e| format!("{case}.{e}"))) + .collect(); + named.sort(); + + assert_eq!(on_disk, named); +} + +#[test] +fn the_files_of_a_case_say_what_it_is_about_in_the_same_words() { + for (case, extensions) in CASES { + let first_lines: Vec = extensions + .iter() + .map(|e| read(case, e).lines().next().unwrap_or_default().to_string()) + .collect(); + assert!(first_lines[0].starts_with("# "), "{case}: {first_lines:?}"); + assert!( + first_lines.iter().all(|line| *line == first_lines[0]), + "{case}: {first_lines:?}" + ); + } +} diff --git a/komorebi-hotkeys/tests/fixtures/blacklist.skhdrc b/komorebi-hotkeys/tests/fixtures/blacklist.skhdrc new file mode 100644 index 00000000..06c102ac --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/blacklist.skhdrc @@ -0,0 +1,7 @@ +# no binding is active while steam or dota2 has the focus +.blacklist [ + "steam" + "dota2" +] + +alt - h : komorebic focus left diff --git a/komorebi-hotkeys/tests/fixtures/braces.skhdrc b/komorebi-hotkeys/tests/fixtures/braces.skhdrc new file mode 100644 index 00000000..61ef58c8 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/braces.skhdrc @@ -0,0 +1,11 @@ +# what sxhkd writes with braces, one line each +alt - h : komorebic focus left +alt - j : komorebic focus down +alt - k : komorebic focus up +alt - l : komorebic focus right +alt - 1 : komorebic focus-workspace 0 +alt - 2 : komorebic focus-workspace 1 +alt - 3 : komorebic focus-workspace 2 +alt + shift - 1 : komorebic move-to-workspace 0 +alt + shift - 2 : komorebic move-to-workspace 1 +alt + shift - 3 : komorebic move-to-workspace 2 diff --git a/komorebi-hotkeys/tests/fixtures/braces.sxhkdrc b/komorebi-hotkeys/tests/fixtures/braces.sxhkdrc new file mode 100644 index 00000000..7c587144 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/braces.sxhkdrc @@ -0,0 +1,5 @@ +# what sxhkd writes with braces, one line each +alt + {h,j,k,l} + komorebic focus {left,down,up,right} +alt + {_,shift + }{1-3} + komorebic {focus,move-to}-workspace {0-2} diff --git a/komorebi-hotkeys/tests/fixtures/braces.whkdrc b/komorebi-hotkeys/tests/fixtures/braces.whkdrc new file mode 100644 index 00000000..cfada016 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/braces.whkdrc @@ -0,0 +1,13 @@ +# what sxhkd writes with braces, one line each +.shell pwsh + +alt + h : komorebic focus left +alt + j : komorebic focus down +alt + k : komorebic focus up +alt + l : komorebic focus right +alt + 1 : komorebic focus-workspace 0 +alt + 2 : komorebic focus-workspace 1 +alt + 3 : komorebic focus-workspace 2 +alt + shift + 1 : komorebic move-to-workspace 0 +alt + shift + 2 : komorebic move-to-workspace 1 +alt + shift + 3 : komorebic move-to-workspace 2 diff --git a/komorebi-hotkeys/tests/fixtures/chords.sxhkdrc b/komorebi-hotkeys/tests/fixtures/chords.sxhkdrc new file mode 100644 index 00000000..f71ae56c --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/chords.sxhkdrc @@ -0,0 +1,7 @@ +# chord chains: alt + w and then a second key; alt + r and then any number of h or l +alt + w ; h + komorebic move left +alt + w ; l + komorebic move right +alt + r : {h,l} + komorebic resize-edge {left,right} increase diff --git a/komorebi-hotkeys/tests/fixtures/comments.skhdrc b/komorebi-hotkeys/tests/fixtures/comments.skhdrc new file mode 100644 index 00000000..b6cb5868 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/comments.skhdrc @@ -0,0 +1,6 @@ +# comments, trailing comments and a command continued on the next line + +# a comment on a line of its own +alt - h : komorebic focus left # a trailing comment is not part of the command +alt - x : komorebic \ + flip-layout horizontal diff --git a/komorebi-hotkeys/tests/fixtures/comments.sxhkdrc b/komorebi-hotkeys/tests/fixtures/comments.sxhkdrc new file mode 100644 index 00000000..c1fb0361 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/comments.sxhkdrc @@ -0,0 +1,8 @@ +# comments, trailing comments and a command continued on the next line + +# a comment on a line of its own +alt + h + komorebic focus left # a trailing comment is not part of the command +alt + x + komorebic \ + flip-layout horizontal diff --git a/komorebi-hotkeys/tests/fixtures/comments.whkdrc b/komorebi-hotkeys/tests/fixtures/comments.whkdrc new file mode 100644 index 00000000..eeabfae9 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/comments.whkdrc @@ -0,0 +1,6 @@ +# comments, trailing comments and a command continued on the next line +.shell pwsh + +# a comment on a line of its own +alt + h : komorebic focus left # a trailing comment is not part of the command +alt + x : komorebic flip-layout horizontal diff --git a/komorebi-hotkeys/tests/fixtures/define.skhdrc b/komorebi-hotkeys/tests/fixtures/define.skhdrc new file mode 100644 index 00000000..3c654459 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/define.skhdrc @@ -0,0 +1,10 @@ +# a group of applications and a command template, both from .define +.define browsers ["firefox", "chromium"] +.define focus : komorebic focus {{1}} + +alt - b [ + @browsers : komorebic toggle-monocle + * ~ +] +alt - h : @focus("left") +alt - l : @focus("right") diff --git a/komorebi-hotkeys/tests/fixtures/define.whkdrc b/komorebi-hotkeys/tests/fixtures/define.whkdrc new file mode 100644 index 00000000..0b3d1cfe --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/define.whkdrc @@ -0,0 +1,11 @@ +# a group of applications and a command template, both from .define +.shell pwsh + +alt + b [ + firefox : komorebic toggle-monocle + chromium : komorebic toggle-monocle + Default : Ignore +] + +alt + h : komorebic focus left +alt + l : komorebic focus right diff --git a/komorebi-hotkeys/tests/fixtures/keycodes.skhdrc b/komorebi-hotkeys/tests/fixtures/keycodes.skhdrc new file mode 100644 index 00000000..1f6897d3 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/keycodes.skhdrc @@ -0,0 +1,7 @@ +# keys that skhd can only name by their macOS keycode, a position on a US keyboard +alt - 0x21 : komorebic cycle-stack previous +alt - 0x1E : komorebic cycle-stack next +alt - 0x29 : komorebic unstack +alt - 0x18 : komorebic resize-axis horizontal increase +alt - 0x1B : komorebic resize-axis horizontal decrease +alt + shift - 0x21 : komorebic cycle-focus previous diff --git a/komorebi-hotkeys/tests/fixtures/keycodes.sxhkdrc b/komorebi-hotkeys/tests/fixtures/keycodes.sxhkdrc new file mode 100644 index 00000000..4f6f1406 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/keycodes.sxhkdrc @@ -0,0 +1,13 @@ +# keys that skhd can only name by their macOS keycode, a position on a US keyboard +alt + bracketleft + komorebic cycle-stack previous +alt + bracketright + komorebic cycle-stack next +alt + semicolon + komorebic unstack +alt + equal + komorebic resize-axis horizontal increase +alt + minus + komorebic resize-axis horizontal decrease +alt + shift + bracketleft + komorebic cycle-focus previous diff --git a/komorebi-hotkeys/tests/fixtures/keycodes.whkdrc b/komorebi-hotkeys/tests/fixtures/keycodes.whkdrc new file mode 100644 index 00000000..013e395b --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/keycodes.whkdrc @@ -0,0 +1,9 @@ +# keys that skhd can only name by their macOS keycode, a position on a US keyboard +.shell pwsh + +alt + oem_4 : komorebic cycle-stack previous +alt + oem_6 : komorebic cycle-stack next +alt + oem_1 : komorebic unstack +alt + oem_plus : komorebic resize-axis horizontal increase +alt + oem_minus : komorebic resize-axis horizontal decrease +alt + shift + oem_4 : komorebic cycle-focus previous diff --git a/komorebi-hotkeys/tests/fixtures/modes.skhdrc b/komorebi-hotkeys/tests/fixtures/modes.skhdrc new file mode 100644 index 00000000..74bf8511 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/modes.skhdrc @@ -0,0 +1,7 @@ +# alt - r enters a resize mode, escape leaves it, alt - q works in both +:: resize @ : notify-send resize +alt - r ; resize +resize < h : komorebic resize-edge left increase +resize < l : komorebic resize-edge right increase +resize < escape ; default +default, resize < alt - q : komorebic close diff --git a/komorebi-hotkeys/tests/fixtures/modifiers.skhdrc b/komorebi-hotkeys/tests/fixtures/modifiers.skhdrc new file mode 100644 index 00000000..2de9822e --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/modifiers.skhdrc @@ -0,0 +1,9 @@ +# every modifier, and Shift on a key that types a symbol +cmd - return : konsole +ctrl + alt - left : komorebic stack left +alt + shift - h : komorebic move left +ctrl + shift - right : komorebic resize-edge right increase +alt + shift - 1 : komorebic move-to-workspace 0 +ctrl + alt + shift - 9 : komorebic move-to-workspace 8 +hyper - a : komorebic retile +meh - m : komorebic toggle-monocle diff --git a/komorebi-hotkeys/tests/fixtures/modifiers.sxhkdrc b/komorebi-hotkeys/tests/fixtures/modifiers.sxhkdrc new file mode 100644 index 00000000..aa17d93a --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/modifiers.sxhkdrc @@ -0,0 +1,17 @@ +# every modifier, and Shift on a key that types a symbol +super + Return + konsole +ctrl + alt + Left + komorebic stack left +alt + shift + h + komorebic move left +ctrl + shift + Right + komorebic resize-edge right increase +alt + shift + 1 + komorebic move-to-workspace 0 +ctrl + alt + shift + 9 + komorebic move-to-workspace 8 +super + ctrl + alt + shift + a + komorebic retile +ctrl + alt + shift + m + komorebic toggle-monocle diff --git a/komorebi-hotkeys/tests/fixtures/modifiers.whkdrc b/komorebi-hotkeys/tests/fixtures/modifiers.whkdrc new file mode 100644 index 00000000..fd328941 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/modifiers.whkdrc @@ -0,0 +1,11 @@ +# every modifier, and Shift on a key that types a symbol +.shell pwsh + +win + return : konsole +ctrl + alt + left : komorebic stack left +alt + shift + h : komorebic move left +ctrl + shift + right : komorebic resize-edge right increase +alt + shift + 1 : komorebic move-to-workspace 0 +ctrl + alt + shift + 9 : komorebic move-to-workspace 8 +win + ctrl + alt + shift + a : komorebic retile +ctrl + alt + shift + m : komorebic toggle-monocle diff --git a/komorebi-hotkeys/tests/fixtures/pause.whkdrc b/komorebi-hotkeys/tests/fixtures/pause.whkdrc new file mode 100644 index 00000000..7f6c0b85 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/pause.whkdrc @@ -0,0 +1,6 @@ +# alt + shift + p turns every other binding off and on again +.shell pwsh +.pause alt + shift + p +.pause_hook komorebic toggle-pause + +alt + h : komorebic focus left diff --git a/komorebi-hotkeys/tests/fixtures/plain.skhdrc b/komorebi-hotkeys/tests/fixtures/plain.skhdrc new file mode 100644 index 00000000..ce5a6192 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/plain.skhdrc @@ -0,0 +1,6 @@ +# plain bindings: modifiers, a key and a command +alt - h : komorebic focus left +alt - j : komorebic focus down +alt - k : komorebic focus up +alt - l : komorebic focus right +alt - q : komorebic close diff --git a/komorebi-hotkeys/tests/fixtures/plain.sxhkdrc b/komorebi-hotkeys/tests/fixtures/plain.sxhkdrc new file mode 100644 index 00000000..0febedc7 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/plain.sxhkdrc @@ -0,0 +1,11 @@ +# plain bindings: modifiers, a key and a command +alt + h + komorebic focus left +alt + j + komorebic focus down +alt + k + komorebic focus up +alt + l + komorebic focus right +alt + q + komorebic close diff --git a/komorebi-hotkeys/tests/fixtures/plain.whkdrc b/komorebi-hotkeys/tests/fixtures/plain.whkdrc new file mode 100644 index 00000000..9b6666e7 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/plain.whkdrc @@ -0,0 +1,8 @@ +# plain bindings: modifiers, a key and a command +.shell pwsh + +alt + h : komorebic focus left +alt + j : komorebic focus down +alt + k : komorebic focus up +alt + l : komorebic focus right +alt + q : komorebic close diff --git a/komorebi-hotkeys/tests/fixtures/release.sxhkdrc b/komorebi-hotkeys/tests/fixtures/release.sxhkdrc new file mode 100644 index 00000000..41498b8f --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/release.sxhkdrc @@ -0,0 +1,3 @@ +# a binding that runs when the key is released +alt + @space + komorebic toggle-float diff --git a/komorebi-hotkeys/tests/fixtures/sample.skhdrc b/komorebi-hotkeys/tests/fixtures/sample.skhdrc new file mode 100644 index 00000000..36b68b79 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/sample.skhdrc @@ -0,0 +1,71 @@ +# the komorebi sample configuration + +# Focus windows +alt - h : komorebic focus left +alt - j : komorebic focus down +alt - k : komorebic focus up +alt - l : komorebic focus right +alt + shift - 0x21 : komorebic cycle-focus previous # 0x21 is [ +alt + shift - 0x1E : komorebic cycle-focus next # 0x1E is ] + +# Move windows +alt + shift - h : komorebic move left +alt + shift - j : komorebic move down +alt + shift - k : komorebic move up +alt + shift - l : komorebic move right +alt + shift - return : komorebic promote + +# Stack windows +ctrl + alt - left : komorebic stack left +ctrl + alt - down : komorebic stack down +ctrl + alt - up : komorebic stack up +ctrl + alt - right : komorebic stack right +alt - 0x29 : komorebic unstack # 0x29 is ; +alt - 0x21 : komorebic cycle-stack previous # 0x21 is [ +alt - 0x1E : komorebic cycle-stack next # 0x1E is ] + +# Workspace layer +alt + shift - 0x29 : komorebic toggle-workspace-layer # 0x29 is ; + +# Resize +alt - 0x18 : komorebic resize-axis horizontal increase # 0x18 is + +alt - 0x1B : komorebic resize-axis horizontal decrease # 0x1B is - +alt + shift - 0x18 : komorebic resize-axis vertical increase +alt + shift - 0x1B : komorebic resize-axis vertical decrease + +# Manipulate windows +alt - t : komorebic toggle-float +alt + shift - t : komorebic toggle-workspace-float-override +alt + shift - f : komorebic toggle-monocle + +# Window manager options +alt + shift - r : komorebic retile +alt - p : komorebic toggle-pause +alt - 0 : komorebic toggle-window-container-behaviour + +# Layouts +alt - x : komorebic flip-layout horizontal +alt - y : komorebic flip-layout vertical +alt + shift - x : komorebic session-float-rule + +# Workspaces +alt - 1 : komorebic focus-workspace 0 +alt - 2 : komorebic focus-workspace 1 +alt - 3 : komorebic focus-workspace 2 +alt - 4 : komorebic focus-workspace 3 +alt - 5 : komorebic focus-workspace 4 +alt - 6 : komorebic focus-workspace 5 +alt - 7 : komorebic focus-workspace 6 +alt - 8 : komorebic focus-workspace 7 +alt - 9 : komorebic focus-workspace 8 + +# Move windows across workspaces +alt + shift - 1 : komorebic move-to-workspace 0 +alt + shift - 2 : komorebic move-to-workspace 1 +alt + shift - 3 : komorebic move-to-workspace 2 +alt + shift - 4 : komorebic move-to-workspace 3 +alt + shift - 5 : komorebic move-to-workspace 4 +alt + shift - 6 : komorebic move-to-workspace 5 +alt + shift - 7 : komorebic move-to-workspace 6 +alt + shift - 8 : komorebic move-to-workspace 7 +alt + shift - 9 : komorebic move-to-workspace 8 \ No newline at end of file diff --git a/komorebi-hotkeys/tests/fixtures/sample.sxhkdrc b/komorebi-hotkeys/tests/fixtures/sample.sxhkdrc new file mode 100644 index 00000000..e2cf288e --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/sample.sxhkdrc @@ -0,0 +1,121 @@ +# the komorebi sample configuration + +# Focus windows +alt + h + komorebic focus left +alt + j + komorebic focus down +alt + k + komorebic focus up +alt + l + komorebic focus right +alt + shift + bracketleft + komorebic cycle-focus previous +alt + shift + bracketright + komorebic cycle-focus next + +# Move windows +alt + shift + h + komorebic move left +alt + shift + j + komorebic move down +alt + shift + k + komorebic move up +alt + shift + l + komorebic move right +alt + shift + Return + komorebic promote + +# Stack windows +ctrl + alt + Left + komorebic stack left +ctrl + alt + Down + komorebic stack down +ctrl + alt + Up + komorebic stack up +ctrl + alt + Right + komorebic stack right +alt + semicolon + komorebic unstack +alt + bracketleft + komorebic cycle-stack previous +alt + bracketright + komorebic cycle-stack next + +# Workspace layer +alt + shift + semicolon + komorebic toggle-workspace-layer + +# Resize +alt + equal + komorebic resize-axis horizontal increase +alt + minus + komorebic resize-axis horizontal decrease +alt + shift + equal + komorebic resize-axis vertical increase +alt + shift + minus + komorebic resize-axis vertical decrease + +# Manipulate windows +alt + t + komorebic toggle-float +alt + shift + t + komorebic toggle-workspace-float-override +alt + shift + f + komorebic toggle-monocle + +# Window manager options +alt + shift + r + komorebic retile +alt + p + komorebic toggle-pause +alt + 0 + komorebic toggle-window-container-behaviour + +# Layouts +alt + x + komorebic flip-layout horizontal +alt + y + komorebic flip-layout vertical +alt + shift + x + komorebic session-float-rule + +# Workspaces +alt + 1 + komorebic focus-workspace 0 +alt + 2 + komorebic focus-workspace 1 +alt + 3 + komorebic focus-workspace 2 +alt + 4 + komorebic focus-workspace 3 +alt + 5 + komorebic focus-workspace 4 +alt + 6 + komorebic focus-workspace 5 +alt + 7 + komorebic focus-workspace 6 +alt + 8 + komorebic focus-workspace 7 +alt + 9 + komorebic focus-workspace 8 + +# Move windows across workspaces +alt + shift + 1 + komorebic move-to-workspace 0 +alt + shift + 2 + komorebic move-to-workspace 1 +alt + shift + 3 + komorebic move-to-workspace 2 +alt + shift + 4 + komorebic move-to-workspace 3 +alt + shift + 5 + komorebic move-to-workspace 4 +alt + shift + 6 + komorebic move-to-workspace 5 +alt + shift + 7 + komorebic move-to-workspace 6 +alt + shift + 8 + komorebic move-to-workspace 7 +alt + shift + 9 + komorebic move-to-workspace 8 diff --git a/komorebi-hotkeys/tests/fixtures/sample.whkdrc b/komorebi-hotkeys/tests/fixtures/sample.whkdrc new file mode 100644 index 00000000..54d3979e --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/sample.whkdrc @@ -0,0 +1,72 @@ +# the komorebi sample configuration +.shell pwsh + +# Focus windows +alt + h : komorebic focus left +alt + j : komorebic focus down +alt + k : komorebic focus up +alt + l : komorebic focus right +alt + shift + oem_4 : komorebic cycle-focus previous # oem_4 is [ +alt + shift + oem_6 : komorebic cycle-focus next # oem_6 is ] + +# Move windows +alt + shift + h : komorebic move left +alt + shift + j : komorebic move down +alt + shift + k : komorebic move up +alt + shift + l : komorebic move right +alt + shift + return : komorebic promote + +# Stack windows +ctrl + alt + left : komorebic stack left +ctrl + alt + down : komorebic stack down +ctrl + alt + up : komorebic stack up +ctrl + alt + right : komorebic stack right +alt + oem_1 : komorebic unstack # oem_1 is ; +alt + oem_4 : komorebic cycle-stack previous # oem_4 is [ +alt + oem_6 : komorebic cycle-stack next # oem_6 is ] + +# Workspace layer +alt + shift + oem_1 : komorebic toggle-workspace-layer # oem_1 is ; + +# Resize +alt + oem_plus : komorebic resize-axis horizontal increase # oem_plus is + +alt + oem_minus : komorebic resize-axis horizontal decrease # oem_minus is - +alt + shift + oem_plus : komorebic resize-axis vertical increase +alt + shift + oem_minus : komorebic resize-axis vertical decrease + +# Manipulate windows +alt + t : komorebic toggle-float +alt + shift + t : komorebic toggle-workspace-float-override +alt + shift + f : komorebic toggle-monocle + +# Window manager options +alt + shift + r : komorebic retile +alt + p : komorebic toggle-pause +alt + 0 : komorebic toggle-window-container-behaviour + +# Layouts +alt + x : komorebic flip-layout horizontal +alt + y : komorebic flip-layout vertical +alt + shift + x : komorebic session-float-rule + +# Workspaces +alt + 1 : komorebic focus-workspace 0 +alt + 2 : komorebic focus-workspace 1 +alt + 3 : komorebic focus-workspace 2 +alt + 4 : komorebic focus-workspace 3 +alt + 5 : komorebic focus-workspace 4 +alt + 6 : komorebic focus-workspace 5 +alt + 7 : komorebic focus-workspace 6 +alt + 8 : komorebic focus-workspace 7 +alt + 9 : komorebic focus-workspace 8 + +# Move windows across workspaces +alt + shift + 1 : komorebic move-to-workspace 0 +alt + shift + 2 : komorebic move-to-workspace 1 +alt + shift + 3 : komorebic move-to-workspace 2 +alt + shift + 4 : komorebic move-to-workspace 3 +alt + shift + 5 : komorebic move-to-workspace 4 +alt + shift + 6 : komorebic move-to-workspace 5 +alt + shift + 7 : komorebic move-to-workspace 6 +alt + shift + 8 : komorebic move-to-workspace 7 +alt + shift + 9 : komorebic move-to-workspace 8 diff --git a/komorebi-hotkeys/tests/fixtures/scopes.skhdrc b/komorebi-hotkeys/tests/fixtures/scopes.skhdrc new file mode 100644 index 00000000..3524f445 --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/scopes.skhdrc @@ -0,0 +1,7 @@ +# one key, a different command in each application; kitty gets the key itself +alt - n [ + "firefox" : komorebic focus-workspace 1 + "kitty" ~ + * : komorebic focus-workspace 0 +] +alt - h : komorebic focus left diff --git a/komorebi-hotkeys/tests/fixtures/scopes.whkdrc b/komorebi-hotkeys/tests/fixtures/scopes.whkdrc new file mode 100644 index 00000000..96b8cb3f --- /dev/null +++ b/komorebi-hotkeys/tests/fixtures/scopes.whkdrc @@ -0,0 +1,10 @@ +# one key, a different command in each application; kitty gets the key itself +.shell pwsh + +alt + n [ + firefox : komorebic focus-workspace 1 + kitty : Ignore + Default : komorebic focus-workspace 0 +] + +alt + h : komorebic focus left