feat(kwin): the daemon registers with KGlobalAccel

A static shortcut can only be one combo, pressed, the same in every application.
Modes, chord chains, release bindings and per-application bindings need komorebi
to hold the keys and decide what each press does: the engine of
komorebi-hotkeys, a state machine with no I/O. This commit runs it against
KWin's global shortcut daemon, which KWin 6.8 runs inside itself on the session
bus.

kwin::hotkeys owns the component komorebi in kglobalaccel, with one action per
combo, named after the combo (Alt+H). An activation of the engine is
setShortcutKeys(id, [[combo]], 6), with a doRegister the first time; a
deactivation is setInactive, after which the key reaches the focused window
again. The calls of one event are sent without waiting for each other's answers,
which Phase 0 measured at 60 calls in 2.4 ms. globalShortcutPressed and
globalShortcutReleased of /component/komorebi feed the engine;
globalShortcutRepeated is ignored, so a held key runs its binding once. A
komorebic command runs the komorebic next to the daemon with its words when they
need no shell, anything else runs through sh -c. The calls are computed by
Registry, which is pure and tested; the D-Bus part is proved by the VM test.

The engine hears the presses at the path /component/komorebi and does not ask
kglobalaccel for the object with getComponent. kglobalaccel makes the object
when the component gets its first action, so a start with no key to grab (every
binding is for an application other than the one with the focus) has none to ask
for: getComponent fails with NoSuchComponent, and an engine that asked would
never start. A signal is matched by the path it comes from, so the presses are
heard as soon as there is an object. PLATFORM.md says so.

kglobalaccel keeps the actions and the grabs of a client that was killed, so a
start is an idempotent reconcile: the actions of the component that the keymap
names are taken over and released unless the default mode wants them, the others
are unregistered. A stop releases and unregisters everything, from
KWinBackend::shutdown, which SIGINT, SIGTERM and the Stop message all go
through.

The daemon takes --keybindings FILE, --keybindings-format skhd|whkd|sxhkd (by
default from the file's name) and --keybindings-mode (the mode komorebic hotkeys
compile wrote the static shortcuts in, so that the daemon leaves those to KDE);
without --keybindings it reads the first of skhdrc, whkdrc and sxhkdrc in the
config directory (HOME_DIR, KOMOREBI_CONFIG_HOME). It logs one line about the
file and the diagnostics at debug level. An engine that cannot start is logged
and the window manager runs without keys; the fake backend runs none.

The VM test vm-keys-engine starts the daemon in a Plasma session with an skhdrc
in the config directory, presses its keys (a command, one through a shell,
komorebic retile reaching the daemon), kills the daemon and sees its keys stay
registered, starts it with another file and sees the old keys unregistered and
the new ones work, and stops it with komorebic stop, after which no key is
registered and none runs. The library gains spawn_komorebi,
kill_spawned_komorebi and shortcut_actions, and Checks.finish names the checks
that failed, since nix build shows only the last lines of a failed run. The
suite's node turns the module's unit off: the test runs daemons of its own.
This commit is contained in:
LGUG2Z committed 2026-10-28 07:21:14 -07:00
1 parent e1a227434b
commit b49c4fab0a
16 files changed
+1109 -21

No files matched your search

