feat(kwin): move and focus windows through a held call

With the commands of the Backend trait carried out, the daemon tiles a real
KWin. A command looks up the UUID KWin knows the window by, is queued as JSON
for the bridge, and returns; the held Poll call is answered with the queue, one
millisecond after the first command, so that a retile reaches KWin as one batch.
The bridge sets the frame, activates, raises, minimizes, restores or closes the
window, and reports what it could not do. set_rect records the frame it asked
for in the table, so the window manager sees it at once, and the geometry event
that follows says what the client made of it.

A KWin script cannot move the pointer, so the pointer follows the focus through
KWin's own "Move Mouse to Focus" action, invoked over kglobalaccel once KWin
reports the window active.

The commands are typed in bridge.js, and the declarations of KWin's API let the
bridge set a window's frame, its minimized state and the active window, raise
and close it, and nothing else. The session the tests of both sides share grows
a second batch: the backend's tests check that set_rect, focus, raise, minimize,
unminimize and close send it, and the bridge's tests answer the bridge with it
and check what KWin is asked to do, down to the command for a window that has
closed, which comes back as failed. The bridge's tests also cover findWindow's
fallback to KWin's list, a frame set as a plain object, and a command KWin
throws on.

Three VM suites check it against a real KWin. vm-core-e2e (from the spike's
m2-e2e, the sections that need no komorebic) compares what the daemon asked for,
read from its debug log, with what KWin has, read with kdotool: three windows
inside the screen, not overlapping, sharing it, the same focused window on both
sides, and the same again after a minimize, a restore and a close.
vm-client-geometry (slow) has eight real clients answer the frames komorebi asks
for: Qt programs and xterm take them exactly, foot sizes itself to whole cells,
GTK 4 programs and Firefox keep to their minimum sizes. vm-latency (slow) times
retiles from a recording of the session bus: on HVF, from the daemon's answer to
the last frame KWin reports, p50 17.3 ms, p95 27.7 ms. vm-kwin-events no longer
checks that nothing moves. The VM library gives session commands the test user's
home and data directories rather than root's, which a GTK client was refused.

The bridge's second request for a position after a resize, which matters for
windows off the screen, comes with the scrolling layout.
This commit is contained in:
LGUG2Z committed 2026-10-27 14:48:56 -07:00
1 parent 15ec3c1274
commit b463191d00
28 files changed
+1197 -88

No files matched your search

