feat(hotkeys): read a whkdrc

komorebi for Windows' users bind komorebic in a whkdrc. `whkd::parse` reads it
into the same model as an skhdrc: `keys : command` bindings with the Windows
virtual key names whkd takes, per-application lists with `Ignore` and `Default`,
`.pause` and `.pause_hook`. A `#` starts a comment wherever it is, as in whkd.
whkd requires its sections in a fixed order; the reader takes them in any.
`.shell` is noted, since commands run through `sh -c`, side-specific modifiers
are approximated, and keys KDE has no key for (the keypad's) are left out with a
warning.

whkd's own parser, `whkd-parser`, is not used to read: it requires `.shell` to
be pwsh, powershell or cmd and panics on anything else, and it matches Windows
process names. It is under the same license as komorebi, so it is a
dev-dependency at v0.2.10, and a test reads every whkdrc of the corpus and the
example of whkd's README with both parsers and requires the same bindings.
deny.toml allows its git source.

The corpus test now also reads the whkdrc fixtures, and checks that the files of
a case read into the same keymap, apart from where each binding was written.
This commit is contained in:
LGUG2Z committed 2026-10-28 07:20:57 -07:00
1 parent ecf91f077f
commit dc9d12b34a
10 files changed
+881 -11

No files matched your search

Generated
+86 -1
View File
@@ -157,6 +157,12 @@ dependencies = [
"memchr",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "android-activity"
version = "0.6.1"
@@ -256,6 +262,15 @@ dependencies = [
"num-traits",
]
[[package]]
name = "ar_archive_writer"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6"
dependencies = [
"object 0.39.1",
]
[[package]]
name = "arboard"
version = "3.7.0"
@@ -506,7 +521,7 @@ dependencies = [
"cfg-if",
"libc",
"miniz_oxide 0.9.1",
"object",
"object 0.40.0",
"rustc-demangle",
"windows-link 0.2.1",
]
@@ -804,6 +819,16 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "chumsky"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eebd66744a15ded14960ab4ccdbfb51ad3b81f51f3f04a80adac98c985396c9"
dependencies = [
"hashbrown 0.14.5",
"stacker",
]
[[package]]
name = "clap"
version = "4.6.7"
@@ -1988,6 +2013,16 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
"allocator-api2",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -2500,6 +2535,9 @@ dependencies = [
[[package]]
name = "komorebi-hotkeys"
version = "0.1.0"
dependencies = [
"whkd-parser",
]
[[package]]
name = "komorebi-layouts"
@@ -3373,6 +3411,15 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "object"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
dependencies = [
"memchr",
]
[[package]]
name = "object"
version = "0.40.0"
@@ -3708,6 +3755,16 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
[[package]]
name = "psm"
version = "0.1.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
dependencies = [
"ar_archive_writer",
"cc",
]
[[package]]
name = "pxfm"
version = "0.1.30"
@@ -4445,6 +4502,19 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "stacker"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
dependencies = [
"cc",
"cfg-if",
"libc",
"psm",
"windows-sys 0.61.2",
]
[[package]]
name = "static_assertions"
version = "1.1.0"
@@ -5419,6 +5489,21 @@ dependencies = [
"web-sys",
]
[[package]]
name = "whkd-core"
version = "0.2.10"
source = "git+https://github.com/LGUG2Z/whkd?rev=v0.2.10#5d6a767f2ab7ac309686fe44ce59689546cf55fe"
[[package]]
name = "whkd-parser"
version = "0.2.10"
source = "git+https://github.com/LGUG2Z/whkd?rev=v0.2.10#5d6a767f2ab7ac309686fe44ce59689546cf55fe"
dependencies = [
"chumsky",
"thiserror 2.0.21",
"whkd-core",
]
[[package]]
name = "winapi"
version = "0.3.9"
+2 -2
View File
@@ -91,8 +91,8 @@ 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): reads the key binding file of skhd
into a model that also has room for whkd's and sxhkd's, with the keys as KDE
- [`komorebi-hotkeys`](komorebi-hotkeys): reads the key binding files of skhd
and whkd into one model, which also has room for sxhkd's, 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.
+1
View File
@@ -95,4 +95,5 @@ allow-git = [
"https://github.com/LGUG2Z/catppuccin-egui",
"https://github.com/LGUG2Z/flavours",
"https://github.com/LGUG2Z/komorebi",
"https://github.com/LGUG2Z/whkd",
]
+8 -2
View File
@@ -1596,6 +1596,9 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11).
- [`skhd`](../../komorebi-hotkeys/src/skhd.rs): reads an skhdrc. A mode may be used before it
is declared, so each binding waits for the end of the file to be put in its modes. skhd.zig's
`.define` templates and application groups are expanded where they are used.
- [`whkd`](../../komorebi-hotkeys/src/whkd.rs): reads a whkdrc, in any order of its sections,
where whkd requires one. `tests/whkd_parser.rs` compares it with whkd's own parser,
`whkd-parser` (a dev-dependency), on every whkdrc of the corpus.
- [`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, `<case>.skhdrc`,
@@ -1610,7 +1613,9 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11).
| Positional key names (macOS keycodes, `oem_*`) are read as on a US layout | convention only | none | none |
| Reading a file returns a keymap, whatever the text | type system: a reader returns `Parsed`, not a `Result` | none | none |
| 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, for the skhdrc files; convention only for the others | `every_file_reads_without_errors_into_the_keymap_of_its_case` | none |
| A fixture reads, without errors, into the keymap of its case | test, for the skhdrc and whkdrc files; convention only for the others | `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, for the skhdrc and whkdrc files | `the_files_of_a_case_read_into_the_same_keymap` | 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
@@ -1788,7 +1793,8 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11).
komorebi.
- [`komorebi-hotkeys/src/lib.rs`](../../komorebi-hotkeys/src/lib.rs): the key binding model,
[`komorebi-hotkeys/src/qt.rs`](../../komorebi-hotkeys/src/qt.rs) the keys, and one module per
format, [`skhd.rs`](../../komorebi-hotkeys/src/skhd.rs).
format, [`skhd.rs`](../../komorebi-hotkeys/src/skhd.rs) and
[`whkd.rs`](../../komorebi-hotkeys/src/whkd.rs).
- [`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),
+6 -4
View File
@@ -712,10 +712,12 @@ or text that is a number, which is also what the module's typed `config` takes.
## Why are the key binding files read by parsers written for komorebi?
All three formats, skhd's, whkd's and sxhkd's, are read by parsers written by hand in
`komorebi-hotkeys`. For whkd there is a Rust parser, `whkd-parser`, under the same license
as komorebi, but it requires a `.shell pwsh|powershell|cmd` line, panics in `Shell::from` on
any other shell, and its per-application bindings match Windows process names. For skhd and
sxhkd the reason is not recorded; this entry needs one.
`komorebi-hotkeys`. For whkd there is a Rust parser, `whkd-parser`, but it requires a
`.shell pwsh|powershell|cmd` line, panics in `Shell::from` on any other shell, and its
per-application bindings match Windows process names. It is under the same license as
komorebi, so it stays usable as a dev-dependency: a test reads every whkdrc of the fixture
corpus with both parsers and compares the bindings. For skhd and sxhkd the reason is not
recorded; this entry needs one.
What is not plain syntax is expanded while the file is read: skhd's `.define` templates and
application groups are replaced where they are used, so the model has only expanded bindings
+4
View File
@@ -5,3 +5,7 @@ description = "Reads skhd, whkd and sxhkd key binding files and plans them as KD
edition = "2024"
[dependencies]
[dev-dependencies]
# whkd's own parser, which the whkd reader is compared with
whkd-parser = { git = "https://github.com/LGUG2Z/whkd", rev = "v0.2.10" }
+2
View File
@@ -51,6 +51,7 @@
//!
//! - [`skhd`]: an skhdrc, with modes, per-application bindings, `.blacklist` and skhd.zig's
//! `.define`.
//! - [`whkd`]: a whkdrc, with per-application bindings and `.pause`.
//!
//! ```rust
//! use komorebi_hotkeys::{ParseOptions, Severity, skhd};
@@ -72,6 +73,7 @@ mod ir;
pub mod qt;
pub mod skhd;
mod text;
pub mod whkd;
pub use ir::App;
pub use ir::Binding;
+585
View File
@@ -0,0 +1,585 @@
//! Reading a whkdrc.
//!
//! A whkdrc is the file of whkd, the hotkey daemon komorebi for Windows uses. A binding is the
//! keys, joined by `+`, then `:` and the command; the last key is the one that is pressed, the
//! others are modifiers:
//!
//! ```text
//! .shell pwsh # the shell whkd runs commands with
//! .pause alt + shift + p # turns every other binding off and on
//! .pause_hook komorebic toggle-pause # runs when it does
//!
//! alt + n [ # one command per application
//! firefox : komorebic focus-workspace 1
//! kitty : Ignore # kitty gets the key
//! Default : komorebic focus-workspace 0
//! ]
//!
//! alt + h : komorebic focus left
//! alt + shift + oem_4 : komorebic cycle-focus previous # oem_4 is [
//! ```
//!
//! [`parse`] reads it into a [`Keymap`]:
//!
//! ```rust
//! use komorebi_hotkeys::{ParseOptions, whkd};
//!
//! let parsed = whkd::parse(
//! ".shell pwsh\nalt + shift + oem_4 : komorebic cycle-focus previous # oem_4 is [\n",
//! &ParseOptions::default(),
//! );
//! let binding = &parsed.keymap.modes[0].bindings[0];
//! // Shift+[ types {, which is what KWin matches
//! assert_eq!(binding.chord[0].to_string(), "Alt+{");
//! // commands run through `sh -c`, not PowerShell, which the reader notes
//! assert_eq!(
//! parsed.diagnostics[0].to_string(),
//! "line 1: note: commands run through `sh -c`, not `pwsh`",
//! );
//! ```
//!
//! # What is read, and how
//!
//! - **Bindings**: `keys : command`. The modifiers are `alt`, `ctrl`, `shift` and `win` (which is
//! Meta), and the key is a Windows virtual key name with or without `VK_` (`h`, `1`, `return`,
//! `oem_4`...), read as on a US keyboard. A `#` starts a comment, wherever it is, as in whkd.
//! - **Per-application bindings**: `keys [ app : command ... ]`, with `app : Ignore` for an
//! application that gets the key itself and `Default` for every other application. An
//! application's name may have spaces in it.
//! - **`.pause keys`** is the binding that turns the others off and on, and `.pause_hook command`
//! the command it runs each time.
//!
//! whkd itself requires `.shell` first, then `.pause` and `.pause_hook`, then the per-application
//! bindings, then the others. This reader takes them in any order.
//!
//! # What is not, and the diagnostics about it
//!
//! - `.shell` is not followed: commands run through `sh -c` (a note).
//! - `lalt`, `ralt`, `lwin` and the other side-specific modifiers are the modifier itself, since KDE
//! does not tell the sides apart ([`Support::Approximated`]).
//! - A key that has no KDE key, such as the keypad's, is left out ([`Support::Unsupported`]).
//!
//! Text that whkd would not read is an error and is skipped.
//!
//! [`Keymap`]: crate::Keymap
//! [`Support::Approximated`]: crate::Support::Approximated
//! [`Support::Unsupported`]: crate::Support::Unsupported
use crate::App;
use crate::Binding;
use crate::Body;
use crate::Diagnostic;
use crate::Edge;
use crate::Format;
use crate::Keymap;
use crate::ParseOptions;
use crate::Parsed;
use crate::Pause;
use crate::Run;
use crate::Scope;
use crate::Span;
use crate::Support;
use crate::Then;
use crate::qt::Combo;
use crate::qt::Layout;
use crate::qt::Mods;
use crate::qt::key_to_qt;
use crate::text;
use crate::text::Lines;
/// Reads a whkdrc.
///
/// Reading never fails: what cannot be read is left out, with a [`Diagnostic`] that says why.
/// The [module documentation](self) lists what is read and what is not.
///
/// # Example
///
/// ```rust
/// use komorebi_hotkeys::{App, Body, ParseOptions, Then, whkd};
///
/// let parsed = whkd::parse(
/// "alt + q [\n Default : komorebic close\n Google Chrome : Ignore\n]\n",
/// &ParseOptions::default(),
/// );
/// let Body::Scoped(scopes) = &parsed.keymap.modes[0].bindings[0].body else {
/// panic!("a binding per application");
/// };
/// assert_eq!(scopes[0].app, App::Other);
/// assert_eq!(scopes[1].app, App::Named("Google Chrome".into()));
/// assert_eq!(scopes[1].then, Then::Ignore);
/// ```
pub fn parse(text: &str, options: &ParseOptions) -> Parsed {
let lines = Lines::new(text);
let mut keymap = Keymap::new(Format::Whkd);
let mut diagnostics = Vec::new();
let mut hook: Option<(String, Span)> = None;
// the keys of the list being read, where it started, and its scopes
let mut list: Option<(Option<Combo>, usize, Vec<Scope>)> = None;
let mut offset = 0;
for raw in text.split_inclusive('\n') {
let start = offset;
offset += raw.len();
let line = raw.trim_end_matches(['\n', '\r']);
// a `#` starts a comment wherever it is
let content = line.split('#').next().unwrap_or_default();
let trimmed = content.trim();
if trimmed.is_empty() {
continue;
}
let indent = content.len() - content.trim_start().len();
let at = start + indent;
let span = lines.span(at, at + trimmed.len());
if let Some((combo, list_start, scopes)) = &mut list {
if trimmed.starts_with(']') {
let end = at + 1;
if let Some(combo) = *combo {
if scopes.is_empty() {
diagnostics.push(text::error(span, "the list of applications is empty"));
} else {
keymap.modes[0].bindings.push(Binding {
chord: vec![combo],
edge: Edge::Press,
body: Body::Scoped(std::mem::take(scopes)),
span: lines.span(*list_start, end),
source: text::one_line(&text[*list_start..end]),
});
}
}
list = None;
continue;
}
match trimmed.split_once(':') {
Some((app, command)) => {
let app = app.split_whitespace().collect::<Vec<_>>().join(" ");
let command = command.trim();
if app.is_empty() {
diagnostics.push(text::error(span, "expected an application before `:`"));
} else if command.is_empty() {
diagnostics.push(text::error(span, "the command is empty"));
} else {
scopes.push(Scope {
app: if app == "Default" {
App::Other
} else {
App::Named(app)
},
then: if command == "Ignore" {
Then::Ignore
} else {
Then::Run(Run::Command(command.to_string()))
},
});
}
}
None => diagnostics.push(text::error(
span,
"expected `application : command`, or `]` to close the list",
)),
}
continue;
}
if let Some(directive) = trimmed.strip_prefix('.') {
let (name, argument) = directive
.split_once(char::is_whitespace)
.map_or((directive, ""), |(name, argument)| (name, argument.trim()));
match name {
"shell" => diagnostics.push(text::note(
span,
Support::Approximated,
format!("commands run through `sh -c`, not `{argument}`"),
)),
"pause" => {
if let Some(combo) = keys(argument, at, &lines, options, &mut diagnostics) {
keymap.pause = Some(Pause {
combo,
hook: None,
span,
});
}
}
"pause_hook" if argument.is_empty() => {
diagnostics.push(text::error(span, "the command is empty"));
}
"pause_hook" => hook = Some((argument.to_string(), span)),
_ => diagnostics.push(text::error(
span,
format!("`.{name}` is not a whkd directive"),
)),
}
continue;
}
if let Some(keys_text) = trimmed.strip_suffix('[') {
let combo = keys(keys_text, at, &lines, options, &mut diagnostics);
list = Some((combo, at, Vec::new()));
continue;
}
let Some((keys_text, command)) = trimmed.split_once(':') else {
diagnostics.push(text::error(span, "expected `keys : command`"));
continue;
};
let command = command.trim();
if command.is_empty() {
diagnostics.push(text::error(span, "the command is empty"));
continue;
}
if let Some(combo) = keys(keys_text, at, &lines, options, &mut diagnostics) {
keymap.modes[0].bindings.push(Binding {
chord: vec![combo],
edge: Edge::Press,
body: Body::Run(Run::Command(command.to_string())),
span: lines.span(at, start + line.trim_end().len()),
source: line.trim().to_string(),
});
}
}
if let Some((_, list_start, _)) = list {
diagnostics.push(text::error(
lines.span(list_start, list_start + 1),
"the list is not closed with `]`",
));
}
match (&mut keymap.pause, hook) {
(Some(pause), Some((hook, _))) => pause.hook = Some(hook),
(None, Some((_, span))) => diagnostics.push(text::note(
span,
Support::Exact,
"`.pause_hook` runs only with a `.pause` binding, and there is none",
)),
(_, None) => {}
}
diagnostics.sort_by_key(|d| d.span.start);
Parsed {
keymap,
diagnostics,
}
}
/// `mod + mod + key`, starting at byte `at` of the text. `None` when the keys cannot be read or
/// realized, with a diagnostic.
fn keys(
keys: &str,
at: usize,
lines: &Lines,
options: &ParseOptions,
diagnostics: &mut Vec<Diagnostic>,
) -> Option<Combo> {
let mut names = Vec::new();
let mut offset = 0;
for part in keys.split('+') {
let name = part.trim();
let start = at + offset + (part.len() - part.trim_start().len());
offset += part.len() + 1;
let span = lines.span(start, start + name.len());
if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
diagnostics.push(text::error(
span,
format!("expected a key name between the `+`, found `{name}`"),
));
return None;
}
names.push((name, span));
}
let (key, modifiers) = names.split_last()?;
let mut mods = Mods::NONE;
for &(name, span) in modifiers {
mods |= match name.to_ascii_lowercase().as_str() {
"alt" | "menu" => Mods::ALT,
"ctrl" | "control" => Mods::CTRL,
"shift" => Mods::SHIFT,
"win" => Mods::META,
"lalt" | "ralt" | "lmenu" | "rmenu" => {
diagnostics.push(text::one_sided(span, name, "Alt"));
Mods::ALT
}
"lctrl" | "rctrl" | "lcontrol" | "rcontrol" => {
diagnostics.push(text::one_sided(span, name, "Ctrl"));
Mods::CTRL
}
"lshift" | "rshift" => {
diagnostics.push(text::one_sided(span, name, "Shift"));
Mods::SHIFT
}
"lwin" | "rwin" => {
diagnostics.push(text::one_sided(span, name, "Meta"));
Mods::META
}
_ => {
diagnostics.push(text::error(span, format!("`{name}` is not a modifier")));
return None;
}
};
}
let (name, span) = *key;
let found = match options.layout {
Layout::Us => key_to_qt(Format::Whkd, name),
};
match found {
Some(key) => Some(Combo::new(mods, key)),
None => {
let lower = name.to_ascii_lowercase();
let lower = lower.strip_prefix("vk_").unwrap_or(&lower);
if WITHOUT_KDE_KEY.contains(&lower) || lower.starts_with("numpad") {
diagnostics.push(text::unsupported(
span,
format!("no KDE key for `{name}`: the binding is left out"),
));
} else {
diagnostics.push(text::error(
span,
format!("`{name}` is not a key whkd knows"),
));
}
None
}
}
}
/// The virtual key names whkd knows that are not a key here, other than the keypad's.
const WITHOUT_KDE_KEY: &[&str] = &[
"multiply",
"add",
"separator",
"subtract",
"decimal",
"divide",
"print",
"execute",
"launch_app1",
"launch_app2",
"oem_8",
"oem_102",
"attn",
"crsel",
"exsel",
"play",
"zoom",
"pa1",
"oem_clear",
"shift",
"ctrl",
"control",
"alt",
"menu",
"win",
"lwin",
"rwin",
"lshift",
"rshift",
"lctrl",
"lcontrol",
"rctrl",
"rcontrol",
"lalt",
"lmenu",
"ralt",
"rmenu",
];
#[cfg(test)]
mod tests {
use super::*;
use crate::Severity;
fn read(text: &str) -> Parsed {
parse(text, &ParseOptions::default())
}
fn messages(parsed: &Parsed) -> Vec<String> {
parsed.diagnostics.iter().map(ToString::to_string).collect()
}
fn keys_of(parsed: &Parsed) -> Vec<String> {
parsed.keymap.modes[0]
.bindings
.iter()
.map(|b| b.chord[0].to_string())
.collect()
}
#[test]
fn bindings_and_their_keys() {
let parsed = read(
".shell cmd\n\
alt + h : komorebic focus left # so should comments at the end of a line\n\
alt + 1 : komorebic focus-workspace 0\n\
f11 : echo \"hello f11\"\n\
win + shift + return : konsole\n\
ctrl + alt + vk_left : komorebic stack left\n\
alt + shift + oem_plus : komorebic resize-axis vertical increase\n",
);
assert_eq!(
keys_of(&parsed),
[
"Alt+H",
"Alt+1",
"F11",
"Meta+Shift+Return",
"Ctrl+Alt+Left",
"Alt++"
]
);
let first = &parsed.keymap.modes[0].bindings[0];
assert_eq!(
first.body,
Body::Run(Run::Command("komorebic focus left".into()))
);
assert_eq!(first.span.line, 2);
assert_eq!(
first.source,
"alt + h : komorebic focus left # so should comments at the end of a line"
);
assert_eq!(
messages(&parsed),
["line 1: note: commands run through `sh -c`, not `cmd`"]
);
}
#[test]
fn a_hash_starts_a_comment_wherever_it_is() {
let parsed = read("alt + e : echo '#not a comment in a shell'\n");
assert_eq!(
parsed.keymap.modes[0].bindings[0].body,
Body::Run(Run::Command("echo '".into()))
);
}
#[test]
fn a_binding_can_do_something_else_in_each_application() {
let parsed = read(
"alt + n [\n\
\x20 # ProcessName as shown by `Get-Process`\n\
\x20 Firefox : echo \"hello firefox\"\n\
\x20 Google Chrome : echo \"hello chrome\"\n\
\x20 Zen Browser : Ignore\n\
\x20 Default : echo \"hello world\"\n\
]\n\
alt + h : x\n",
);
assert!(parsed.diagnostics.is_empty(), "{:?}", parsed.diagnostics);
let bindings = &parsed.keymap.modes[0].bindings;
assert_eq!(bindings.len(), 2);
assert_eq!(
bindings[0].body,
Body::Scoped(vec![
Scope {
app: App::Named("Firefox".into()),
then: Then::Run(Run::Command("echo \"hello firefox\"".into())),
},
Scope {
app: App::Named("Google Chrome".into()),
then: Then::Run(Run::Command("echo \"hello chrome\"".into())),
},
Scope {
app: App::Named("Zen Browser".into()),
then: Then::Ignore,
},
Scope {
app: App::Other,
then: Then::Run(Run::Command("echo \"hello world\"".into())),
},
])
);
assert_eq!(bindings[0].span.line, 1);
assert!(bindings[0].source.starts_with("alt + n [ # ProcessName"));
assert!(bindings[0].source.ends_with("]"));
}
#[test]
fn the_pause_binding_and_its_hook() {
let parsed = read(
".shell pwsh # can be one of cmd | pwsh | powershell\n\
.pause alt + shift + p # toggles all other hotkeys\n\
.pause_hook komorebic toggle-pause # another comment\n\
alt + h : echo \"Hello\"\n",
);
let pause = parsed.keymap.pause.as_ref().unwrap();
assert_eq!(pause.combo.to_string(), "Alt+Shift+P");
assert_eq!(pause.hook.as_deref(), Some("komorebic toggle-pause"));
assert_eq!(pause.span.line, 2);
assert_eq!(keys_of(&parsed), ["Alt+H"]);
}
#[test]
fn what_cannot_be_read_is_reported_and_left_out() {
for (text, message) in [
(
"alt + numpad1 : x",
"line 1: warning: no KDE key for `numpad1`: the binding is left out",
),
(
"alt + nope : x",
"line 1: error: `nope` is not a key whkd knows",
),
("h + alt : x", "line 1: error: `h` is not a modifier"),
(
"alt + : x",
"line 1: error: expected a key name between the `+`, found ``",
),
(
"alt + [ : x",
"line 1: error: expected a key name between the `+`, found `[`",
),
("alt + h", "line 1: error: expected `keys : command`"),
("alt + h :", "line 1: error: the command is empty"),
("alt + h : # nothing", "line 1: error: the command is empty"),
(
".blacklist steam",
"line 1: error: `.blacklist` is not a whkd directive",
),
(
"alt + n [\n firefox : x",
"line 1: error: the list is not closed with `]`",
),
(
"alt + n [\n]",
"line 2: error: the list of applications is empty",
),
(
".pause_hook x",
"line 1: note: `.pause_hook` runs only with a `.pause` binding, and there is none",
),
] {
let parsed = read(text);
assert!(parsed.keymap.modes[0].bindings.is_empty(), "{text}");
assert_eq!(messages(&parsed), [message], "{text}");
}
}
#[test]
fn side_specific_modifiers_are_the_modifier() {
let text = "lwin + h : x\nralt + j : y\n";
let parsed = read(text);
assert_eq!(keys_of(&parsed), ["Meta+H", "Alt+J"]);
let diagnostic = &parsed.diagnostics[1];
assert_eq!(diagnostic.severity, Severity::Warning);
assert_eq!(diagnostic.support, Support::Approximated);
assert_eq!(&text[diagnostic.span.start..diagnostic.span.end], "ralt");
assert_eq!(diagnostic.span.line, 2);
}
#[test]
fn reading_goes_on_after_an_error() {
let parsed = read("alt + nope : x\nalt + h : y\nalt + n [\n firefox x\n kitty : z\n]\n");
assert_eq!(keys_of(&parsed), ["Alt+H", "Alt+N"]);
let Body::Scoped(scopes) = &parsed.keymap.modes[0].bindings[1].body else {
panic!("{:?}", parsed.keymap.modes[0].bindings[1].body);
};
assert_eq!(scopes.len(), 1);
assert_eq!(
messages(&parsed),
[
"line 1: error: `nope` is not a key whkd knows",
"line 4: error: expected `application : command`, or `]` to close the list",
]
);
}
}
+46 -2
View File
@@ -9,13 +9,16 @@ use komorebi_hotkeys::App;
use komorebi_hotkeys::Body;
use komorebi_hotkeys::DEFAULT_MODE;
use komorebi_hotkeys::Edge;
use komorebi_hotkeys::Format;
use komorebi_hotkeys::Keymap;
use komorebi_hotkeys::ParseOptions;
use komorebi_hotkeys::Parsed;
use komorebi_hotkeys::Run;
use komorebi_hotkeys::Severity;
use komorebi_hotkeys::Span;
use komorebi_hotkeys::Then;
use komorebi_hotkeys::skhd;
use komorebi_hotkeys::whkd;
use std::path::PathBuf;
/// Every case, and the formats it is written in.
@@ -194,10 +197,28 @@ fn parse(extension: &str, text: &str) -> Option<Parsed> {
let options = ParseOptions::default();
match extension {
"skhdrc" => Some(skhd::parse(text, &options)),
"whkdrc" => Some(whkd::parse(text, &options)),
_ => None,
}
}
/// The keymap with everything that says where it was written taken out: the format, the spans,
/// the bindings' source text and the defines.
fn without_provenance(mut keymap: Keymap) -> Keymap {
keymap.format = Format::Skhd;
keymap.defines.clear();
if let Some(pause) = &mut keymap.pause {
pause.span = Span::default();
}
for mode in &mut keymap.modes {
for binding in &mut mode.bindings {
binding.span = Span::default();
binding.source.clear();
}
}
keymap
}
fn fixtures() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
}
@@ -271,9 +292,14 @@ fn every_case_but_the_sample_has_an_expected_keymap() {
#[test]
fn the_sample_reads_completely() {
for extension in ["skhdrc"] {
for extension in ["skhdrc", "whkdrc"] {
let parsed = parse(extension, &read("sample", extension)).unwrap();
assert!(parsed.diagnostics.is_empty(), "{:#?}", parsed.diagnostics);
let lossy: Vec<_> = parsed
.diagnostics
.iter()
.filter(|d| d.severity != Severity::Note)
.collect();
assert!(lossy.is_empty(), "{extension}: {lossy:#?}");
let bindings = &parsed.keymap.modes[0].bindings;
assert_eq!(bindings.len(), 50);
@@ -295,3 +321,21 @@ fn the_sample_reads_completely() {
assert_eq!(keys.len(), bindings.len());
}
}
#[test]
fn the_files_of_a_case_read_into_the_same_keymap() {
for (case, extensions) in CASES {
let keymaps: Vec<(&str, Keymap)> = extensions
.iter()
.filter_map(|e| Some((*e, parse(e, &read(case, e))?.keymap)))
.map(|(e, keymap)| (e, without_provenance(keymap)))
.collect();
for pair in keymaps.windows(2) {
assert_eq!(
pair[0].1, pair[1].1,
"{case}: {} and {}",
pair[0].0, pair[1].0
);
}
}
}
+141
View File
@@ -0,0 +1,141 @@
//! The whkd reader against whkd's own parser, `whkd-parser`, on the whkdrc files of the corpus and
//! on the example of whkd's README: both must read the same bindings.
use komorebi_hotkeys::App;
use komorebi_hotkeys::Body;
use komorebi_hotkeys::Format;
use komorebi_hotkeys::ParseOptions;
use komorebi_hotkeys::Run;
use komorebi_hotkeys::Scope;
use komorebi_hotkeys::Then;
use komorebi_hotkeys::qt::Combo;
use komorebi_hotkeys::qt::Mods;
use komorebi_hotkeys::qt::key_to_qt;
use komorebi_hotkeys::whkd;
use std::path::Path;
use std::path::PathBuf;
/// The bindings of a file, as (keys, what they do), and the pause binding with its hook.
type Read = (Vec<(Combo, Body)>, Option<(Combo, Option<String>)>);
/// The combo a list of whkd key names stands for: the last is the key, the others modifiers.
fn combo(keys: &[String]) -> Combo {
let (key, modifiers) = keys.split_last().unwrap();
let mut mods = Mods::NONE;
for modifier in modifiers {
mods |= match modifier.to_ascii_lowercase().as_str() {
"alt" => Mods::ALT,
"ctrl" => Mods::CTRL,
"shift" => Mods::SHIFT,
"win" => Mods::META,
other => panic!("the corpus has no modifier {other}"),
};
}
Combo::new(mods, key_to_qt(Format::Whkd, key).unwrap())
}
/// What whkd-parser reads.
fn theirs(path: &Path) -> Read {
let whkdrc = whkd_parser::load(&path.to_path_buf()).unwrap();
let mut bindings = Vec::new();
for (keys, apps) in &whkdrc.app_bindings {
let scopes = apps
.iter()
.map(|binding| Scope {
app: match binding.process_name.as_deref() {
Some("Default") => App::Other,
Some(name) => App::Named(name.to_string()),
None => panic!("an application binding with no application"),
},
then: match binding.command.as_str() {
"Ignore" => Then::Ignore,
command => Then::Run(Run::Command(command.to_string())),
},
})
.collect();
bindings.push((combo(keys), Body::Scoped(scopes)));
}
for binding in &whkdrc.bindings {
bindings.push((
combo(&binding.keys),
Body::Run(Run::Command(binding.command.clone())),
));
}
let pause = whkdrc
.pause_binding
.as_ref()
.map(|keys| (combo(keys), whkdrc.pause_hook.clone()));
(bindings, pause)
}
/// What the whkd reader reads.
fn ours(path: &Path) -> Read {
let text = std::fs::read_to_string(path).unwrap();
let parsed = whkd::parse(&text, &ParseOptions::default());
assert_eq!(parsed.keymap.modes.len(), 1);
let bindings = parsed.keymap.modes[0]
.bindings
.iter()
.map(|binding| (binding.chord[0], binding.body.clone()))
.collect();
let pause = parsed
.keymap
.pause
.map(|pause| (pause.combo, pause.hook.clone()));
(bindings, pause)
}
#[test]
fn every_whkdrc_of_the_corpus_reads_as_whkd_reads_it() {
let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
let mut compared = 0;
for entry in std::fs::read_dir(fixtures).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_some_and(|e| e == "whkdrc") {
assert_eq!(ours(&path), theirs(&path), "{}", path.display());
compared += 1;
}
}
assert_eq!(compared, 9);
}
#[test]
fn the_example_of_whkds_readme_reads_as_whkd_reads_it() {
let example = r#".shell pwsh # can be one of cmd | pwsh | powershell
.pause alt + shift + p # can be any hotkey combo to toggle all other hotkeys on and off
.pause_hook echo "you can call whatever powershell command you want here"
alt + n [
# ProcessName as shown by `Get-Process`
Firefox : echo "hello firefox"
# Spaces are fine, no quotes required
Google Chrome : echo "hello chrome"
]
alt + q [
# Default is a keyword which will apply to all apps
# If you only have Default, this is the same as doing "alt + q : komorebic close"
Default : komorebic close
# Ignore is a keyword which will skip running the hotkey for the given process
Google Chrome : Ignore
]
# focus windows with komorebi
alt + h : komorebic focus left
alt + j : komorebic focus down
alt + k : komorebic focus up
alt + l : komorebic focus right
"#;
let path = std::env::temp_dir().join(format!(
"komorebi-hotkeys-whkd-readme-{}.whkdrc",
std::process::id()
));
std::fs::write(&path, example).unwrap();
let (ours, theirs) = (ours(&path), theirs(&path));
let _ = std::fs::remove_file(&path);
assert_eq!(ours.0.len(), 6);
assert_eq!(ours, theirs);
}