Generated
+13
View File
@@ -2501,6 +2501,7 @@ dependencies = [
"dirs 6.0.0",
"futures-util",
"hotwatch",
"komorebi-hotkeys",
"komorebi-layouts",
"komorebi-themes",
"lazy_static",
@@ -4810,10 +4811,22 @@ dependencies = [
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"tracing",
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "toml"
version = "0.5.11"
+5 -2
View File
@@ -88,7 +88,8 @@ without a checkout of the toolchain.
it handles (`notify_subscribers`), and is configured by a `komorebi.json` that
it reads and reads again when it changes (`static_config`), and checks it, the
key binding file, and the desktop it runs on, for mistakes without the daemon
(`check`).
(`check`). With a key binding file, it registers keys with KWin's global
shortcut daemon and runs their commands (`kwin::hotkeys`).
- [`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.
@@ -325,7 +326,9 @@ Key bindings are written in the format of skhd, whkd or sxhkd. `komorebi-hotkeys
reads such a file into one model and sorts its bindings into static shortcuts,
which KDE runs by itself from a `.desktop` file, and those that need komorebi
to register the keys and decide what each press does. `komorebic hotkeys
compile` writes the static shortcuts.
compile` writes the static shortcuts, and the daemon runs the engine for the
rest: it registers their keys with KWin's global shortcut daemon over the
session bus and runs the command of each press.
## Documentation
+31
View File
@@ -1655,6 +1655,28 @@ read and left out (a warning) and how many bindings are not realized as their ow
the ones `kde::diff` says that plan would write. It reads no file the desktop has no part in, so
`--configuration-only` keeps it.
### The engine in the daemon
[`komorebi/src/kwin/hotkeys.rs`](../../komorebi/src/kwin/hotkeys.rs) runs the engine against
kglobalaccel, on a session bus connection and a thread of its own. The daemon reads the file
it is given with `--keybindings` (or the first it finds in the config directory), plans it in
`--keybindings-mode`, and hands the plan's engine keymap to `kwin::hotkeys::start`, unless the
plan needs no engine. A failure to start is logged, and the window manager runs without keys.
- **Calls**: each effect becomes calls on `/kglobalaccel` (`Registry`): an activation is
`setShortcutKeys(id, [[combo]], 6)`, preceded by `doRegister` the first time; a deactivation
is `setInactive`. The calls of one event are sent together, and only those for one action
wait for each other.
- **Signals**: `globalShortcutPressed` and `globalShortcutReleased` of `/component/komorebi`
are the engine's presses and releases. `globalShortcutRepeated` is not listened to.
- **Commands**: a `komorebic` command runs `komorebic` (the one next to the daemon) with its
words when it needs no shell, and anything else runs through `sh -c`, as processes the
daemon does not wait for.
- **Start**: the component's actions that the keymap names are taken over, and released
unless the default mode wants them; the others are unregistered.
- **Stop**: every key is released and every action unregistered, from
`KWinBackend::shutdown`, which every way the daemon stops goes through.
### What is guaranteed, and by what
| Rule | Enforced by | Proof | Escape hatch |
@@ -1682,6 +1704,11 @@ the ones `kde::diff` says that plan would write. It reads no file the desktop ha
| `komorebic check` says when the shortcut files are not the ones `hotkeys compile` would write | test | `shortcut_files_that_are_not_the_ones_of_the_plan_are_a_warning_that_says_how_many`, `shortcut_files_the_file_does_not_call_for_are_a_warning_until_compile_replaces_them` | none |
| `--strict` writes nothing when a diagnostic is a warning or an error | test, through the binary | `strict_refuses_a_file_with_a_warning_and_writes_nothing` | none |
| KWin runs a static shortcut's command on its key, from the system profile at the start of a session and from the user's directory after `--reload` | VM test | `vm-keys-static` | none |
| An effect becomes the calls that carry it out, and an action is registered once | test | `Registry` doctest, `a_start_with_nothing_left_behind_registers_and_grabs_the_default_mode` | none |
| A start takes over the keys a killed daemon left, releases those the default mode does not want, and unregisters the actions its keymap does not name | test, of the calls; VM test, against kglobalaccel | `a_start_takes_over_the_keys_of_a_killed_komorebi_and_drops_the_rest`, `vm-keys-engine` | none |
| A stop of the daemon unregisters every action | framework path: `KWinBackend::shutdown` calls `kwin::hotkeys::stop`, and both ways to stop call it; VM test | `vm-keys-engine` (`komorebic stop`) | `SIGKILL` leaves the keys until the next start |
| A press of a grabbed key runs its binding's command, `komorebic` without a shell where it needs none | test, of the process; VM test | `command` doctest, `a_press_runs_the_command_and_changes_no_key`, `vm-keys-engine` | none |
| Holding a key runs its binding once | convention only: the transport listens to `globalShortcutPressed` and not to `globalShortcutRepeated` | none (measured in PLATFORM.md) | none |
## Where to look in the code
@@ -1870,6 +1897,10 @@ the ones `kde::diff` says that plan would write. It reads no file the desktop ha
[`komorebic/tests/hotkeys.rs`](../../komorebic/tests/hotkeys.rs), what they write.
- [`nix/tests/vm/suites/keys-static`](../../nix/tests/vm/suites/keys-static/test.py): static
shortcuts run by a real KWin.
- [`komorebi/src/kwin/hotkeys.rs`](../../komorebi/src/kwin/hotkeys.rs): the engine against
kglobalaccel, and
[`nix/tests/vm/suites/keys-engine`](../../nix/tests/vm/suites/keys-engine/test.py), keys
pressed in a real KWin with the daemon running.
- [`komorebi-hotkeys/tests`](../../komorebi-hotkeys/tests): the corpus test and the comparison
with `whkd-parser`.
- [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module;
+45 -12
View File
@@ -196,20 +196,22 @@ an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a runnin
#### What komorebi leaves behind
When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it brings back
the windows it hid, waits until the commands that do so have reached the bridge, removes the
parking desktop, unloads the effects it loaded, puts back the values the keys it set in `kwinrc`
had (`PerOutputVirtualDesktops`, the focus policy, and the keys of the effects), or removes a key
the user had not set, and asks KWin to reload its configuration, asks KWin to unload the script,
closes an empty connection to each subscriber, and removes the socket. The desktops it created for
workspaces stay: they are the user's desktops from then on. A `StopIgnoreRestore` message stops it
the same way, except that it does not bring the windows back: the parking desktop is removed all
the same. The file `bridge.js` stays in the runtime
the windows it hid, unregisters the keys of its engine, waits until the commands that do so have
reached the bridge, removes the parking desktop, unloads the effects it loaded, puts back the
values the keys it set in `kwinrc` had (`PerOutputVirtualDesktops`, the focus policy, and the keys
of the effects), or removes a key the user had not set, and asks KWin to reload its configuration,
asks KWin to unload the script, closes an empty connection to each subscriber, and removes the
socket. The desktops it created for workspaces stay: they are the user's desktops from then on. A
`StopIgnoreRestore` message stops it the same way, except that it does not bring the windows back:
the parking desktop is removed all the same. The file `bridge.js` stays in the runtime
directory, which is removed at logout. A daemon that is killed leaves the script running in
KWin, reporting to nobody, the socket file in the runtime directory, per-output desktops
on, and the parking desktop with the hidden windows on it, until the next start replaces the
script and the socket, sends the windows on the parking desktop to the first workspace's desktop
and removes the desktop, and its stop puts the setting back (the backup in the runtime
directory keeps the user's value), or the session ends.
directory keeps the user's value), or the session ends. It also leaves the keys of its engine
grabbed: they are swallowed, and run nothing, until the next start takes them over and unregisters
those its key bindings no longer have.
### A headless KWin
@@ -260,6 +262,9 @@ What komorebi calls:
| `org.kde.KWin` | `/KWin` | `org.kde.KWin` | `reconfigure()` | after komorebi changed `kwinrc`, at start and at exit |
| `org.kde.KWin` | `/VirtualDesktopManager` | `org.kde.KWin.VirtualDesktopManager` | the properties `desktops` and `count`, `createDesktop(us)`, `setDesktopName(ss)`, `removeDesktop(s)` | when a workspace has no desktop, and at start; `createDesktop` also for the parking desktop, the first time a window is hidden, and `removeDesktop` for it when komorebi stops and for one a killed run left |
| `org.kde.plasmashell` | `/PlasmaShell` | `org.kde.PlasmaShell` | `evaluateScript(s) -> s`, `wallpaper(u) -> a{sv}`, `setWallpaper(sa{sv}u)` | when a workspace with a wallpaper comes into view ([The Plasma shell](#the-plasma-shell)) |
| `org.kde.kglobalaccel` | `/kglobalaccel` | `org.kde.KGlobalAccel` | `allActionsForComponent(as) -> aas` | when the engine starts |
| `org.kde.kglobalaccel` | `/kglobalaccel` | `org.kde.KGlobalAccel` | `doRegister(as)`, `setShortcutKeys(as, a(ai), u) -> a(ai)`, `setInactive(as)`, `unRegister(as)` | when the engine grabs and lets go of keys, and when it starts and stops |
| `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `AddMatch(s)`, for `globalShortcutPressed` and `globalShortcutReleased` of `/component/komorebi` | when the engine starts |
What komorebi listens to, for the machine sleeping and the screen being locked:
@@ -317,6 +322,34 @@ write such files. What follows was measured at time of writing (2026-10-27) on K
- The VM test `vm-keys-static` presses the keys of shortcut files in the system profile, and of
one written and handed over in the middle of the session.
The engine registers its keys itself, in the component `komorebi`, with one action per combo
named after the combo (`Alt+H`); an action's id is `["komorebi", "Alt+H", "komorebi",
"Alt+H"]`. What was measured of that interface at time of writing (2026-10-27), on KWin
6.8.1 in a virtual machine under HVF with 4 cores:
- `setShortcutKeys(as id, a(ai) keys, u flags) -> a(ai)` takes a list of key sequences, each
a struct of one Qt key code per key of the sequence, and returns the keys it set. Flags 6
(`SetPresent | NoAutoloading`) grab the key at once, whatever kglobalaccel saved for the
action. A key that another action has is not set: the answer is not what was asked for, and
komorebi logs a warning.
- A grabbed key does not reach the focused window, a bare key (`H`, `Escape`) included, and
each tap is a `globalShortcutPressed` and then a `globalShortcutReleased` signal
(`ssx`: component, action, timestamp) on `/component/komorebi`. The signal reached a client
2.5 ms after the key at the median (2.2 to 3.9 ms, 20 presses), also after another window
had taken the focus.
- A key held for 1.2 s sent one pressed signal, 15 `globalShortcutRepeated` and one released
signal, in that order.
- After `setInactive`, the key reaches the focused window and no signal is sent;
`setShortcutKeys` grabs it again. Sixty such calls, sent without waiting for the answers,
were all answered in 2.4 ms, and the state afterwards was right.
- A client that is killed leaves its actions and its grabs: the key stays swallowed and its
signal is sent to nobody until `unRegister`.
- A sequence of two keys (`[[Meta+A, B]]`) is accepted and stored, but never fires: the
second key reaches the focused window.
- `getComponent` fails until the component has an action, so the engine does not ask for the
object of its component: it listens at the object's path, `/component/komorebi`, which a
signal is matched by, and a start with no key to grab is a start all the same.
## Files and directories
| Path | What | Lifetime |
@@ -335,7 +368,7 @@ write such files. What follows was measured at time of writing (2026-10-27) on K
| `$XDG_DATA_HOME/komorebi/komorebi.log.YYYY-MM-DD` | the daemon's log, with colors, which `komorebic log` follows | a file a day (the UTC date), never removed by komorebi |
| `$XDG_DATA_HOME/komorebi/komorebi_plaintext.log.YYYY-MM-DD` | the same log without colors | as above |
| `$XDG_DATA_HOME/kglobalaccel/komorebi-*.desktop` | the static shortcuts `komorebic hotkeys compile` and `komorebic export-kde-shortcuts` write, each with `X-Komorebi-Generated=true` | replaced at every write: the files with that key are removed, and no other |
| `$KOMOREBI_CONFIG_HOME/{skhdrc,whkdrc,sxhkdrc}` | the key binding file `komorebic hotkeys compile` reads when it is given none (the first that exists), and the skhdrc of `export-kde-shortcuts` | the user's |
| `$KOMOREBI_CONFIG_HOME/{skhdrc,whkdrc,sxhkdrc}` | the key binding file `komorebic hotkeys compile` and the daemon read when they are given none (the first that exists), and the skhdrc of `export-kde-shortcuts` | the user's; the daemon reads it once, at start |
Without `XDG_RUNTIME_DIR` the bridge and the socket are in `komorebi` in the local data
directory instead, with the logs (see [`XDG_DATA_HOME`](#xdg_data_home)).
@@ -380,8 +413,8 @@ The config home, where komorebi looks for `komorebi.json`: a directory, in which
configuration` and the daemon look for the file. Without it the config home is
`~/.config/komorebi`, whatever `XDG_CONFIG_HOME` is. When it is set and is not a directory, the
daemon and `komorebic` panic when they first need the config home, and say so. Environment
variables in it are expanded (`$HOME/komorebi`). `komorebic hotkeys compile` looks in it for the
key binding file it is not given.
variables in it are expanded (`$HOME/komorebi`). The daemon and `komorebic hotkeys compile` look
in it for the key binding file they are not given.
### `XDG_RUNTIME_DIR`
+8 -1
View File
@@ -106,7 +106,9 @@ check also runs `ruff` and `ty` over it. The driver type checks every
the run.
- `Checks` counts checks and fails once, at the end, so that one failure does
not hide the ones after it. `finish()` prints `passed: N failed: M`.
not hide the ones after it. `finish()` prints `passed: N failed: M`, and its
error names the checks that failed, which `nix build` shows in the last lines
of the run.
- `Kde` is one KWin session. `Kde.headless(machine, name, size=, outputs=,
scale=)` starts the units and waits for KWin to own its name on the private
bus. `wid`, `rect`, `title` and `active` read windows through `kdotool`,
@@ -187,6 +189,11 @@ the run.
- `Keys(machine).send("alt-shift-k")` presses a combo on the machine's
keyboard, written as KDE writes it in lower case with `-` between the keys
(`meta` and `super` are the left Super key).
- `spawn_komorebi(*args)` starts a daemon of the test's own in the session
node's Plasma session, logging to the file `komorebi_log()` reads;
`kill_spawned_komorebi()` kills it with `SIGKILL`; `shortcut_actions()` lists the
actions komorebi has registered with kglobalaccel. A suite that spawns its own
daemon turns the module's unit off in its `node`.
## Pressing keys
+25
View File
@@ -59,6 +59,31 @@ back of a stack, [stacking windows](stacking-windows.md), and the windows behind
[monocle](monocle.md)), removes the desktop they were hidden on, asks KWin to unload its script,
removes its socket and exits. Stopping the process with `SIGINT` or `SIGTERM` does the same.
## Key bindings
komorebi reads key bindings from a file in the format of skhd, whkd or sxhkd. The daemon
looks for `skhdrc`, `whkdrc` or `sxhkdrc` in `~/.config/komorebi` (or in
`$KOMOREBI_CONFIG_HOME`) and takes the first it finds; `--keybindings FILE` names another,
with `--keybindings-format skhd|whkd|sxhkd` when its name does not end with one of those.
The daemon registers the keys with KDE itself and runs the command of each press:
```sh
komorebic start -- --keybindings ~/dotfiles/skhdrc
```
KDE can also run a binding with no komorebi process, as a static shortcut that shows in System
Settings: [`komorebic hotkeys compile`](../cli/hotkeys-compile.md) writes those, and
`--mode auto` writes every binding that can be one. Give the daemon the same mode, so that it
leaves those bindings to KDE:
```sh
komorebic hotkeys compile --mode auto
komorebic start -- --keybindings-mode auto
```
A daemon that is killed leaves its keys swallowed until it is started again; `komorebic stop`
gives them back.
## Asking komorebi what it is doing
The daemon answers questions on its socket, and these commands print the answers:
+7 -1
View File
@@ -5,6 +5,7 @@ description = "A tiling window manager for KDE Plasma"
edition = "2024"
[dependencies]
komorebi-hotkeys = { path = "../komorebi-hotkeys" }
komorebi-themes = { workspace = true }
komorebi-layouts = { workspace = true }
version = { path = "../version" }
@@ -26,7 +27,12 @@ serde = { workspace = true }
serde_json = { workspace = true, features = ["preserve_order"] }
serde_with = { version = "3", features = ["schemars_1"] }
strum = { version = "0.28", features = ["derive"] }
tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] }
tokio = { version = "1", features = [
"macros",
"rt-multi-thread",
"sync",
"time",
] }
tracing = { workspace = true }
tracing-appender = { workspace = true }
tracing-subscriber = { workspace = true }
+648
View File
@@ -0,0 +1,648 @@
//! The engine's keys, through KDE's global shortcut daemon.
//!
//! [`Engine`] decides which combos komorebi holds and what a press of each does; it does no I/O.
//! This module carries its decisions out on the session bus, where KWin 6.8 runs the global
//! shortcut daemon (`org.kde.kglobalaccel`, inside `kwin_wayland`):
//!
//! ```text
//! komorebi (this module) kglobalaccel, in KWin
//! ---------------------- ---------------------
//! Activate(combo) -- doRegister(id) -------> the action exists, with no key
//! -- setShortcutKeys(id, -> the key is grabbed: swallowed, and reported
//! [[combo]], 6)
//! Deactivate(combo) -- setInactive(id) ------> the key reaches the focused window again
//! engine.on_pressed <- globalShortcutPressed -- a press of a grabbed key
//! engine.on_released <- globalShortcutReleased - its release
//! ```
//!
//! komorebi owns the component [`COMPONENT`] in kglobalaccel, with one action per combo, named
//! after the combo as KDE writes it (`Alt+H`): an action's id is `["komorebi", "Alt+H", "komorebi",
//! "Alt+H"]`. The engine's effects become [`Call`]s ([`Registry`]), and the calls of one event are
//! sent together, without waiting for each answer; only the calls for one action wait for each
//! other. kglobalaccel also sends `globalShortcutRepeated` while a key is held; nothing listens to
//! it, so a held key runs its binding once.
//!
//! A command the engine runs is started as a process of its own, which komorebi does not wait
//! for ([`command`]): `komorebic` with the words of a `komorebic` command, when they need no shell,
//! and `sh -c` with anything else.
//!
//! # Start and stop
//!
//! kglobalaccel keeps an action, and the grab of its key, until it is unregistered: a komorebi
//! that was killed leaves its keys swallowed and reporting to nobody. So a start is an idempotent
//! reconcile ([`Registry::startup`]): the actions of the component that a combo of the keymap
//! names are taken over, and released unless the default mode wants them, and every other action
//! of the component is unregistered. A stop ([`stop`]) releases every key and unregisters every
//! action, so that nothing is left behind; [`KWinBackend`](super::KWinBackend) stops the engine
//! when it shuts down, which every way the daemon stops goes through.
//!
//! `docs/dev/PLATFORM.md` has what was measured of kglobalaccel, and the VM test `vm-keys-engine`
//! presses keys in a Plasma session with the daemon running.
use color_eyre::eyre;
use futures_util::StreamExt;
use futures_util::future::join_all;
use komorebi_hotkeys::Keymap;
use komorebi_hotkeys::engine::Effect;
use komorebi_hotkeys::engine::Engine;
use komorebi_hotkeys::engine::EngineOptions;
use komorebi_hotkeys::qt::Combo;
use komorebi_hotkeys::qt::Key;
use komorebi_hotkeys::qt::Mods;
use parking_lot::Mutex;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::time::Duration;
use std::time::Instant;
use tokio::sync::mpsc;
use zbus::Connection;
use zbus::proxy::Proxy;
use zbus::zvariant::OwnedObjectPath;
/// The name of komorebi's component in kglobalaccel.
pub const COMPONENT: &str = "komorebi";
const SERVICE: &str = "org.kde.kglobalaccel";
const PATH: &str = "/kglobalaccel";
const IFACE: &str = "org.kde.KGlobalAccel";
const COMPONENT_IFACE: &str = "org.kde.kglobalaccel.Component";
/// `SetPresent | NoAutoloading`: the key is grabbed now, and not replaced by one saved in
/// kglobalaccel's configuration
const FLAGS: u32 = 6;
/// A call komorebi makes on kglobalaccel's `/kglobalaccel`, for the action of one combo, or of an
/// action it does not know.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Call {
/// `doRegister`: makes the action known, with no key.
Register(Combo),
/// `setShortcutKeys(id, [[combo]], 6)`: gives the action its key, and grabs it.
Grab(Combo),
/// `setInactive`: lets the key go, so that it reaches the focused window.
Release(Combo),
/// `unRegister`: removes the action of that name from the component.
Unregister(String),
}
impl Call {
/// Returns the name of the action the call is for: the combo as KDE writes it.
///
/// # Example
///
/// ```rust
/// use komorebi::kwin::hotkeys::Call;
/// use komorebi_hotkeys::Format;
/// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt};
///
/// let alt_h = Combo::new(Mods::ALT, key_to_qt(Format::Skhd, "h").unwrap());
/// assert_eq!(Call::Grab(alt_h).action(), "Alt+H");
/// assert_eq!(Call::Unregister("Meta+Q".into()).action(), "Meta+Q");
/// ```
pub fn action(&self) -> String {
match self {
Call::Register(combo) | Call::Grab(combo) | Call::Release(combo) => combo.to_string(),
Call::Unregister(name) => name.clone(),
}
}
}
/// The actions komorebi has registered, and the calls that keep kglobalaccel in step with the
/// engine.
///
/// An [`Effect::Activate`] is a [`Call::Grab`], preceded by a [`Call::Register`] the first time
/// the combo is activated; an [`Effect::Deactivate`] is a [`Call::Release`]. Commands are not
/// calls.
///
/// # Example
///
/// ```rust
/// use komorebi::kwin::hotkeys::{Call, Registry};
/// use komorebi_hotkeys::Format;
/// use komorebi_hotkeys::engine::Effect;
/// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt};
///
/// let alt_h = Combo::new(Mods::ALT, key_to_qt(Format::Skhd, "h").unwrap());
/// let mut registry = Registry::default();
///
/// assert_eq!(
/// registry.calls(&[Effect::Activate(alt_h)]),
/// [Call::Register(alt_h), Call::Grab(alt_h)]
/// );
/// assert_eq!(registry.calls(&[Effect::Deactivate(alt_h)]), [Call::Release(alt_h)]);
/// // registered once: activating it again only grabs it
/// assert_eq!(registry.calls(&[Effect::Activate(alt_h)]), [Call::Grab(alt_h)]);
/// assert_eq!(registry.unregister_all(), [Call::Unregister("Alt+H".into())]);
/// ```
#[derive(Debug, Default)]
pub struct Registry {
registered: BTreeSet<Combo>,
}
impl Registry {
/// Returns the calls that take over what an earlier komorebi left in the component.
///
/// `existing` is the names of the component's actions, as kglobalaccel lists them;
/// `known` maps the name of every combo the keymap can activate to the combo; `start` is
/// what [`Engine::start`] returned. An existing action that `known` names is taken over:
/// it is registered already, and released unless `start` activates it. Any other existing
/// action is unregistered. Then come the calls of `start` itself.
///
/// # Example
///
/// ```rust
/// use std::collections::BTreeMap;
/// use komorebi::kwin::hotkeys::{Call, Registry};
/// use komorebi_hotkeys::Format;
/// use komorebi_hotkeys::engine::Effect;
/// use komorebi_hotkeys::qt::{Combo, Mods, key_to_qt};
///
/// let combo = |key| Combo::new(Mods::ALT, key_to_qt(Format::Skhd, key).unwrap());
/// let (h, j, k) = (combo("h"), combo("j"), combo("k"));
/// let known = BTreeMap::from([h, j, k].map(|c| (c.to_string(), c)));
/// // a komorebi that was killed left Alt+J grabbed, and Alt+X from another keymap
/// let existing = ["Alt+J".to_string(), "Alt+X".to_string()];
///
/// let calls = Registry::default().startup(&existing, &known, &[Effect::Activate(h)]);
///
/// assert_eq!(
/// calls,
/// [
/// Call::Release(j),
/// Call::Unregister("Alt+X".into()),
/// Call::Register(h),
/// Call::Grab(h),
/// ]
/// );
/// ```
pub fn startup(
&mut self,
existing: &[String],
known: &BTreeMap<String, Combo>,
start: &[Effect],
) -> Vec<Call> {
let activated: BTreeSet<Combo> = start
.iter()
.filter_map(|effect| match effect {
Effect::Activate(combo) => Some(*combo),
_ => None,
})
.collect();
let mut calls = Vec::new();
for name in existing {
match known.get(name) {
Some(combo) => {
self.registered.insert(*combo);
if !activated.contains(combo) {
calls.push(Call::Release(*combo));
}
}
None => calls.push(Call::Unregister(name.clone())),
}
}
calls.extend(self.calls(start));
calls
}
/// Returns the calls that carry out `effects`, in their order.
pub fn calls(&mut self, effects: &[Effect]) -> Vec<Call> {
let mut calls = Vec::new();
for effect in effects {
match effect {
Effect::Activate(combo) => {
if self.registered.insert(*combo) {
calls.push(Call::Register(*combo));
}
calls.push(Call::Grab(*combo));
}
Effect::Deactivate(combo) => calls.push(Call::Release(*combo)),
Effect::Komorebic(_) | Effect::Shell(_) => {}
}
}
calls
}
/// Returns the calls that unregister every action komorebi registered, and forgets them.
pub fn unregister_all(&mut self) -> Vec<Call> {
std::mem::take(&mut self.registered)
.into_iter()
.map(|combo| Call::Unregister(combo.to_string()))
.collect()
}
}
/// Returns every combo the engine can activate for `keymap`, by the name of its action.
///
/// That is every combo of every chord of every mode, the pause binding's, and Escape, which ends
/// a chord chain.
///
/// # Example
///
/// ```rust
/// use komorebi::kwin::hotkeys::combos;
/// use komorebi_hotkeys::{Format, ParseOptions, parse};
///
/// let parsed = parse(
/// Format::Sxhkd,
/// "super + w ; h\n komorebic focus left\n",
/// &ParseOptions::default(),
/// );
///
/// let names: Vec<String> = combos(&parsed.keymap).into_keys().collect();
///
/// assert_eq!(names, ["Esc", "H", "Meta+W"]);
/// ```
pub fn combos(keymap: &Keymap) -> BTreeMap<String, Combo> {
let mut combos: BTreeSet<Combo> = keymap
.modes
.iter()
.flat_map(|mode| &mode.bindings)
.flat_map(|binding| binding.chord.iter().copied())
.collect();
combos.extend(keymap.pause.as_ref().map(|pause| pause.combo));
combos.insert(Combo::new(Mods::NONE, Key::ESCAPE));
combos.into_iter().map(|c| (c.to_string(), c)).collect()
}
/// Returns the process that runs the command of an effect, or `None` for an effect that is not
/// a command.
///
/// An [`Effect::Komorebic`] runs `komorebic` with the words of the command, when they are made of
/// letters, digits and `_./:=,+@-` only, and through `sh -c` otherwise. `komorebic` is the one
/// next to the running `komorebi`, when there is one, so that a key runs the `komorebic` of the
/// same build; otherwise it is looked up on `PATH`. An [`Effect::Shell`] runs through `sh -c`.
///
/// # Example
///
/// ```rust
/// use komorebi::kwin::hotkeys::command;
/// use komorebi_hotkeys::engine::Effect;
///
/// let words = |effect| {
/// let command = command(&effect).unwrap();
/// let program = command.get_program().to_string_lossy().into_owned();
/// let args: Vec<String> = command.get_args().map(|a| a.to_string_lossy().into_owned()).collect();
/// (program, args)
/// };
///
/// let (program, args) = words(Effect::Komorebic("focus left".into()));
/// assert!(program.ends_with("komorebic"));
/// assert_eq!(args, ["focus", "left"]);
///
/// let (program, args) = words(Effect::Komorebic("workspace-name 0 \"my one\"".into()));
/// assert_eq!((program.as_str(), args[0].as_str()), ("sh", "-c"));
/// assert_eq!(args[1], "komorebic workspace-name 0 \"my one\"");
///
/// let (program, args) = words(Effect::Shell("notify-send hi".into()));
/// assert_eq!((program.as_str(), args), ("sh", vec!["-c".into(), "notify-send hi".into()]));
/// ```
pub fn command(effect: &Effect) -> Option<std::process::Command> {
match effect {
Effect::Komorebic(args)
if args.chars().all(|c| {
c.is_ascii_alphanumeric() || c.is_whitespace() || "_./:=,+@-".contains(c)
}) =>
{
let mut command = std::process::Command::new(komorebic());
command.args(args.split_whitespace());
Some(command)
}
Effect::Komorebic(args) => Some(shell(&format!("komorebic {args}"))),
Effect::Shell(text) => Some(shell(text)),
Effect::Activate(_) | Effect::Deactivate(_) => None,
}
}
fn shell(text: &str) -> std::process::Command {
let mut command = std::process::Command::new("sh");
command.arg("-c").arg(text);
command
}
fn komorebic() -> PathBuf {
std::env::current_exe()
.ok()
.map(|exe| exe.with_file_name("komorebic"))
.filter(|path| path.is_file())
.unwrap_or_else(|| PathBuf::from("komorebic"))
}
/// Starts a command and returns at once; a thread waits for it, so that it leaves no zombie.
fn spawn(effect: &Effect) {
let Some(mut command) = command(effect) else {
return;
};
match command.spawn() {
Ok(mut child) => {
std::thread::spawn(move || child.wait());
}
Err(error) => tracing::error!("could not run the command of a key ({effect:?}): {error}"),
}
}
/// What the thread of the keys is told
enum Message {
Stop(std::sync::mpsc::Sender<()>),
}
/// The engine that runs, if one does: the way to its thread (`kwin-hotkeys`)
static RUNNING: Mutex<Option<mpsc::UnboundedSender<Message>>> = Mutex::new(None);
/// Returns true if and only if an engine runs, started by [`start`] and not stopped since.
pub fn is_running() -> bool {
RUNNING
.lock()
.as_ref()
.is_some_and(|sender| !sender.is_closed())
}
/// Releases every key, unregisters every action of the component and ends the engine's thread,
/// and returns when that is done, or after 2 seconds. Does nothing when no engine runs.
pub fn stop() {
let Some(messages) = RUNNING.lock().take() else {
return;
};
let (done, wait) = std::sync::mpsc::channel();
if messages.send(Message::Stop(done)).is_ok() {
let _ = wait.recv_timeout(Duration::from_secs(2));
}
}
/// Starts the engine for `keymap` against kglobalaccel on the session bus, on a thread of its
/// own (`kwin-hotkeys`), and returns once its keys are registered. An engine that runs already
/// is [stopped](stop) first.
///
/// The engine runs until [`stop`] or until the session bus goes away.
///
/// # Errors
///
/// - The session bus cannot be reached.
/// - kglobalaccel is not on it (a KWin started with `--no-global-shortcuts`, or no KWin), or
/// refuses a call.
pub fn start(keymap: Keymap, options: EngineOptions) -> eyre::Result<()> {
stop();
let (messages, receiver) = mpsc::unbounded_channel();
let (started, wait) = std::sync::mpsc::channel::<eyre::Result<()>>();
std::thread::Builder::new()
.name("kwin-hotkeys".into())
.spawn(move || {
let runtime = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(runtime) => runtime,
Err(error) => {
let _ = started.send(Err(error.into()));
return;
}
};
runtime.block_on(async move {
if let Err(error) = serve(keymap, options, receiver, started).await {
tracing::error!("the keys stopped: {error}");
}
});
})?;
wait.recv()
.map_err(|_| eyre::Report::msg("the thread of the keys exited before starting"))??;
*RUNNING.lock() = Some(messages);
Ok(())
}
fn action_id(action: &str) -> Vec<String> {
vec![
COMPONENT.to_string(),
action.to_string(),
COMPONENT.to_string(),
action.to_string(),
]
}
/// Sends the calls, those of different actions without waiting for each other
async fn execute(kglobalaccel: &Proxy<'_>, calls: Vec<Call>) {
let mut by_action: BTreeMap<String, Vec<Call>> = BTreeMap::new();
for call in calls {
by_action.entry(call.action()).or_default().push(call);
}
join_all(by_action.into_iter().map(|(action, calls)| async move {
let id = action_id(&action);
for call in calls {
let result = match &call {
Call::Register(_) => kglobalaccel
.call::<_, _, ()>("doRegister", &(&id,))
.await
.map(|()| None),
Call::Grab(combo) => {
let keys = vec![(vec![combo.to_qt() as i32],)];
kglobalaccel
.call::<_, _, Vec<(Vec<i32>,)>>("setShortcutKeys", &(&id, &keys, FLAGS))
.await
.map(|set| (set != keys).then_some(set))
}
Call::Release(_) => kglobalaccel
.call::<_, _, ()>("setInactive", &(&id,))
.await
.map(|()| None),
Call::Unregister(_) => kglobalaccel
.call_method("unRegister", &(&id,))
.await
.map(|_| None),
};
match result {
Ok(None) => tracing::trace!("{call:?}"),
// kglobalaccel gives a key to one action only
Ok(Some(set)) => tracing::warn!(
"{action} is another shortcut's key, so komorebi does not get it (kglobalaccel set {set:?})"
),
Err(error) => tracing::error!("{call:?} failed: {error}"),
}
}
}))
.await;
}
async fn serve(
keymap: Keymap,
options: EngineOptions,
mut messages: mpsc::UnboundedReceiver<Message>,
started: std::sync::mpsc::Sender<eyre::Result<()>>,
) -> eyre::Result<()> {
let setup = async {
let connection = Connection::session().await?;
let kglobalaccel = Proxy::new(&connection, SERVICE, PATH, IFACE).await?;
Ok::<_, eyre::Report>((connection, kglobalaccel))
};
let (connection, kglobalaccel) = match setup.await {
Ok(setup) => setup,
Err(error) => {
let _ = started.send(Err(error));
return Ok(());
}
};
let known = combos(&keymap);
let mut engine = Engine::new(keymap, options);
let mut registry = Registry::default();
let existing: Vec<String> = kglobalaccel
.call::<_, _, Vec<Vec<String>>>("allActionsForComponent", &(action_id(""),))
.await
.unwrap_or_default()
.into_iter()
.filter_map(|id| id.get(1).cloned())
.collect();
let start = engine.start();
let calls = registry.startup(&existing, &known, &start);
let registered = calls.iter().filter(|c| matches!(c, Call::Grab(_))).count();
execute(&kglobalaccel, calls).await;
// The component's object exists once it has an action, which a start with no key to grab (every
// binding is for another application than the one with the focus) has not given it, so
// `getComponent` would refuse. A signal is matched by the path it comes from: kglobalaccel puts
// the object at the name of the component, and the engine hears the presses once there is one.
let component = async {
let path = OwnedObjectPath::try_from(format!("/component/{COMPONENT}"))?;
let component = Proxy::new(&connection, SERVICE, path, COMPONENT_IFACE).await?;
let pressed = component.receive_signal("globalShortcutPressed").await?;
let released = component.receive_signal("globalShortcutReleased").await?;
Ok::<_, eyre::Report>((pressed, released))
};
let (mut pressed, mut released) = match component.await {
Ok(streams) => streams,
Err(error) => {
let _ = started.send(Err(error));
return Ok(());
}
};
tracing::info!(
"grabbed {registered} keys in kglobalaccel, of the {} the key bindings use",
known.len()
);
let _ = started.send(Ok(()));
loop {
let effects = tokio::select! {
Some(signal) = pressed.next() => {
let (component, action, _): (String, String, i64) = signal.body().deserialize()?;
match known.get(&action) {
Some(combo) if component == COMPONENT => {
tracing::debug!("{action} pressed");
engine.on_pressed(*combo, Instant::now())
}
_ => continue,
}
}
Some(signal) = released.next() => {
let (component, action, _): (String, String, i64) = signal.body().deserialize()?;
match known.get(&action) {
Some(combo) if component == COMPONENT => engine.on_released(*combo),
_ => continue,
}
}
message = messages.recv() => match message {
Some(Message::Stop(done)) => {
let mut calls = registry.calls(&engine.stop());
calls.extend(registry.unregister_all());
execute(&kglobalaccel, calls).await;
tracing::info!("gave every key back to kglobalaccel");
let _ = done.send(());
return Ok(());
}
None => return Ok(()),
},
else => return Ok(()),
};
for effect in &effects {
spawn(effect);
}
execute(&kglobalaccel, registry.calls(&effects)).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
use komorebi_hotkeys::Format;
use komorebi_hotkeys::ParseOptions;
use komorebi_hotkeys::parse;
fn keymap(text: &str) -> Keymap {
parse(Format::Skhd, text, &ParseOptions::default()).keymap
}
#[test]
fn a_start_takes_over_the_keys_of_a_killed_komorebi_and_drops_the_rest() {
let keymap = keymap("alt - h : komorebic focus left\n:: resize\nresize < h : echo h\n");
let known = combos(&keymap);
let mut engine = Engine::new(keymap, EngineOptions::default());
let start = engine.start();
let mut registry = Registry::default();
// Alt+H and H are this keymap's; Alt+Q was another's
let existing = ["Alt+H", "H", "Alt+Q"].map(String::from);
let calls = registry.startup(&existing, &known, &start);
let alt_h = known["Alt+H"];
assert_eq!(
calls,
[
// H is in the mode resize, which is not the one the engine starts in
Call::Release(known["H"]),
Call::Unregister("Alt+Q".into()),
// registered already: grabbed again, not registered again
Call::Grab(alt_h),
]
);
// a stop releases and unregisters what was taken over, too
let mut stop = registry.calls(&engine.stop());
stop.extend(registry.unregister_all());
assert_eq!(
stop,
[
Call::Release(alt_h),
// in the order of the combos, where no modifier comes first
Call::Unregister("H".into()),
Call::Unregister("Alt+H".into()),
]
);
}
#[test]
fn a_start_with_nothing_left_behind_registers_and_grabs_the_default_mode() {
let keymap = keymap("alt - h : echo h\nalt - l : echo l\n");
let known = combos(&keymap);
let mut engine = Engine::new(keymap, EngineOptions::default());
let calls = Registry::default().startup(&[], &known, &engine.start());
let (h, l) = (known["Alt+H"], known["Alt+L"]);
assert_eq!(
calls,
[
Call::Register(h),
Call::Grab(h),
Call::Register(l),
Call::Grab(l)
]
);
}
#[test]
fn a_press_runs_the_command_and_changes_no_key() {
let keymap = keymap("alt - h : komorebic retile\n");
let known = combos(&keymap);
let mut engine = Engine::new(keymap, EngineOptions::default());
let mut registry = Registry::default();
registry.startup(&[], &known, &engine.start());
let effects = engine.on_pressed(known["Alt+H"], Instant::now());
assert_eq!(effects, [Effect::Komorebic("retile".into())]);
assert!(registry.calls(&effects).is_empty());
let command = command(&effects[0]).unwrap();
assert_eq!(command.get_args().collect::<Vec<_>>(), ["retile"]);
}
}
+7
View File
@@ -58,6 +58,9 @@
//! when it stops, and one that an earlier run left (it was killed, or the session was torn down
//! under it) is found in the first snapshot, its windows are sent home and it is removed.
//!
//! The engine of the key bindings reaches KWin's global shortcut daemon in [`hotkeys`], on a
//! connection and a thread of its own.
//!
//! [`WorkspaceChange`]: crate::window_manager_event::WindowManagerEvent::WorkspaceChange
//! [`WorkspaceMove`]: crate::window_manager_event::WindowManagerEvent::WorkspaceMove
//!
@@ -78,6 +81,7 @@
#![deny(missing_docs)]
mod effects;
pub mod hotkeys;
mod kwinrc;
pub mod power;
pub mod state;
@@ -1081,6 +1085,9 @@ impl Backend for KWinBackend {
}
fn shutdown(&self) {
// the keys go with komorebi: kglobalaccel would otherwise keep them, swallowed
hotkeys::stop();
// the window manager has already restored every window it hid. What is left is the parking
// desktop, which KWin would otherwise keep in the user's configuration, and the script,
// which KWin would otherwise keep running, reporting to nobody
+147 -2
View File
@@ -16,6 +16,13 @@
//! of the monitors on threads of their own, and runs until it is stopped, with `SIGINT`,
//! `SIGTERM` or a `Stop` message.
//!
//! With a key binding file (`--keybindings`, or the first of `skhdrc`, `whkdrc` and `sxhkdrc` in
//! [`struct@HOME_DIR`]), the daemon also runs the engine of [`komorebi_hotkeys`]: it registers the
//! keys of the bindings that are not static shortcuts with KWin's global shortcut daemon and runs
//! their commands ([`komorebi::kwin::hotkeys`]). The bindings it takes are the engine's part of
//! the file's plan in `--keybindings-mode`, the mode `komorebic hotkeys compile --mode` wrote the
//! static shortcuts in.
//!
//! It logs to standard output and to a file a day in [`struct@LOG_DIR`], which `komorebic log`
//! follows.
//!
@@ -40,6 +47,11 @@ use komorebi::process_event::listen_for_events;
use komorebi::static_config::StaticConfig;
use komorebi::window_manager::WindowManager;
use komorebi::window_manager_event_listener;
use komorebi_hotkeys::Format;
use komorebi_hotkeys::ParseOptions;
use komorebi_hotkeys::engine::EngineOptions;
use komorebi_hotkeys::plan::PlanMode;
use komorebi_hotkeys::plan::PlanOptions;
use parking_lot::Mutex;
use serde::Deserialize;
use std::net::Shutdown;
@@ -154,6 +166,52 @@ enum LogLevel {
Trace,
}
/// [`Format`], for the command line
#[derive(Clone, Copy, ValueEnum)]
enum KeyFormat {
Skhd,
Whkd,
Sxhkd,
}
impl From<KeyFormat> for Format {
fn from(format: KeyFormat) -> Self {
match format {
KeyFormat::Skhd => Format::Skhd,
KeyFormat::Whkd => Format::Whkd,
KeyFormat::Sxhkd => Format::Sxhkd,
}
}
}
/// [`PlanMode`], for the command line
#[derive(Clone, Copy, ValueEnum)]
enum KeyPlanMode {
Auto,
Engine,
Static,
}
impl From<PlanMode> for KeyPlanMode {
fn from(mode: PlanMode) -> Self {
match mode {
PlanMode::Auto => KeyPlanMode::Auto,
PlanMode::Engine => KeyPlanMode::Engine,
PlanMode::Static => KeyPlanMode::Static,
}
}
}
impl From<KeyPlanMode> for PlanMode {
fn from(mode: KeyPlanMode) -> Self {
match mode {
KeyPlanMode::Auto => PlanMode::Auto,
KeyPlanMode::Engine => PlanMode::Engine,
KeyPlanMode::Static => PlanMode::Static,
}
}
}
/// A tiling window manager for KDE Plasma.
#[derive(Parser)]
#[clap(author, about, version = version::LONG_VERSION)]
@@ -169,11 +227,93 @@ struct Opts {
/// socket interface. Windows and monitors are not real.
#[clap(long, hide = true)]
fake_backend: bool,
/// A key binding file (skhdrc, whkdrc or sxhkdrc) whose bindings komorebi registers with KDE
/// itself [default: the first of skhdrc, whkdrc and sxhkdrc in the komorebi config directory,
/// if there is one]
#[clap(long)]
keybindings: Option<PathBuf>,
/// The format of the key binding file [default: from the end of its name]
#[clap(long, value_enum)]
keybindings_format: Option<KeyFormat>,
/// Which bindings of the file komorebi registers: those that `komorebic hotkeys compile` in
/// the same mode does not write as static shortcuts
#[clap(long, value_enum, default_value_t = PlanMode::default().into())]
keybindings_mode: KeyPlanMode,
}
/// Reads the key binding file, and starts the engine for the bindings that are not static
/// shortcuts. Does nothing when there is no file, or nothing in it for the engine. An engine that
/// cannot start is logged, and the window manager runs without keys.
///
/// # Errors
///
/// The file cannot be read, or its format is neither given nor in its name.
fn keybindings(opts: &Opts) -> eyre::Result<()> {
let file = match &opts.keybindings {
Some(file) => file.clone(),
None => {
let found = [Format::Skhd, Format::Whkd, Format::Sxhkd]
.iter()
.map(|format| HOME_DIR.join(format.file_name()))
.find(|path| path.is_file());
match found {
Some(file) => file,
None => return Ok(()),
}
}
};
let format = match opts.keybindings_format {
Some(format) => format.into(),
None => {
let name = file
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default();
[Format::Skhd, Format::Whkd, Format::Sxhkd]
.into_iter()
.find(|format| name.ends_with(format.file_name()))
.ok_or_else(|| {
eyre::Report::msg(format!(
"{} does not end with skhdrc, whkdrc or sxhkdrc: give its --keybindings-format",
file.display()
))
})?
}
};
let text = std::fs::read_to_string(&file).map_err(|error| {
eyre::Report::msg(format!("could not read {}: {error}", file.display()))
})?;
let parsed = komorebi_hotkeys::parse(format, &text, &ParseOptions::default());
let plan = komorebi_hotkeys::plan::plan(
&parsed.keymap,
&PlanOptions {
mode: opts.keybindings_mode.into(),
},
);
let diagnostics = parsed.diagnostics.iter().chain(&plan.diagnostics);
for diagnostic in diagnostics.clone() {
tracing::debug!("{}: {diagnostic}", file.display());
}
let engine: usize = plan.engine.modes.iter().map(|m| m.bindings.len()).sum();
tracing::info!(
"read {}: {engine} bindings for the engine, {} static shortcuts, {} diagnostics \
(`komorebic hotkeys compile --dry-run` shows them)",
file.display(),
plan.static_files.len(),
diagnostics.count()
);
if plan.needs_engine()
&& let Err(error) = komorebi::kwin::hotkeys::start(plan.engine, EngineOptions::default())
{
tracing::error!("the key bindings are not active: {error}");
}
Ok(())
}
fn main() -> eyre::Result<()> {
let opts: Opts = Opts::parse();
let (_guard, _color_guard) = setup(opts.log_level)?;
let (_guard, _color_guard) = setup(opts.log_level.clone())?;
if !DATA_DIR.is_dir() {
std::fs::create_dir_all(&*DATA_DIR)?;
@@ -190,7 +330,7 @@ fn main() -> eyre::Result<()> {
#[cfg(feature = "deadlock_detection")]
detect_deadlocks();
let static_config = opts.config.map_or_else(
let static_config = opts.config.clone().map_or_else(
|| {
let komorebi_json = HOME_DIR.join("komorebi.json");
if komorebi_json.is_file() {
@@ -249,6 +389,11 @@ fn main() -> eyre::Result<()> {
listen_for_commands(wm.clone());
listen_for_events(wm.clone());
// the keys need KWin's global shortcut daemon, and the in-memory desktop has none
if !opts.fake_backend {
keybindings(&opts)?;
}
let (quit_sender, quit_receiver) = std::sync::mpsc::channel();
ctrlc::set_handler(move || {
let _ = quit_sender.send(());
+8 -2
View File
@@ -14,6 +14,7 @@ class Checks:
def __init__(self) -> None:
self.passed = 0
self.failed = 0
self.failures: list[str] = []
def ok(self, description: str) -> None:
"""Records a check that passed."""
@@ -23,6 +24,7 @@ class Checks:
def bad(self, description: str) -> None:
"""Records a check that failed."""
self.failed += 1
self.failures.append(description)
print(f" FAIL {description}")
def check(self, description: str, condition: bool | Callable[[], bool]) -> bool:
@@ -35,7 +37,11 @@ class Checks:
return holds
def finish(self) -> None:
"""Prints `passed: N failed: M` and raises if any check failed."""
"""Prints `passed: N failed: M` and raises if any check failed.
The error names the checks that failed, so that the last lines of a failed run, which
are all `nix build` shows, say which they were.
"""
print(f"passed: {self.passed} failed: {self.failed}")
if self.failed:
raise AssertionError(f"{self.failed} checks failed")
raise AssertionError(f"{self.failed} checks failed: {'; '.join(self.failures)}")
+32
View File
@@ -356,6 +356,38 @@ class Kde:
"""Stops the daemon with `SIGTERM`, as a logout does, and waits for it to exit."""
self.systemctl("stop", f"komorebi@{self.name}.service")
def spawn_komorebi(self, *args: str) -> None:
"""Starts the daemon inside this session, in the background, with `args`.
This is for the session node's own Plasma session, with arguments of the test's own:
the daemon is a client of the session's KWin and bus, as one started from a terminal
there is. The module's unit runs a daemon there too, with its `execStart` as it is, so a
suite that spawns its own sets `services.komorebi.enable = false` in its node. The log
goes to the file [`Kde.komorebi_log`][] reads, emptied on every start.
"""
log = f"{self.runtime}/komorebi-{self.name}.log"
self.spawn(shlex.join(["env", "NO_COLOR=1", "komorebi", *args]), log=log)
def kill_spawned_komorebi(self) -> None:
"""Kills every daemon of the machine with `SIGKILL`, as a crash would, and waits for them
to be gone: the one [`Kde.spawn_komorebi`][] started, which is not a unit to kill."""
self.machine.execute("pkill -KILL -x komorebi")
if not self.wait_for(lambda: self.machine.execute("pgrep -x komorebi")[0] != 0):
raise AssertionError("komorebi is still running after SIGKILL")
def shortcut_actions(self, component: str = "komorebi") -> list[str]:
"""The names of the actions `component` has in KDE's global shortcut daemon.
That is the empty list when the component has none, or there is no such component.
"""
status, out = self.run(
"busctl --user --json=short call org.kde.kglobalaccel /kglobalaccel"
f" org.kde.KGlobalAccel allActionsForComponent as 4 {shlex.quote(component)} '' '' ''"
)
if status != 0:
return []
return sorted(action[1] for action in json.loads(out)["data"][0])
def komorebi_running(self) -> bool:
"""Returns true if and only if the daemon of this session is running."""
unit = f"komorebi@{self.name}.service"
+1 -1
View File
@@ -28,6 +28,6 @@ def test_finish_raises_only_when_something_failed(capsys: pytest.CaptureFixture[
assert "passed: 1 failed: 0" in capsys.readouterr().out
checks.check("broken", False)
with pytest.raises(AssertionError, match="1 checks failed"):
with pytest.raises(AssertionError, match="^1 checks failed: broken$"):
checks.finish()
assert "passed: 1 failed: 1" in capsys.readouterr().out
+39
View File
@@ -785,3 +785,42 @@ def test_an_output_is_disabled_enabled_and_scaled_with_kscreen_doctor(
"kscreen-doctor output.Virtual-0.scale.1.5",
"kscreen-doctor output.Virtual-0.scale.1",
]
def test_spawn_komorebi_runs_the_daemon_in_the_session_with_its_log_where_it_is_read(
machine: FakeMachine,
) -> None:
Kde(machine, "session").spawn_komorebi("--keybindings", "/tmp/my skhdrc")
(command,) = machine.commands
assert "WAYLAND_DISPLAY=wayland-session" in command
assert inner(command) == (
"setsid nohup env NO_COLOR=1 komorebi --keybindings '/tmp/my skhdrc'"
" > /run/user/1000/komorebi-session.log 2>&1 < /dev/null &"
)
def test_kill_spawned_komorebi_kills_and_waits_until_it_is_gone(machine: FakeMachine) -> None:
machine.reply("pgrep -x komorebi", status=1)
Kde(machine, "main").kill_spawned_komorebi()
assert machine.commands[:2] == ["pkill -KILL -x komorebi", "pgrep -x komorebi"]
def test_shortcut_actions_are_the_action_names_of_the_component(machine: FakeMachine) -> None:
answer = {
"type": "aas",
"data": [
[
["komorebi", "Alt+L", "komorebi", "Alt+L"],
["komorebi", "Alt+H", "komorebi", "Alt+H"],
]
],
}
machine.reply("allActionsForComponent as 4 komorebi", output=json.dumps(answer))
assert Kde(machine, "main").shortcut_actions() == ["Alt+H", "Alt+L"]
machine.replies.clear()
machine.reply("allActionsForComponent", status=1)
assert Kde(machine, "main").shortcut_actions() == []
@@ -0,0 +1,12 @@
{
tier = "slow";
kind = "session";
timeoutMinutes = 10;
node =
{ config, ... }:
{
# the test starts, kills and stops its own daemon, with the key bindings it writes
services.komorebi.enable = false;
environment.systemPackages = [ config.services.komorebi.package ];
};
}
+81
View File
@@ -0,0 +1,81 @@
# The engine in a real Plasma session: the daemon registers the keys of a key binding file with
# KWin's global shortcut daemon and runs their commands. The Rust tests check the calls the
# engine's effects become; only KWin can say that a grabbed key reports its presses to the daemon,
# that the keys of a killed daemon stay registered until the next start takes them over, and that
# a stop gives them back.
import shlex
from komorebi_vm import Checks, Kde, Keys
start_all()
machine.wait_for_unit("multi-user.target")
checks = Checks()
kde = Kde.session(machine, scale=SCALE)
keys = Keys(machine)
def ran(marker: str) -> bool:
return machine.execute(f"test -e /tmp/{marker}")[0] == 0
def press(combo: str, marker: str) -> bool:
keys.send(combo)
return kde.wait_for(lambda: ran(marker), timeout=10)
def start(skhdrc: str) -> None:
kde.sh(
f"mkdir -p ~/.config/komorebi && printf '%s' {shlex.quote(skhdrc)} > ~/.config/komorebi/skhdrc"
)
# no --keybindings: the daemon finds the skhdrc in the config directory
kde.spawn_komorebi("--log-level", "debug")
if not kde.wait_for(lambda: "keys in kglobalaccel" in kde.komorebi_log(), timeout=60):
raise AssertionError(f"the keys were not registered:\n{kde.komorebi_log()}")
start(
"alt - h : touch /tmp/keys-engine-alt-h\n"
"alt - r : komorebic retile\n"
'alt - q : echo "$HOME" > /tmp/keys-engine-alt-q\n'
)
actions = kde.shortcut_actions()
checks.check(
f"the daemon registered its three keys ({actions})", actions == ["Alt+H", "Alt+Q", "Alt+R"]
)
checks.check("Alt+H runs its command", press("alt-h", "keys-engine-alt-h"))
checks.check("Alt+Q runs its command through a shell", press("alt-q", "keys-engine-alt-q"))
home = machine.succeed("cat /tmp/keys-engine-alt-q").strip()
checks.check(f"the shell expanded $HOME ({home!r})", home == "/home/komorebi")
keys.send("alt-r")
checks.check(
"Alt+R runs komorebic, which sends its message to the daemon",
kde.wait_for(lambda: "processing command: Retile" in kde.komorebi_log(), timeout=10),
)
# kglobalaccel keeps the keys of a daemon that was killed
kde.kill_spawned_komorebi()
checks.check("a killed daemon leaves its keys registered", kde.shortcut_actions() == actions)
# the next start takes over the keys it binds, and unregisters the others
start("alt - j : touch /tmp/keys-engine-alt-j\nalt - h : touch /tmp/keys-engine-alt-h-again\n")
actions = kde.shortcut_actions()
checks.check(f"the next start leaves only its own keys ({actions})", actions == ["Alt+H", "Alt+J"])
checks.check("Alt+J runs its command", press("alt-j", "keys-engine-alt-j"))
checks.check("Alt+H runs its new command", press("alt-h", "keys-engine-alt-h-again"))
# a stop gives every key back
kde.komorebic("stop")
checks.check(
"komorebic stop stops the daemon",
kde.wait_for(lambda: machine.execute("pgrep -x komorebi")[0] != 0, timeout=10),
)
checks.check("a stop unregisters every key", kde.shortcut_actions() == [])
machine.succeed("rm /tmp/keys-engine-alt-j")
keys.send("alt-j")
checks.check(
"Alt+J runs nothing once the daemon stopped",
not kde.wait_for(lambda: ran("keys-engine-alt-j"), timeout=3),
)
checks.finish()