+3 -4
View File
@@ -16,10 +16,9 @@ cargo run --bin komorebi --locked -- --fake-backend
```
Inside a Plasma Wayland session, `komorebi` loads a script into KWin, reads the
monitors and the windows that are open, and logs every window that opens,
closes, takes the focus, is minimized or comes back, until it is stopped with
Ctrl-C. It reads the desktop and does not change it: every attempt to move
a window is logged as refused. It needs KWin 6.8 or newer;
monitors and the windows that are open, tiles them, and tiles the windows again
whenever one opens, closes, takes the focus, is minimized or comes back, until
it is stopped with Ctrl-C. It needs KWin 6.8 or newer;
[`docs/dev/PLATFORM.md`](docs/dev/PLATFORM.md) has what it expects of the
session. Outside a Plasma session it exits with an error that says what is
missing. `--fake-backend` runs the window manager against an in-memory desktop
+26 -11
View File
@@ -127,9 +127,17 @@ The path of an event: a KWin signal, the bridge's handler, `Event(json)` on the
read the pointer, so it is asked through the held call, and given 250 ms to answer before
the table's last known position is returned.
The KWin backend only reads the desktop: every command is an error, "the KWin backend only
reads the desktop", which the window manager logs. When komorebi stops, the backend asks KWin
to unload the bridge.
A command goes the other way. The backend looks up the UUID KWin knows the window by,
queues a JSON command for the bridge, and returns. The held `Poll` call is answered with the
queue, as one batch: the daemon waits a millisecond after the first command for the rest, so
that a retile of every window of a workspace reaches KWin at once. The bridge carries the
commands out in order and reports the ones it could not carry out (a window that closed in
the meantime) as a `failed` event, which is logged. `set_rect` also records the frame it
asked for in the table, so that the window manager sees it straight away; the `geometry`
event that follows says what the client made of it. The pointer cannot be moved from a
script: when it follows the focus, the backend invokes KWin's "Move Mouse to Focus" shortcut,
which centers it on the window KWin has focused. When komorebi stops, the backend asks KWin to
unload the bridge.
[`connect`] makes the backend: it connects to the session bus, loads the bridge into KWin,
and returns once the snapshot has arrived, so that the window manager reads a full table when
@@ -184,7 +192,8 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
it. The frame a window ends up with is what `window_rect` says afterwards, because a
client may refuse a size.
- A command about a window that does not exist, or is no longer alive, is an error. It
never panics.
never panics. The KWin backend knows a closed window for a minute after it closed, and
sends its commands to the bridge, which reports that it could not carry them out.
- `shutdown`, `is_window`, `window_rect` and `monitor_from_point` have defaults, written in
terms of the queries. An implementor should not need to override them, except `shutdown`
when it created something in the compositor that has to be given up.
@@ -197,7 +206,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
| A backend can be shared between threads | type system: `Backend: Send + Sync + 'static` | `compile_fail,E0277` on [`Backend`] | none |
| The window manager asks for a backend that was never installed | runtime error: [`backend`] panics, naming [`set_backend`] and [`with_backend`] | `# Panics` on [`backend`] | none |
| A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none |
| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error`, against the fake only | none |
| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none |
| A locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window` and `test_locked_containers_remove_window` | `containers_mut()` is the `VecDeque` itself |
| A window komorebi does not manage is never moved | framework path: `handle_event` asks [`Window::should_manage`] before it acts on any event but a destroy | `dialogs_and_other_non_normal_windows_are_left_alone` | none |
| A destroyed window leaves whichever workspace has it | framework path: the destroy is looked up in the index of managed windows, which is rebuilt at startup and before and after every event | `a_window_that_was_open_before_komorebi_started_is_removed_when_it_closes` | none |
@@ -207,10 +216,12 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
| No event names a window before the event that announces it | convention in the bridge, which announces a window it has not seen when it is activated; the table shows a window once | `a_new_window_raises_show_and_then_focus_in_that_order`, `announcing_the_same_window_twice_shows_it_once`, `vm-kwin-events` | none |
| A window's id names one window while the daemon runs | framework path: the table numbers each KWin window the first time it sees it, and never gives a number out twice | `ids_are_assigned_once_per_window_and_survive_a_new_snapshot`, `tombstones_are_dropped_after_a_while_and_their_ids_are_not_reused` | none |
| A backend never waits for the window manager | framework path: an event that does not fit in the channel (20 waiting) is dropped and logged | none | none |
| The KWin backend changes nothing on the desktop | runtime error: every command returns "the KWin backend only reads the desktop"; type checker: [`kwin-api.d.ts`] declares every property the bridge could set read-only | `vm-kwin-events` ("nothing was moved"), `tsc` | none |
| Every window is where komorebi asked for it, within the size its client keeps to | VM test | `vm-core-e2e`, `vm-client-geometry` | a client may refuse a size: the frame is what `window_rect` says |
| A retile reaches KWin as one batch | framework path: the answer to `Poll` waits a millisecond after the first command for the others | `vm-latency` | none |
| The window manager sees a frame it asked for at once | framework path: the KWin backend's `set_rect` records it in the table before KWin answers | `a_requested_rect_is_visible_at_once_and_replaced_by_the_real_one` | none |
| The bridge holds no window manager logic | convention, with every decision about an event in the table, which the `kwin::state` unit tests pin | the unit tests in `komorebi/src/kwin/state.rs` | none |
| What the bridge sends is what the table reads | type checker: the JSDoc types of the messages in [`bridge.js`]; tests: the events of [`fixtures`] are what the bridge's tests check it sends and what the table's tests feed it | `what the bridge sends for a session is what the daemon's tests read`, `the_bridges_events_for_a_session_are_the_window_events_komorebi_expects` | none |
| What the backend sends is what the bridge carries out | tests: the commands of [`fixtures`] are what the backend's tests check it sends and what the bridge's tests answer it with | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read` | none |
| What the backend sends is what the bridge carries out | tests: the commands of [`fixtures`] are what the backend's tests check it sends and what the bridge's tests answer it with, checking what KWin is asked to do for each | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a command for a window KWin no longer has is given back, and the rest are carried out` | none |
| Everything the bridge sends over D-Bus is one string | type checker: [`kwin-api.d.ts`] gives `callDBus` one string argument | `tsc`, `every call goes to the daemon's names, with one JSON string` | none |
| The bridge uses nothing a KWin script does not have | type checker: the library is ECMAScript 2016 alone, and KWin's API is what [`kwin-api.d.ts`] declares | `tsc` | a declaration KWin does not match: the VM tests run the bridge in KWin |
| Queries never block on the compositor | convention only | none | the KWin backend's `cursor_pos` waits up to 250 ms |
@@ -245,10 +256,12 @@ A window is shown, and ends up on a tile:
6. `Workspace::update` asks the layout for one tile per container, clamps each to the work
area, and calls [`Window::set_position`] for each window, which is the backend's
`set_rect`. The fake puts the window there at once; the frame a window ends up with is
what `window_rect` says afterwards. The KWin backend refuses, and the window stays where
KWin put it.
what `window_rect` says afterwards. The KWin backend queues a `geo` command for the
bridge, the bridge sets the window's frame, the client draws at the size it accepts, and
KWin reports the frame it ended up with as a `geometry` event, which updates the table.
7. If the new container is the only one, the window is given the focus with the backend's
`focus`, and the pointer follows it.
`focus`, and the pointer follows it (on KWin, through its "Move Mouse to Focus"
shortcut).
8. The index is rebuilt again, so the next event finds the window.
## Where to look in the code
@@ -273,7 +286,9 @@ A window is shown, and ends up on a tile:
[`tsconfig.json`](../../komorebi/src/kwin/tsconfig.json), what `tsc` checks it against;
[`bridge.test.js`], its tests; [`fixtures`], the messages both sides' tests read.
- [`nix/tests/vm/suites/kwin-events`](../../nix/tests/vm/suites/kwin-events/test.py): the
daemon against a real KWin.
events of a real KWin, through the daemon.
- [`nix/tests/vm/suites/core-e2e`](../../nix/tests/vm/suites/core-e2e/test.py): the daemon
tiling a real KWin, checked against what KWin has.
- [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager
driven end to end against the fake.
+10
View File
@@ -133,3 +133,13 @@ number as a 32-bit integer, and a call whose arguments do not match the method's
fails with no error the script can see. One string argument always matches, and the daemon
parses it. The declaration of `callDBus` the bridge is type-checked against takes one string,
so `tsc` refuses anything else.
## Why does the pointer follow the focus through a KWin shortcut?
Because a KWin script cannot move the pointer, and KWin can. Its "Move Mouse to Focus" action
puts the pointer in the middle of the window that has the focus, and it can be invoked over
D-Bus, through `kglobalaccel`: in the spikes it moved the pointer from the middle of the screen
to the middle of the focused window, for two different windows. The backend asks for it once
KWin reports the window it focused as active, so the action finds the right one. The cost is
that the pointer can go to the middle of the focused window and nowhere else, which is what
komorebi asks for.
+47 -4
View File
@@ -68,9 +68,11 @@ the windows and outputs it finds, and from then on every window that opens, clos
focus, is minimized or brought back, moves or changes size. The daemon waits up to 10 seconds
for the first report and does not start without it.
The KWin backend only reads the desktop. Every command the window manager gives it (move,
focus, raise, minimize, close a window, move the pointer) fails with "the KWin backend only
reads the desktop", which the window manager logs.
Every command of the window manager (move and resize, focus, raise, minimize, bring back or
close a window) is queued for the bridge, which gets the queue as the answer to its held call
and carries the commands out in KWin, in order. The script API cannot move the pointer, so
when the pointer follows the focus komorebi invokes KWin's own "Move Mouse to Focus" shortcut,
which puts the pointer in the middle of the window KWin has focused.
#### What komorebi leaves behind
@@ -84,7 +86,9 @@ it or the session ends.
`kwin_wayland --virtual` behaves like the KWin of a session for everything komorebi does:
the VM tests run the daemon against one, on a private session bus of its own. It cannot draw
(see [Rendering](#rendering-in-virtual-machines-and-over-rdp)), so nothing that depends on
pixels can be tested against it.
pixels can be tested against it. Started with `--no-global-shortcuts`, as the VM tests start
it, KWin does not own `org.kde.kglobalaccel`, and the pointer does not follow the focus; the
daemon logs that at debug level and carries on.
### No KWin
@@ -118,6 +122,7 @@ What komorebi calls:
|---|---|---|---|---|
| `org.kde.KWin` | `/Scripting` | `org.kde.kwin.Scripting` | `unloadScript(s)`, `loadScript(ss) -> i` | at start; `unloadScript` again at exit |
| `org.kde.KWin` | `/Scripting/Script<id>` | `org.kde.kwin.Script` | `run()` | at start |
| `org.kde.kglobalaccel` | `/component/kwin` | `org.kde.kglobalaccel.Component` | `invokeShortcut(s)`, with `MoveMouseToFocus` | when the pointer follows the focus |
## Files and directories
@@ -184,6 +189,44 @@ TypeScript are needed only for those checks: in the session the bridge needs KWi
logging category is enabled (`QT_LOGGING_RULES="kwin_scripting.debug=true"`, as the VM
tests do).
## How clients answer a frame
KWin applies a frame komorebi asks for at once, and then the client decides what size it
draws at; the frame KWin reports afterwards (a `geometry` event) is the one the client
chose. Measured at time of writing (2026-10-27) in a headless KWin with eight clients, by the
VM test `vm-client-geometry`, and by the spikes before it with more sizes and at a scale of
1.25:
| Client | Answer | In `vm-client-geometry` |
|---|---|---|
| Konsole, Kate, Dolphin (Qt, KDE) | exactly the frame asked for, also below the minimum size they report (spikes) | Kate asked for 948x527, has 948x527 |
| `xterm` on XWayland | exactly the frame asked for | asked for 229x259, has 229x259 |
| `foot` | sizes itself down to whole cells of its font | asked for 1905x2140, has 1902x2129 |
| GTK 4 Text Editor | exactly the frame asked for, down to its minimum of 360x200 | asked for 469x528, has 469x528 |
| GTK 4 Calculator | never below its minimum of 360x616 | asked for 469x259, has 469x616 |
| Firefox | never below its minimum width of 500 and height of 120 | asked for 230x259, has 500x259 |
Every client keeps the position it is asked for, also one partly off the screen. A fractional
scale of 1.25 gives the same answers as 1.0: every whole logical frame comes back as it was
asked for. komorebi does not ask again when a client keeps to a size of its own: the window
manager reads the frame the window has from the table, and a window larger than its tile
covers part of its neighbor's.
## How long a retile takes
Measured by the VM test `vm-latency` at time of writing (2026-10-27), in a headless KWin 6.8.1
under HVF on an Apple silicon Mac, with ten `foot` windows on a 3840x2160 output: twenty
retiles (a window minimized and brought back, ten times over), each of which moved 5.5 windows
on average. From the daemon's answer to `Poll` to the last frame KWin reported for the windows
the batch moved, the client's answer included:
| p50 | p95 | max |
|---|---|---|
| 17.3 ms | 27.7 ms | 31.4 ms |
The spikes measured the channel alone, with twenty windows in each batch, at 16, 19 and 20 ms
([DESIGN.md](DESIGN.md#why-do-commands-go-to-the-bridge-as-the-answer-to-a-held-call)).
## Rendering in virtual machines and over RDP
At time of writing (2026-10-27):
+11 -4
View File
@@ -36,7 +36,8 @@ JSON, which is what CI reads.
A suite has two files:
- `default.nix` sets `tier` (`"fast"` or `"slow"`), `kind` (the node it runs on)
and `timeoutMinutes`.
and `timeoutMinutes`, and may set `node`, a NixOS module that adds to the node
for this suite alone (more memory, the clients it starts).
- `test.py` is the test, a Python script for the NixOS test driver. It is
prefixed with `SCALE = <number>`, how many times slower than KVM the machine
is.
@@ -96,14 +97,20 @@ the run.
session once its desktop is up, and `shot(name)` returns a screenshot as a
Pillow image, keeping `NAME.png` in the output directory.
- `activate`, `minimize` and `close` act on a window through `kdotool`, as the
user would.
user would, and `wid_by_class` finds a window by its app id or X11 class.
`Kde.headless(..., xwayland=True)` gives the session XWayland, for X11
clients.
- `start_komorebi(*args)` starts the daemon in the session, `stop_komorebi()`
stops it with `SIGTERM`, `komorebi_log()` returns its log since it was last
started, and `script_loaded()` asks KWin whether it runs the bridge.
- `daemon` reads the daemon's view of the desktop from that log, started with
`--log-level debug`: `daemon.events(log)` lists the window events it handled,
in order, and `daemon.window_ids(log)` maps a window's title to the daemon's id
for it.
in order, `daemon.window_ids(log)` maps a window's title to the daemon's id
for it, and `daemon.requests(log)` returns the frame the daemon last asked KWin
for, for each window.
- `monitor_bridge(path)` records the bridge's traffic on the session bus with
`dbus-monitor`, and `latency.rounds` times each batch of commands in it, from
the daemon's answer to the last frame KWin reports for the windows it moved.
Poll for what the test needs with `wait_for`. A fixed sleep is too long on
KVM and too short on TCG.
+54 -4
View File
@@ -62,11 +62,19 @@
*/
/**
* What the daemon sends: the answer to `Poll` is a list of batches, each a list of commands. The
* only command is the cursor query, which `token` numbers so that its answer can be matched.
* What the daemon sends: the answer to `Poll` is a list of batches, each a list of commands. A
* window command names the window by its `id`: `geo` sets its frame, `min` minimizes it (`v`) or
* brings it back, and `activate`, `raise` and `close` do what they say. A cursor query is
* numbered by `token` so that its answer can be matched.
*
* @typedef {{ op: "cursor", token: number }} CursorQuery
* @typedef {CursorQuery} Command
* @typedef {{ op: "geo", id: string, x: number, y: number, w: number, h: number }} SetFrame
* @typedef {{ op: "min", id: string, v: boolean }} SetMinimized
* @typedef {{ op: "activate", id: string }} Activate
* @typedef {{ op: "raise", id: string }} Raise
* @typedef {{ op: "close", id: string }} Close
* @typedef {SetFrame | SetMinimized | Activate | Raise | Close} WindowCommand
* @typedef {CursorQuery | WindowCommand} Command
* @typedef {{ batch: number, cmds: Command[] }} Batch
*/
@@ -185,6 +193,23 @@ function cursor() {
return { x: Math.round(p.x), y: Math.round(p.y) };
}
/**
* @param {string} id
* @returns {KWinWindow | null}
*/
function findWindow(id) {
if (known[id]) {
return known[id];
}
var l = workspace.windowList();
for (var i = 0; i < l.length; i++) {
if (wid(l[i]) === id) {
return l[i];
}
}
return null;
}
// ---- hooks ---------------------------------------------------------------------------------
/**
@@ -259,7 +284,32 @@ function applyOne(c) {
emit("cursor", { token: c.token, x: p.x, y: p.y });
return true;
}
return false;
var w = findWindow(c.id);
if (!w) {
return false;
}
switch (c.op) {
case "geo":
// a plain object converts to QRectF; there is no `Qt` global in kwin scripts
w.frameGeometry = { x: c.x, y: c.y, width: c.w, height: c.h };
break;
case "min":
w.minimized = !!c.v;
break;
case "activate":
workspace.activeWindow = w;
break;
case "raise":
workspace.raiseWindow(w);
break;
case "close":
w.closeWindow();
break;
default:
return false;
}
return true;
}
/** @param {Batch} batch */
+75 -4
View File
@@ -57,7 +57,8 @@ function geometry(x, y, width, height) {
}
// A window. `id` becomes its `internalId`, which is a QUuid in KWin: an object, not a string.
// Setting `minimized` or `frameGeometry` raises the signal KWin raises.
// Setting `minimized` or `frameGeometry` raises the signal KWin raises, and `closeWindow` closes it
// once it is in a KWin.
function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100), ...rest }) {
const w = {
internalId: { toString: () => id },
@@ -76,6 +77,7 @@ function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100
desktops: [],
frameGeometryChanged: new Signal(),
minimizedChanged: new Signal(),
closeWindow: () => assert.fail("a window that is in no KWin was closed"),
...rest,
};
let state = { minimized, frameGeometry };
@@ -115,9 +117,10 @@ const DP1 = {
function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y: 0 } } = {}) {
const calls = [];
const printed = [];
const raised = [];
const timers = [];
const clock = { now: 1000 };
const open = windows.slice();
const open = [];
let activeWindow = active;
const workspace = {
@@ -130,6 +133,7 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y
return output.placementArea;
},
currentDesktopForScreen: (output) => ({ id: `desktop of ${output.name}` }),
raiseWindow: (w) => raised.push(w),
windowAdded: new Signal(),
windowRemoved: new Signal(),
windowActivated: new Signal(),
@@ -155,6 +159,13 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y
}
}
// a window KWin has: it can close
function adopt(w) {
open.push(w);
w.closeWindow = () => k.close(w);
}
windows.forEach(adopt);
const context = vm.createContext({
workspace,
KWin: { PlacementArea: 7 },
@@ -173,6 +184,7 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y
workspace,
calls,
printed,
raised,
timers,
clock,
// what the bridge has sent with `Event`, oldest first
@@ -182,7 +194,7 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y
reply: (text) => calls.filter((c) => c.method === "Poll").at(-1).callback(text),
// a window opens: KWin activates it before it announces it, unless it is not to be focused
open: (w, { focus = true } = {}) => {
open.push(w);
adopt(w);
if (focus) {
workspace.activeWindow = w;
}
@@ -245,14 +257,24 @@ test("what the bridge sends for a session is what the daemon's tests read", () =
// the client took the frame it was given to whole cells of its font
terminal.frameGeometry = geometry(480.4, 270, 956, 532);
const [cursorQuery] = commands;
const [cursorQuery, windowCommands] = commands;
assert.equal(k.events().at(-1).seq, cursorQuery.after_seq);
k.workspace.cursorPos = { x: 1200, y: 700.5 };
k.answer([cursorQuery.batch]);
k.close(terminal);
// the editor is tiled, focused, raised, minimized and brought back, the dialog closed, and the
// terminal, which has closed, is asked for a frame
assert.equal(k.events().at(-1).seq, windowCommands.after_seq);
k.answer([windowCommands.batch]);
assert.deepStrictEqual(k.events(), events);
assert.deepStrictEqual(editor.frameGeometry, geometry(0, 0, 960, 1050));
assert.equal(k.workspace.activeWindow, editor);
assert.deepStrictEqual(k.raised, [editor]);
assert.equal(editor.minimized, false);
assert.deepStrictEqual(k.workspace.windowList(), [editor]);
});
test("a window KWin activates before announcing it is announced first, and once", () => {
@@ -387,3 +409,52 @@ test("a command the bridge does not know is given back as failed", () => {
{ type: "failed", batch: 4, cmds: [{ op: "teleport" }], seq: 3 },
]);
});
test("a frame is set as a plain object, and the frame KWin gives comes back as an event", () => {
const w = window({ id: "{w}", frameGeometry: geometry(0, 0, 100, 100) });
const k = kwin({ windows: [w] });
k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: 10, y: 20, w: 300, h: 400 }] }]);
assert.deepStrictEqual(w.frameGeometry, geometry(10, 20, 300, 400));
assert.deepStrictEqual(k.events().slice(1), [
{ type: "geometry", id: "{w}", geo: { x: 10, y: 20, w: 300, h: 400 }, seq: 2 },
]);
});
test("a window the bridge has not seen is found in KWin's list", () => {
const k = kwin();
const unseen = window({ id: "{unseen}" });
// in KWin's list, without a windowAdded
k.workspace.windowList = () => [unseen];
k.answer([{ batch: 1, cmds: [{ op: "min", id: "{unseen}", v: true }] }]);
assert.equal(unseen.minimized, true);
assert.equal(k.events().length, 1, "and nothing failed");
});
test("a command for a window KWin no longer has is given back, and the rest are carried out", () => {
const w = window({ id: "{w}" });
const k = kwin({ windows: [w] });
const gone = { op: "activate", id: "{gone}" };
k.answer([{ batch: 3, cmds: [gone, { op: "raise", id: "{w}" }] }]);
assert.deepStrictEqual(k.raised, [w]);
assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 3, cmds: [gone], seq: 2 });
});
test("a command KWin throws on is printed and given back as failed", () => {
const w = window({ id: "{w}" });
const k = kwin({ windows: [w] });
w.closeWindow = () => {
throw new Error("the window is being destroyed");
};
const close = { op: "close", id: "{w}" };
k.answer([{ batch: 5, cmds: [close] }]);
assert.match(k.printed[0], /^komorebi bridge: Error: the window is being destroyed in /);
assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 5, cmds: [close], seq: 2 });
});
+22 -1
View File
@@ -1,3 +1,24 @@
[
{"after_seq": 7, "batch": {"batch": 1, "cmds": [{"op": "cursor", "token": 1}]}}
{"after_seq": 7, "batch": {"batch": 1, "cmds": [{"op": "cursor", "token": 1}]}},
{
"after_seq": 9,
"batch": {
"batch": 2,
"cmds": [
{
"op": "geo", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}",
"x": 0, "y": 0, "w": 960, "h": 1050
},
{"op": "activate", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}"},
{"op": "raise", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}"},
{"op": "min", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": true},
{"op": "min", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": false},
{"op": "close", "id": "{c4b8a2f0-0000-4000-8000-00000000000c}"},
{
"op": "geo", "id": "{7f3d9e21-0000-4000-8000-00000000000b}",
"x": 960, "y": 0, "w": 960, "h": 1050
}
]
}
}
]
+18 -1
View File
@@ -42,5 +42,22 @@
"geo": {"x": 480, "y": 270, "w": 956, "h": 532}
},
{"type": "cursor", "seq": 8, "token": 1, "x": 1200, "y": 701},
{"type": "removed", "seq": 9, "id": "{7f3d9e21-0000-4000-8000-00000000000b}"}
{"type": "removed", "seq": 9, "id": "{7f3d9e21-0000-4000-8000-00000000000b}"},
{
"type": "geometry", "seq": 10, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}",
"geo": {"x": 0, "y": 0, "w": 960, "h": 1050}
},
{"type": "activated", "seq": 11, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}"},
{"type": "minimized", "seq": 12, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": true},
{"type": "minimized", "seq": 13, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": false},
{"type": "removed", "seq": 14, "id": "{c4b8a2f0-0000-4000-8000-00000000000c}"},
{
"type": "failed", "seq": 15, "batch": 2,
"cmds": [
{
"op": "geo", "id": "{7f3d9e21-0000-4000-8000-00000000000b}", "x": 960, "y": 0,
"w": 960, "h": 1050
}
]
}
]
+7 -3
View File
@@ -71,25 +71,29 @@ interface KWinWindow {
readonly skipTaskbar: boolean;
readonly skipPager: boolean;
readonly skipSwitcher: boolean;
readonly minimized: boolean;
minimized: boolean;
readonly fullScreen: boolean;
/** `KWin::MaximizeMode`: 0 restored, 1 vertically, 2 horizontally, 3 both ways. */
readonly maximizeMode: number;
readonly frameGeometry: QRectF;
/** Set to a plain `{x, y, width, height}`: a script has no `Qt` global to make a `QRectF`. */
frameGeometry: QRectF;
readonly minSize: QSizeF;
readonly desktops: VirtualDesktop[];
readonly frameGeometryChanged: Signal<[oldGeometry: QRectF]>;
readonly minimizedChanged: Signal;
closeWindow(): void;
}
/** The global `workspace` (`KWin::ScriptingWorkspace`). */
interface Workspace {
readonly screens: Output[];
readonly activeWindow: KWinWindow | null;
/** Setting it activates the window. */
activeWindow: KWinWindow | null;
readonly cursorPos: QPointF;
windowList(): KWinWindow[];
clientArea(option: number, output: Output, desktop: VirtualDesktop): QRectF;
currentDesktopForScreen(output: Output): VirtualDesktop;
raiseWindow(window: KWinWindow): void;
readonly windowAdded: Signal<[window: KWinWindow]>;
readonly windowRemoved: Signal<[window: KWinWindow]>;
/** `null` when no window has the focus. */
+120 -26
View File
@@ -23,9 +23,9 @@
//! against a fake KWin (`just check-js`). Its tests and the tests of this module and of [`state`]
//! read the same messages, in `fixtures/`, so that what one side sends is what the other reads.
//!
//! The backend reads the desktop: it answers every query from the [`state::Table`], and turns
//! what KWin reports into the window events of [`crate::window_manager_event`]. It does not change
//! the desktop: every command of [`Backend`] is an error.
//! The backend answers every query from the [`state::Table`], turns what KWin reports into the
//! window events of [`crate::window_manager_event`], and queues every command of [`Backend`] for
//! the script, which carries it out in KWin.
//!
//! `docs/dev/PLATFORM.md` has the D-Bus names, the files and the environment variables involved,
//! and `docs/dev/DESIGN.md` the reasons for this design.
@@ -201,14 +201,23 @@ impl Poll {
}
}
/// The desktop of a running KWin, read through the script komorebi loads into it.
/// The desktop of a running KWin, read and changed through the script komorebi loads into it.
///
/// The queries are answered from a [`state::Table`] that the script's events keep up to date, so
/// they do not wait for KWin, except [`Backend::cursor_pos`]: only the script can read the pointer,
/// so it is asked, and given 250 ms to answer.
///
/// The backend only reads the desktop. Every command ([`Backend::set_rect`],
/// [`Backend::focus`] and the rest) returns an error and changes nothing.
/// A command ([`Backend::set_rect`], [`Backend::focus`] and the rest) is queued for the script and
/// returns: the script gets the queue as the answer to its held `Poll` call, and carries the
/// commands out in order. Commands queued within a millisecond of each other go out as one batch,
/// so a retile reaches KWin at once. A command is an error when the table does not know the
/// window; a command for a window that has just closed is sent, and the script reports that it
/// could not carry it out, which is logged.
///
/// The script cannot move the pointer, so the pointer follows the focus through KWin's own "Move
/// Mouse to Focus" action, over `kglobalaccel`: it lands in the middle of the window KWin has
/// focused, whatever rectangle [`Backend::center_cursor_in`] is given. A KWin without global
/// shortcuts leaves the pointer where it is.
///
/// It is made by [`connect`].
pub struct KWinBackend {
@@ -384,9 +393,37 @@ async fn load_script(connection: &Connection) -> eyre::Result<()> {
Ok(())
}
/// The error of every command: the backend reads the desktop and changes nothing
fn read_only<T>() -> eyre::Result<T> {
eyre::bail!("the KWin backend only reads the desktop")
/// KWin's own "Move Mouse to Focus" action: the scripting API cannot move the pointer
async fn move_mouse_to_focus(shared: &Shared) -> eyre::Result<()> {
let connection = shared.connection().await?;
let component = Proxy::new(
&connection,
"org.kde.kglobalaccel",
"/component/kwin",
"org.kde.kglobalaccel.Component",
)
.await?;
component
.call_method("invokeShortcut", &("MoveMouseToFocus",))
.await?;
Ok(())
}
fn command_rect(uuid: &str, rect: &Rect) -> Value {
json!({ "op": "geo", "id": uuid, "x": rect.left, "y": rect.top, "w": rect.right, "h": rect.bottom })
}
impl KWinBackend {
fn command(&self, id: u32, build: impl FnOnce(&str) -> Value) -> eyre::Result<()> {
let uuid = self
.shared
.table
.lock()
.uuid(id)
.ok_or_eyre("there is no such window")?;
self.shared.push(build(&uuid));
Ok(())
}
}
impl Backend for KWinBackend {
@@ -424,32 +461,62 @@ impl Backend for KWinBackend {
answer.or_else(|| self.shared.table.lock().cursor())
}
fn set_rect(&self, _id: u32, _rect: &Rect) -> eyre::Result<()> {
read_only()
fn set_rect(&self, id: u32, rect: &Rect) -> eyre::Result<()> {
tracing::debug!("asking for window {id} to be at {rect:?}");
self.command(id, |uuid| command_rect(uuid, rect))?;
self.shared.table.lock().note_requested_rect(id, *rect);
Ok(())
}
fn focus(&self, _id: u32, _mouse_follows_focus: bool) -> eyre::Result<()> {
read_only()
fn focus(&self, id: u32, mouse_follows_focus: bool) -> eyre::Result<()> {
self.command(id, |uuid| json!({ "op": "activate", "id": uuid }))?;
if mouse_follows_focus {
// the pointer can only follow once the window really is the active one
let shared = self.shared.clone();
self.shared.handle.spawn(async move {
for _ in 0..60 {
if shared.table.lock().foreground() == Some(id) {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
if let Err(error) = move_mouse_to_focus(&shared).await {
tracing::debug!("could not move the mouse to the focused window: {error}");
}
});
}
Ok(())
}
fn raise(&self, _id: u32) -> eyre::Result<()> {
read_only()
fn raise(&self, id: u32) -> eyre::Result<()> {
self.command(id, |uuid| json!({ "op": "raise", "id": uuid }))
}
fn minimize(&self, _id: u32) -> eyre::Result<()> {
read_only()
fn minimize(&self, id: u32) -> eyre::Result<()> {
self.command(id, |uuid| json!({ "op": "min", "id": uuid, "v": true }))
}
fn unminimize(&self, _id: u32) -> eyre::Result<()> {
read_only()
fn unminimize(&self, id: u32) -> eyre::Result<()> {
self.command(id, |uuid| json!({ "op": "min", "id": uuid, "v": false }))
}
fn close(&self, _id: u32) -> eyre::Result<()> {
read_only()
fn close(&self, id: u32) -> eyre::Result<()> {
self.command(id, |uuid| json!({ "op": "close", "id": uuid }))
}
fn center_cursor_in(&self, _rect: &Rect) -> eyre::Result<()> {
read_only()
// KWin can center the pointer on the active window and nothing else; the WM calls this
// right after focusing the window in question
let shared = self.shared.clone();
self.shared.handle.spawn(async move {
if let Err(error) = move_mouse_to_focus(&shared).await {
tracing::debug!("could not move the mouse to the focused window: {error}");
}
});
Ok(())
}
fn shutdown(&self) {
@@ -520,10 +587,29 @@ mod tests {
serde_json::from_str(include_str!("fixtures/commands.json")).unwrap();
// what the window manager asks of the backend, batch by batch
let asks: [fn(&KWinBackend); 1] = [|backend| {
// nothing answers the query here, so the pointer is where the snapshot had it
assert_eq!(backend.cursor_pos(), Some((481, 525)));
}];
let asks: [fn(&KWinBackend); 2] = [
|backend| {
// nothing answers the query here, so the pointer is where the snapshot had it
assert_eq!(backend.cursor_pos(), Some((481, 525)));
},
|backend| {
let left = |left| Rect {
left,
top: 0,
right: 960,
bottom: 1050,
};
// the editor is 1, the terminal 2 and the dialog 3
backend.set_rect(1, &left(0)).unwrap();
backend.focus(1, false).unwrap();
backend.raise(1).unwrap();
backend.minimize(1).unwrap();
backend.unminimize(1).unwrap();
backend.close(3).unwrap();
// the terminal has closed, and the table still knows it: the bridge gives it back
backend.set_rect(2, &left(960)).unwrap();
},
];
assert_eq!(asks.len(), commands.len());
let mut handled = 0;
@@ -540,6 +626,14 @@ mod tests {
}
}
#[test]
fn a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing() {
let (runtime, backend) = offline();
assert!(backend.focus(7, false).is_err());
assert_eq!(next_poll(&runtime, &backend), json!([]));
}
#[test]
fn a_poll_with_nothing_to_send_is_answered_with_nothing_once_its_hold_is_over() {
let (runtime, backend) = offline();
+50 -3
View File
@@ -201,12 +201,26 @@ impl Table {
self.cursor
}
/// Returns the UUID KWin knows the window by, which is how a command for the script names
/// it, or `None` if the table does not know the window.
pub fn uuid(&self, id: u32) -> Option<String> {
self.windows.get(&id).map(|e| e.uuid.clone())
}
/// Whether komorebi should have anything to do with this window: a normal window, as opposed
/// to a dialog, a panel, a popup.
fn manageable(&self, entry: &Entry) -> bool {
entry.kwin_normal
}
/// Records the frame komorebi has just asked KWin to give a window, so that the window manager
/// sees it at once. The `geometry` event that says what the client did replaces it.
pub fn note_requested_rect(&mut self, id: u32, rect: Rect) {
if let Some(entry) = self.windows.get_mut(&id) {
entry.info.rect = rect;
}
}
// ---- events ----------------------------------------------------------------------------
fn id_for(&mut self, uuid: &str) -> u32 {
@@ -597,16 +611,24 @@ mod tests {
"geometry -> ",
"cursor -> Cursor 1 at 1200,701",
"removed -> Destroy 2",
// the window manager's commands, and the terminal's, which had closed
"geometry -> ",
"activated -> FocusChange 1",
"minimized -> Minimize 1",
"minimized -> Restore 1",
"removed -> ",
"failed -> ",
]
);
// the editor of the snapshot is left, and its dialog, which komorebi does not manage
// the editor of the snapshot is left; its dialog, which komorebi does not manage, closed
let windows = t.windows();
assert_eq!(windows.len(), 1);
assert_eq!(windows[0].title, "notes.txt — Kate");
assert_eq!(t.window(3).map(|w| w.normal), Some(false));
assert_eq!(windows[0].rect.right, 960, "the frame komorebi asked for");
assert_eq!(t.window(3).map(|w| w.alive), Some(false));
assert_eq!(t.window(2).unwrap().rect.bottom, 532, "the geometry event");
assert_eq!(t.foreground(), None, "the terminal had the focus");
assert_eq!(t.foreground(), Some(1));
assert_eq!(t.cursor(), Some((1200, 701)));
let monitor = &t.monitors()[0];
@@ -830,4 +852,29 @@ mod tests {
));
assert_eq!(t.cursor(), Some((300, 400)));
}
#[test]
fn a_requested_rect_is_visible_at_once_and_replaced_by_the_real_one() {
let mut t = table(vec![win("a", &["d1"])]);
t.note_requested_rect(
1,
Rect {
left: 0,
top: 0,
right: 960,
bottom: 1050,
},
);
assert_eq!(t.window(1).unwrap().rect.right, 960);
t.handle(
&json!({ "type": "geometry", "id": "a", "geo": {"x":0,"y":0,"w":956,"h":1048} }),
Instant::now(),
);
assert_eq!(
t.window(1).unwrap().rect.right,
956,
"the client rounded it to its cell grid"
);
}
}
+2 -1
View File
@@ -84,7 +84,8 @@ let
node.specialArgs.komorebi = komorebiFor guestSystem;
nodes.machine = {
imports = [ (./nodes + "/${suite.kind}.nix") ];
# a suite's `node`, if it has one, adds to the node of its kind
imports = [ (./nodes + "/${suite.kind}.nix") ] ++ lib.optional (suite ? node) suite.node;
};
testScript = ''
+5 -3
View File
@@ -7,16 +7,18 @@ A suite imports what it needs from here:
the tools to look at it (`kdotool`, `busctl`, `kscreen-doctor`, screenshots)
and the komorebi daemon that runs in it.
* [`daemon`](komorebi_vm.daemon) reads what the daemon logs about the events it
handles.
handles and the frames it asks for.
* [`latency`](komorebi_vm.latency) times the daemon's commands from a recording
of the session bus.
The library depends on the small [`Machine`](komorebi_vm.machine.Machine)
protocol, not on the test driver, so `nix/tests/vm/lib/tests` can run it
against a fake machine (the `vm-lib` check does).
"""
from komorebi_vm import daemon
from komorebi_vm import daemon, latency
from komorebi_vm.checks import Checks
from komorebi_vm.kde import Kde, Rect
from komorebi_vm.machine import Machine
__all__ = ["Checks", "Kde", "Machine", "Rect", "daemon"]
__all__ = ["Checks", "Kde", "Machine", "Rect", "daemon", "latency"]
+27 -2
View File
@@ -2,15 +2,22 @@
A test reads the daemon's view of the desktop from its log
([`Kde.komorebi_log`](komorebi_vm.kde.Kde.komorebi_log)), started with
`--log-level debug`: every event it handles is an info line, and every focus
change KWin reports names the window by the daemon's id and its title.
`--log-level debug`: every event it handles is an info line, every focus
change KWin reports names the window by the daemon's id and its title, and
every frame the daemon asks KWin for is a debug line.
"""
import re
from dataclasses import dataclass
from komorebi_vm.kde import Rect
_EVENT = re.compile(r"processing event: (\w+) for window (\d+) with notification (\w+)")
_ACTIVATED = re.compile(r"KWin activated window (\d+) \((.*)\)$", re.MULTILINE)
_REQUEST = re.compile(
r"asking for window (\d+) to be at "
r"Rect \{ left: (-?\d+), top: (-?\d+), right: (-?\d+), bottom: (-?\d+) \}"
)
@dataclass(frozen=True)
@@ -36,3 +43,21 @@ def window_ids(log: str) -> dict[str, int]:
A title that two windows had is the later one's.
"""
return {title: int(window) for window, title in _ACTIVATED.findall(log)}
def requests(log: str) -> dict[int, Rect]:
"""Returns the frame the daemon last asked KWin for, for each window, by the daemon's id."""
return {
int(window): Rect(int(x), int(y), int(w), int(h))
for window, x, y, w, h in _REQUEST.findall(log)
}
def asked(log: str, title: str) -> Rect | None:
"""Returns the frame the daemon last asked KWin for, for the window with this title.
`None` if KWin never gave the window the focus (which is how its title reaches the log), or
the daemon never asked for a frame for it.
"""
window = window_ids(log).get(title)
return requests(log).get(window) if window is not None else None
+46 -4
View File
@@ -63,6 +63,7 @@ class Kde:
self.scale = scale
self._bus = bus
self._wayland_display = wayland_display
self._x_display: str | None = None
@classmethod
def headless(
@@ -72,20 +73,33 @@ class Kde:
*,
size: tuple[int, int] = (1920, 1080),
outputs: int = 1,
xwayland: bool = False,
scale: float = 1.0,
user: str = "komorebi",
uid: int = 1000,
) -> "Kde":
"""Starts `kwin_wayland --virtual` with `outputs` outputs of `size`, and waits for it."""
"""Starts `kwin_wayland --virtual` with `outputs` outputs of `size`, and waits for it.
With `xwayland`, KWin also runs XWayland, for X11 clients. It starts it when the first
one connects and does not say where, so the session takes the first X11 socket of the
machine: one session at a time can have XWayland.
"""
kde = cls(machine, name, user=user, uid=uid, scale=scale)
machine.succeed(f"loginctl show-user {user} >/dev/null")
width, height = size
args = f"--width {width} --height {height} --output-count {outputs}"
if xwayland:
args += " --xwayland"
kde.as_user(f"echo KWIN_ARGS={shlex.quote(args)} > {kde.runtime}/kwin-virtual-{name}.env")
kde.systemctl("start", f"session-bus@{name}.service", f"kwin-virtual@{name}.service")
if not kde.wait_for(lambda: kde.has_name("org.kde.KWin"), timeout=60):
log = machine.execute(f"journalctl _UID={uid} --no-pager -n 40")[1]
raise AssertionError(f"KWin did not come up:\n{log}")
if xwayland:
socket = "ls /tmp/.X11-unix | grep -E '^X[0-9]+$' | sort | head -n 1"
if not kde.wait_for(lambda: machine.execute(socket)[1].strip() != "", timeout=10):
raise AssertionError("KWin did not open an X11 socket")
kde._x_display = ":" + machine.execute(socket)[1].strip()[1:]
return kde
@classmethod
@@ -139,6 +153,7 @@ class Kde:
@property
def env(self) -> str:
"""The `VAR=value` words that put a command inside this session."""
profile = f"/etc/profiles/per-user/{self.user}"
pairs = {
"XDG_RUNTIME_DIR": self.runtime,
"DBUS_SESSION_BUS_ADDRESS": self._bus
@@ -149,7 +164,13 @@ class Kde:
"XDG_SESSION_TYPE": "wayland",
"QT_QPA_PLATFORM": "wayland",
"GDK_BACKEND": "wayland",
# the user's, not those of root's shell, which a client would search and be refused
"HOME": f"/home/{self.user}",
"XDG_DATA_DIRS": f"{profile}/share:/run/current-system/sw/share",
"XDG_CONFIG_DIRS": f"/etc/xdg:{profile}/etc/xdg:/run/current-system/sw/etc/xdg",
}
if self._x_display is not None:
pairs["DISPLAY"] = self._x_display
return " ".join(f"{key}={shlex.quote(value)}" for key, value in pairs.items())
def as_user(self, command: str) -> str:
@@ -164,9 +185,12 @@ class Kde:
"""Runs `command` inside the session, and fails the test unless it succeeds."""
return self.machine.succeed(self._wrap(command))
def spawn(self, command: str) -> None:
"""Starts `command` in the background inside the session, as a client of KWin."""
self.sh(f"setsid nohup {command} >/dev/null 2>&1 < /dev/null &")
def spawn(self, command: str, log: str = "/dev/null") -> None:
"""Starts `command` in the background inside the session, as a client of KWin.
Its output goes to the file `log`, or nowhere.
"""
self.sh(f"setsid nohup {command} > {shlex.quote(log)} 2>&1 < /dev/null &")
def systemctl(self, *args: str) -> str:
"""Runs `systemctl --user` as the test user."""
@@ -202,6 +226,15 @@ class Kde:
"""The daemon's log since it was last started, or the empty string before that."""
return self.machine.execute(f"cat {self.runtime}/komorebi-{self.name}.log")[1]
def monitor_bridge(self, path: str) -> None:
"""Starts recording the bridge's traffic on the session bus to `path`, in the background.
`dbus-monitor` records every call to the daemon's `org.komorebi.Bridge` interface and every
reply on the bus, which [`latency.rounds`](komorebi_vm.latency.rounds) reads.
"""
rules = "\"type='method_call',interface='org.komorebi.Bridge'\" \"type='method_return'\""
self.sh(f"setsid nohup dbus-monitor --session {rules} > {path} 2>&1 < /dev/null &")
def script_loaded(self, name: str = "komorebi-bridge") -> bool:
"""Returns true if and only if KWin runs a script loaded under `name`."""
status, out = self.run(
@@ -235,6 +268,15 @@ class Kde:
pattern = shlex.quote(f"^{title}$")
return self.run(f"kdotool search --name {pattern} | head -1")[1].strip()
def wid_by_class(self, app: str) -> str:
"""The id of the first window whose class is exactly `app`, or the empty string.
The class is the Wayland app id (`org.kde.konsole`), or the X11 class of a client
on XWayland (`XTerm`).
"""
pattern = shlex.quote(f"^{app}$")
return self.run(f"kdotool search --class {pattern} | head -1")[1].strip()
def rect(self, wid: str) -> Rect:
"""The position and size KWin reports for the window."""
out = self.sh(f"kdotool getwindowgeometry {shlex.quote(wid)}")
+133
View File
@@ -0,0 +1,133 @@
"""How long the commands of the daemon take to reach the windows of KWin.
[`Kde.monitor_bridge`](komorebi_vm.kde.Kde.monitor_bridge) records the bridge's
traffic on the session bus with `dbus-monitor`: every `Event` call the script
makes, with its JSON, and every reply on the bus, among them the daemon's answers
to `Poll`, which carry the commands. Each line `dbus-monitor` prints for a message
has the time the bus delivered it to the monitor.
A **round** starts when the daemon answers `Poll` with a batch that asks for a
window to be somewhere it was not asked to be before, and ends with the last
`geometry` event KWin reports for one of those windows before the next such batch
(or within a cut-off). Its duration is how long the windows took to be where the
daemon put them, the client's answer included.
"""
import json
import math
import re
from dataclasses import dataclass
from typing import Any
from komorebi_vm.kde import Rect
_HEADER = re.compile(r"^(method call|method return|signal|error) time=(\d+\.\d+) (.*)$")
_STRING = ' string "'
@dataclass(frozen=True)
class Message:
"""One D-Bus message, as `dbus-monitor` printed it."""
kind: str
"""`method call`, `method return`, `signal` or `error`."""
time: float
"""When the bus delivered it, in seconds since the epoch."""
member: str
"""The method or signal, or the empty string for a reply."""
body: str
"""The first string argument, or the empty string."""
@dataclass(frozen=True)
class Round:
"""The windows of one batch of commands, from the batch to the last frame KWin reported."""
sent: float
"""When the daemon's answer to `Poll` was delivered."""
windows: int
"""How many windows the batch moved."""
seconds: float | None
"""How long until the last of them reported its frame, or `None` if one never did."""
def messages(text: str) -> list[Message]:
"""Parses what `dbus-monitor` printed, in its default format."""
out: list[Message] = []
header: re.Match[str] | None = None
body = ""
def flush() -> None:
if header is not None:
fields = header.group(3)
member = re.search(r"member=(\S+)", fields)
out.append(
Message(header.group(1), float(header.group(2)), member[1] if member else "", body)
)
for line in text.splitlines():
if match := _HEADER.match(line):
flush()
header, body = match, ""
elif header is not None and not body and line.startswith(_STRING) and line.endswith('"'):
body = line[len(_STRING) : -1]
flush()
return out
def _json(text: str) -> Any:
try:
return json.loads(text)
except ValueError:
return None
def rounds(text: str, cut_off: float = 2.0) -> list[Round]:
"""Returns every round in what `dbus-monitor` printed, in order.
A batch that asks every window for the frame it was last asked for moves
nothing, and is not a round. A round ends at the next round, or `cut_off`
seconds after it started, whichever comes first.
"""
batches: list[tuple[float, dict[str, Rect]]] = []
frames: list[tuple[float, str]] = []
for message in messages(text):
value = _json(message.body)
if message.kind == "method return" and isinstance(value, list):
geo = {
command["id"]: Rect(command["x"], command["y"], command["w"], command["h"])
for batch in value
if isinstance(batch, dict)
for command in batch.get("cmds", [])
if command.get("op") == "geo"
}
if geo:
batches.append((message.time, geo))
elif message.member == "Event" and isinstance(value, dict):
if value.get("type") == "geometry":
frames.append((message.time, value["id"]))
asked: dict[str, Rect] = {}
moving: list[tuple[float, set[str]]] = []
for sent, geo in batches:
moved = {uuid for uuid, rect in geo.items() if asked.get(uuid) != rect}
asked.update(geo)
if moved:
moving.append((sent, moved))
out = []
for i, (sent, moved) in enumerate(moving):
end = sent + cut_off
if i + 1 < len(moving):
end = min(end, moving[i + 1][0])
last = {uuid: t for t, uuid in frames if sent < t <= end and uuid in moved}
seconds = max(last.values()) - sent if len(last) == len(moved) else None
out.append(Round(sent, len(moved), seconds))
return out
def percentile(values: list[float], fraction: float) -> float:
"""The value below which `fraction` of the values are (nearest rank)."""
ordered = sorted(values)
rank = min(len(ordered), max(1, math.ceil(fraction * len(ordered))))
return ordered[rank - 1]
+25 -1
View File
@@ -1,4 +1,4 @@
from komorebi_vm import daemon
from komorebi_vm import Rect, daemon
from komorebi_vm.daemon import Event
LOG = """\
@@ -26,3 +26,27 @@ def test_window_ids_are_found_by_title_also_one_with_parentheses() -> None:
def test_an_empty_log_has_nothing_in_it() -> None:
assert daemon.events("") == []
assert daemon.window_ids("") == {}
def test_requests_are_the_last_frame_asked_for_each_window() -> None:
log = (
"DEBUG komorebi::kwin: asking for window 2 to be at "
"Rect { left: 10, top: 10, right: 1900, bottom: 1060 }\n"
"DEBUG komorebi::kwin: asking for window 3 to be at "
"Rect { left: -5, top: 0, right: 940, bottom: 1060 }\n"
"DEBUG komorebi::kwin: asking for window 2 to be at "
"Rect { left: 10, top: 10, right: 940, bottom: 1060 }\n"
)
assert daemon.requests(log) == {2: Rect(10, 10, 940, 1060), 3: Rect(-5, 0, 940, 1060)}
def test_asked_finds_the_frame_by_the_title_of_the_window() -> None:
log = LOG + (
"DEBUG komorebi::kwin: asking for window 2 to be at "
"Rect { left: 10, top: 10, right: 940, bottom: 1060 }\n"
)
assert daemon.asked(log, "alpha") == Rect(10, 10, 940, 1060)
assert daemon.asked(log, "a (b) c") is None
assert daemon.asked(log, "nobody") is None
+57
View File
@@ -186,3 +186,60 @@ def test_window_actions_go_through_kdotool_inside_the_session(machine: FakeMachi
"kdotool windowclose '{a}'",
]
assert all("WAYLAND_DISPLAY=wayland-main" in command for command in machine.commands)
def test_wid_by_class_searches_the_class(machine: FakeMachine) -> None:
machine.reply("kdotool search --class", output="{x}\n")
assert Kde(machine, "main").wid_by_class("XTerm") == "{x}"
assert inner(machine.commands[0]) == "kdotool search --class '^XTerm$' | head -1"
def test_headless_with_xwayland_starts_it_and_puts_the_x11_display_in_the_session(
machine: FakeMachine,
) -> None:
machine.reply("busctl", status=0)
machine.reply("/tmp/.X11-unix", output="X1\n")
kde = Kde.headless(machine, "main", xwayland=True)
scripts = [inner(command) for command in machine.commands if " sh -c " in command]
assert any("--output-count 1 --xwayland'" in script for script in scripts)
assert "DISPLAY=:1" in kde.env.split()
assert not any(word.startswith("DISPLAY=") for word in Kde(machine, "other").env.split())
def test_monitor_bridge_records_the_calls_to_the_bridge_and_the_replies(
machine: FakeMachine,
) -> None:
Kde(machine, "main").monitor_bridge("/tmp/bus.log")
(script,) = [inner(command) for command in machine.commands]
assert script.startswith("setsid nohup dbus-monitor --session ")
assert "\"type='method_call',interface='org.komorebi.Bridge'\"" in script
assert "\"type='method_return'\"" in script
assert script.endswith("> /tmp/bus.log 2>&1 < /dev/null &")
def test_spawn_sends_the_output_of_the_client_where_it_is_asked(machine: FakeMachine) -> None:
kde = Kde(machine, "main")
kde.spawn("foot")
kde.spawn("xterm -T x", log="/tmp/x.log")
assert [inner(command) for command in machine.commands] == [
"setsid nohup foot > /dev/null 2>&1 < /dev/null &",
"setsid nohup xterm -T x > /tmp/x.log 2>&1 < /dev/null &",
]
def test_a_session_has_the_users_data_and_config_directories_not_roots(
machine: FakeMachine,
) -> None:
words = Kde(machine, "main").env.split()
assert "HOME=/home/komorebi" in words
assert (
"XDG_DATA_DIRS=/etc/profiles/per-user/komorebi/share:/run/current-system/sw/share" in words
)
assert not any("/root" in word for word in words)
+91
View File
@@ -0,0 +1,91 @@
import json
import pytest
from komorebi_vm import latency
from komorebi_vm.latency import Message, Round
def call(time: float, body: dict[str, object]) -> str:
return (
f"method call time={time:.6f} sender=:1.5 -> destination=org.komorebi.Bridge serial=1"
" path=/org/komorebi/Bridge; interface=org.komorebi.Bridge; member=Event\n"
f' string "{json.dumps(body)}"\n'
)
def answer(time: float, cmds: list[dict[str, object]]) -> str:
batches = [{"batch": 1, "cmds": cmds}]
return (
f"method return time={time:.6f} sender=:1.3 -> destination=:1.5 serial=9 reply_serial=2\n"
f' string "{json.dumps(batches)}"\n'
)
def geo(uuid: str, x: int) -> dict[str, object]:
return {"op": "geo", "id": uuid, "x": x, "y": 0, "w": 100, "h": 100}
def frame(time: float, uuid: str) -> str:
return call(time, {"type": "geometry", "id": uuid, "geo": {"x": 0, "y": 0, "w": 9, "h": 9}})
def test_messages_are_parsed_with_their_time_member_and_string() -> None:
text = call(1.5, {"type": "added"}) + (
"method return time=2.000000 sender=:1.1 -> destination=:1.2 serial=3 reply_serial=1\n"
" boolean true\n"
)
assert latency.messages(text) == [
Message("method call", 1.5, "Event", '{"type": "added"}'),
Message("method return", 2.0, "", ""),
]
def test_a_round_lasts_until_the_last_window_it_moved_reports_its_frame() -> None:
text = (
answer(10.0, [geo("a", 0), geo("b", 100)])
+ frame(10.004, "a")
+ frame(10.010, "b")
+ frame(10.016, "a")
)
(only,) = latency.rounds(text)
assert (only.sent, only.windows) == (10.0, 2)
assert only.seconds == pytest.approx(0.016)
def test_asking_again_for_the_same_frames_is_not_a_round() -> None:
text = (
answer(10.0, [geo("a", 0)])
+ frame(10.01, "a")
+ answer(11.0, [geo("a", 0), {"op": "activate", "id": "a"}])
+ answer(12.0, [geo("a", 50)])
+ frame(12.02, "a")
)
rounds = latency.rounds(text)
assert [r.sent for r in rounds] == [10.0, 12.0]
assert (rounds[1].sent, rounds[1].windows) == (12.0, 1)
assert rounds[1].seconds == pytest.approx(0.02)
def test_a_window_that_never_reports_leaves_its_round_unsettled() -> None:
text = answer(10.0, [geo("a", 0)]) + frame(13.0, "a")
assert latency.rounds(text) == [Round(10.0, 1, None)]
def test_a_round_ends_where_the_next_one_starts() -> None:
text = answer(10.0, [geo("a", 0)]) + answer(10.5, [geo("a", 9)]) + frame(10.6, "a")
assert [r.seconds for r in latency.rounds(text)] == [None, pytest.approx(0.1)]
def test_percentile_is_the_nearest_rank() -> None:
values = [float(n) for n in range(1, 21)]
assert latency.percentile(values, 0.5) == 10.0
assert latency.percentile(values, 0.95) == 19.0
assert latency.percentile(values, 1.0) == 20.0
assert latency.percentile([3.0], 0.5) == 3.0
+2
View File
@@ -52,6 +52,8 @@
description = "A headless KWin for the test session %i";
requires = [ "session-bus@%i.service" ];
after = [ "session-bus@%i.service" ];
# KWin looks for Xwayland on its PATH, when it is started with --xwayland
path = [ pkgs.xwayland ];
environment = {
DBUS_SESSION_BUS_ADDRESS = "unix:path=%t/session-%i.bus";
XDG_SESSION_TYPE = "wayland";
@@ -0,0 +1,23 @@
{
tier = "slow";
kind = "headless";
timeoutMinutes = 20;
node =
{ pkgs, ... }:
{
# eight clients, Firefox among them
virtualisation = {
memorySize = 6144;
cores = 4;
};
environment.systemPackages = with pkgs; [
firefox
gnome-calculator
gnome-text-editor
kdePackages.dolphin
kdePackages.kate
kdePackages.konsole
xterm
];
};
}
+101
View File
@@ -0,0 +1,101 @@
# How real clients answer the frame komorebi asks for. KWin carries out a request at once; the
# client then decides the size it draws at, and that is the frame KWin reports. What only real
# clients can tell, and what the fake desktop of the Rust tests cannot know: Qt and KDE programs
# and X11 programs on XWayland take the frame exactly, also below the minimum size they report;
# foot sizes itself down to whole cells of its font; GTK 4 programs and Firefox never go below
# their minimum size. Every client keeps the position komorebi asked for. The output is large
# enough that some tiles are bigger and some smaller than the clients' minimums.
from komorebi_vm import Checks, Kde, Rect, daemon
W, H = 3840, 2160
CELL = 24
EXACT = ["org.kde.konsole", "org.kde.kate", "org.kde.dolphin", "XTerm"]
WHOLE_CELLS = ["foot"]
NOT_BELOW_MINIMUM = ["org.gnome.TextEditor", "org.gnome.Calculator", "firefox"]
CLIENTS = {
"foot": "foot -T foot-term sleep 3000",
"org.kde.konsole": "konsole --separate",
"org.kde.dolphin": "dolphin --new-window /tmp",
"org.kde.kate": "kate --new",
"org.gnome.TextEditor": "gnome-text-editor --new-window",
"org.gnome.Calculator": "gnome-calculator",
"XTerm": "xterm -T xterm-x11",
"firefox": "firefox --no-remote --profile /tmp/firefox-profile about:blank",
}
start_all()
machine.wait_for_unit("multi-user.target")
machine.wait_for_unit("user@1000.service")
checks = Checks()
kde = Kde.headless(machine, "main", size=(W, H), xwayland=True, scale=SCALE)
kde.as_user("mkdir -p /tmp/firefox-profile")
kde.start_komorebi("--log-level", "debug")
checks.check(
"the daemon loaded its script into KWin",
kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30),
)
for app, command in CLIENTS.items():
kde.spawn(command, log=f"/tmp/{app}.log")
up = kde.wait_for(lambda app=app: kde.wid_by_class(app) != "", timeout=120)
if not checks.check(f"{app} has a window", up):
print(machine.execute(f"cat /tmp/{app}.log")[1])
def shown() -> int:
return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show")
checks.check("the daemon tiles all eight", kde.wait_for(lambda: shown() >= 8, timeout=60))
def show(r: Rect | None) -> str:
return "-" if r is None else f"{r.x},{r.y} {r.w}x{r.h}"
def snapshot() -> dict[str, Rect]:
return {app: kde.rect(kde.wid_by_class(app)) for app in CLIENTS}
# the clients answer in their own time; the frames are final once they stop changing
before: dict[str, Rect] = {}
def still() -> bool:
global before
now = snapshot()
unchanged = now == before
before = now
return unchanged
kde.wait_for(still, timeout=60, interval=3)
requests = list(daemon.requests(kde.komorebi_log()).values())
print(f" {'client':<22} {'asked':<22} {'has':<22}")
for app, have in snapshot().items():
asked = [r for r in requests if (r.x, r.y) == (have.x, have.y)]
want = asked[0] if asked else None
print(f" {app:<22} {show(want):<22} {show(have):<22}")
if not checks.check(f"{app} is where komorebi put it", want is not None):
continue
assert want is not None
if app in EXACT:
checks.check(f"{app} takes the size it is asked for", (have.w, have.h) == (want.w, want.h))
elif app in WHOLE_CELLS:
checks.check(
f"{app} sizes itself down to whole cells",
0 <= want.w - have.w < CELL and 0 <= want.h - have.h < CELL,
)
elif app in NOT_BELOW_MINIMUM:
checks.check(
f"{app} is never smaller than it is asked to be",
have.w >= want.w and have.h >= want.h,
)
kde.stop_komorebi()
kde.stop()
checks.finish()
+5
View File
@@ -0,0 +1,5 @@
{
tier = "fast";
kind = "headless";
timeoutMinutes = 10;
}
+142
View File
@@ -0,0 +1,142 @@
# komorebi tiles a real KWin. What only a real KWin can tell: that the commands the daemon queues
# reach KWin through the held call and that KWin carries them out, so that each window is where
# the daemon asked for it (`komorebi/tests/wm_events.rs` checks the window manager's side against
# the fake), and that the daemon and KWin agree on which window has the focus. A window manager
# that agrees with itself proves nothing, so what the daemon believes is read from its debug log
# and what KWin has through kdotool.
from komorebi_vm import Checks, Kde, Rect, daemon
W, H = 1920, 1080
# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for
CELL = 24
start_all()
machine.wait_for_unit("multi-user.target")
machine.wait_for_unit("user@1000.service")
checks = Checks()
kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE)
def daemon_log() -> str:
return kde.komorebi_log()
def inside(r: Rect) -> bool:
return r.x >= 0 and r.y >= 0 and r.x + r.w <= W and r.y + r.h <= H
def asked(title: str) -> Rect | None:
return daemon.asked(daemon_log(), title)
def where_asked(title: str) -> bool:
"""KWin has the window where the daemon asked: the same place, and the size up to a cell."""
want, wid = asked(title), kde.wid(title)
if want is None or wid == "":
return False
have = kde.rect(wid)
return (
(have.x, have.y) == (want.x, want.y)
and 0 <= want.w - have.w < CELL
and 0 <= want.h - have.h < CELL
)
def focus_agrees() -> bool:
"""The window KWin has focused is the one the daemon last handled a focus change for."""
log = daemon_log()
focus_changes = [e.window for e in daemon.events(log) if e.kind == "FocusChange"]
active = kde.active()
if not focus_changes or active == "":
return False
return daemon.window_ids(log).get(kde.title(active)) == focus_changes[-1]
def report(titles: list[str]) -> None:
for title in titles:
print(f" {title}: asked {asked(title)}, has {kde.rect(kde.wid(title))}")
print("== 1. start")
kde.start_komorebi("--log-level", "debug")
checks.check(
"the daemon loaded its script into KWin",
kde.wait_for(lambda: "loaded the KWin bridge script" in daemon_log(), timeout=30),
)
checks.check("KWin runs the script", kde.script_loaded())
print("== 2. three windows are tiled")
titles = ["win1", "win2", "win3"]
for title in titles:
kde.spawn(f"foot -T {title} sleep 3000")
kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30)
kde.wait_for(lambda title=title: title in daemon.window_ids(daemon_log()), timeout=10)
settled = kde.wait_for(lambda: all(where_asked(t) for t in titles), timeout=20)
report(titles)
checks.check("every window is where the daemon asked for it", settled)
rects = [kde.rect(kde.wid(t)) for t in titles]
for title, rect in zip(titles, rects, strict=True):
checks.check(f"{title} is inside the screen", inside(rect))
checks.check("win1 and win2 do not overlap", not rects[0].overlaps(rects[1]))
checks.check("win1 and win3 do not overlap", not rects[0].overlaps(rects[2]))
checks.check("win2 and win3 do not overlap", not rects[1].overlaps(rects[2]))
checks.check("the windows share the screen: none is full width", all(r.w < W - 20 for r in rects))
checks.check("KWin and the daemon agree on the focused window", kde.wait_for(focus_agrees))
print("== 3. the focus moves by hand")
kde.activate(kde.wid("win1"))
checks.check("KWin focused win1", kde.wait_for(lambda: kde.title(kde.active()) == "win1"))
checks.check("... and the daemon followed", kde.wait_for(focus_agrees))
print("== 4. minimize and restore")
kde.minimize(kde.wid("win2"))
two = ["win1", "win3"]
checks.check(
"the other two windows take the screen",
kde.wait_for(
lambda: (
all(where_asked(t) for t in two)
and all(kde.rect(kde.wid(t)).w > W // 2 - 40 for t in two)
),
timeout=20,
),
)
report(two)
kde.activate(kde.wid("win2"))
checks.check(
"restored, the three windows are tiled again",
kde.wait_for(
lambda: (
all(where_asked(t) for t in titles)
and all(kde.rect(kde.wid(t)).w < W - 20 for t in titles)
),
timeout=20,
),
)
report(titles)
print("== 5. close")
kde.close(kde.wid("win3"))
checks.check("KWin closed win3", kde.wait_for(lambda: kde.wid("win3") == "", timeout=10))
checks.check(
"the two that are left share the screen again",
kde.wait_for(
lambda: (
all(where_asked(t) for t in ["win1", "win2"])
and not kde.rect(kde.wid("win1")).overlaps(kde.rect(kde.wid("win2")))
),
timeout=20,
),
)
report(["win1", "win2"])
checks.check("KWin carried out every command", "the bridge could not do" not in daemon_log())
print("== 6. stop")
kde.stop_komorebi()
checks.check("the daemon exited", not kde.komorebi_running())
checks.check("the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded()))
checks.check("the windows stay", kde.wid("win1") != "" and kde.wid("win2") != "")
kde.stop()
checks.finish()
+2 -12
View File
@@ -1,8 +1,8 @@
# The daemon reads a real KWin through its script. What only a real KWin can tell: that the script
# loads and reports the desktop, that KWin's signals reach the window manager as the events
# `komorebi/src/kwin/state.rs` and `komorebi/tests/wm_events.rs` feed it by hand, in the order KWin
# raised them (KWin activates a new window before it announces it), that the daemon moves nothing
# while its backend only reads, and that it takes its script out of KWin when it stops.
# raised them (KWin activates a new window before it announces it), and that it takes its script
# out of KWin when it stops.
from komorebi_vm import Checks, Kde, daemon
from komorebi_vm.daemon import Event
@@ -28,7 +28,6 @@ checks.check(
kde.wait_for(lambda: kde.wid("before") != "", timeout=30),
)
before = kde.wid("before")
where_it_opened = kde.rect(before)
kde.start_komorebi("--log-level", "debug")
checks.check(
@@ -98,15 +97,6 @@ checks.check(
in_order == ["Show", "Minimize", "Restore", "Destroy"],
)
print("== nothing was moved")
checks.check(
"the daemon asked to tile, and was told the backend only reads",
"the KWin backend only reads the desktop" in daemon_log(),
)
checks.check(
"the window that was open before is where KWin put it", kde.rect(before) == where_it_opened
)
print("== stop")
kde.stop_komorebi()
checks.check("the daemon exited", not kde.komorebi_running())
+10
View File
@@ -0,0 +1,10 @@
{
tier = "slow";
kind = "headless";
timeoutMinutes = 15;
node =
{ pkgs, ... }:
{
environment.systemPackages = [ pkgs.dbus ];
};
}
+83
View File
@@ -0,0 +1,83 @@
# How long a retile takes to reach the windows of a real KWin, measured on the session bus: from
# the moment the daemon answers the bridge's held call with a batch of new frames, to the last
# frame KWin reports for one of the windows it moved, the client's answer included. Every number
# here comes from KWin and real clients; the Rust tests cannot measure it. The output is large, so
# that ten windows in komorebi's default layout all have room.
from komorebi_vm import Checks, Kde, daemon, latency
W, H = 3840, 2160
WINDOWS = 10
ROUNDS = 10
BUS_LOG = "/tmp/komorebi-bus.log"
start_all()
machine.wait_for_unit("multi-user.target")
machine.wait_for_unit("user@1000.service")
checks = Checks()
kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE)
kde.start_komorebi()
checks.check(
"the daemon loaded its script into KWin",
kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30),
)
kde.monitor_bridge(BUS_LOG)
titles = [f"w{n}" for n in range(1, WINDOWS + 1)]
for title in titles:
kde.spawn(f"foot -T {title} sleep 3000")
kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30)
def shown() -> int:
return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show")
checks.check(f"the daemon tiles all {WINDOWS}", kde.wait_for(lambda: shown() >= WINDOWS))
def measured() -> list[latency.Round]:
return latency.rounds(machine.succeed(f"cat {BUS_LOG}"))
def settled_after(count: int) -> bool:
"""A round after the first `count` is over: its windows all reported, and then 0.3 s passed."""
done = measured()
if len(done) <= count or done[-1].seconds is None:
return False
now = float(machine.succeed("date +%s.%N"))
return now - (done[-1].sent + done[-1].seconds) > 0.3
kde.wait_for(lambda: settled_after(0), timeout=10)
start = len(measured())
# each round takes one window out of the layout and puts it back: two retiles
for title in titles[:ROUNDS]:
wid = kde.wid(title)
count = len(measured())
kde.minimize(wid)
kde.wait_for(lambda count=count: settled_after(count), timeout=10)
count = len(measured())
kde.activate(wid)
kde.wait_for(lambda count=count: settled_after(count), timeout=10)
# the rounds before `start` tiled the windows as they opened
rounds = measured()[start:]
settled = [r.seconds * 1000 for r in rounds if r.seconds is not None]
moved = sum(r.windows for r in rounds) / max(1, len(rounds))
print(f" {len(rounds)} retiles, {moved:.1f} windows moved by each on average, scale {SCALE}")
if settled:
p50, p95 = latency.percentile(settled, 0.5), latency.percentile(settled, 0.95)
print(f" from the batch to the last frame: p50 {p50:.1f} ms, p95 {p95:.1f} ms,")
print(f" max {max(settled):.1f} ms, min {min(settled):.1f} ms")
checks.check(f"{2 * ROUNDS} retiles were measured", len(rounds) == 2 * ROUNDS)
checks.check("every window of every retile reported its frame", len(settled) == len(rounds))
checks.check(
"a retile reaches the windows within 100 ms (times the machine's scale), at p95",
bool(settled) and latency.percentile(settled, 0.95) <= 100 * SCALE,
)
kde.stop_komorebi()
kde.stop()
checks.finish()