From b02df47e34c0454588bd96537b0b7b1529de1e7d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 19:37:22 -0700 Subject: [PATCH] feat(nix): Snapshot, the daemon's state in one shape for every port komorebic state prints a different JSON on kfde and on kfw: a window is {id, rect, details} on one and {hwnd, title, exe, class, rect} on the other, and a monitor and the state itself have fields the other lacks. core.snapshot.parse reads either into monitors, workspaces, containers and windows with the same names, keeping what only one has in Snapshot.extra, so that a scenario does not have to care which port it runs on. The fixtures in its tests are written from the two serializers, not recorded; they are replaced by recorded states once a run on each port exists. --- docs/dev/vm-tests.md | 6 + nix/tests/vm/lib/komorebi_vm/core/snapshot.py | 178 ++++++++++++++++++ nix/tests/vm/lib/tests/test_snapshot.py | 99 ++++++++++ 3 files changed, 283 insertions(+) create mode 100644 nix/tests/vm/lib/komorebi_vm/core/snapshot.py create mode 100644 nix/tests/vm/lib/tests/test_snapshot.py diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index b76e2eb1..99da76a6 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -143,6 +143,12 @@ the run. `Rect` and the pixel helpers. It imports nothing of KDE, so that it can move to the Windows port unchanged. `komorebi_vm` re-exports them, so that a suite imports them from the same place as before. +- `Snapshot` (`core/snapshot.py`) is the daemon's state in one shape for every port: + `snapshot.parse(json)` reads the `komorebic state` of kfde and of kfw into + monitors, workspaces, containers and windows. What only one port's state has + goes in `Snapshot.extra`. Its unit tests use fixtures written from the two + ports' serializers; recorded states replace them once a run on each port + exists. - `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`, and its error names the checks that failed, which `nix build` shows in the last lines diff --git a/nix/tests/vm/lib/komorebi_vm/core/snapshot.py b/nix/tests/vm/lib/komorebi_vm/core/snapshot.py new file mode 100644 index 00000000..d3a88b10 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/core/snapshot.py @@ -0,0 +1,178 @@ +"""The daemon's state, in one shape for every port. + +`komorebic state` prints a different JSON for each port. kfde serializes a window as +`{id, rect, details: {title, exe, class, path}}`, kfw as `{hwnd, title, exe, class, rect}`; a +monitor has `serial_number_id` on one and `device_id` on the other; and the state has fields only +one of them has. A scenario must not care, so it reads a +[`Snapshot`](komorebi_vm.core.snapshot.Snapshot): monitors, workspaces, containers and windows, +with the same names and types whatever printed them. + +`rect` is `{left, top, right, bottom}` on both ports, where `right` and `bottom` are the width and +the height, which is what [`Rect`](komorebi_vm.core.geometry.Rect) takes. +""" + +from dataclasses import dataclass, field +from typing import Any + +from komorebi_vm.core.geometry import Rect + + +@dataclass(frozen=True) +class Window: + """A window the daemon manages.""" + + id: int + """The daemon's id: the compositor's on kfde, the handle on kfw.""" + title: str + exe: str + window_class: str + rect: Rect | None + """Where the daemon last saw the window. `None` when the state has no rect for it.""" + + +@dataclass(frozen=True) +class Workspace: + """A workspace of a monitor.""" + + name: str | None + layout: str + """The layout's name: `BSP`, `Columns`, ... or `Custom`.""" + tile: bool + containers: list[list[Window]] + """The tiled containers, in order, each with its stack of windows.""" + focused_container: int + monocle: list[Window] | None + """The windows of the monocle container, or `None` when the workspace is not in monocle.""" + maximized: Window | None + floating: list[Window] + latest_layout: list[Rect] + """The rectangles the layout last computed, one for each container.""" + + def windows(self) -> list[Window]: + """Every window of the workspace: the tiled ones, the monocle ones, the maximized one and + the floating ones.""" + found = [w for container in self.containers for w in container] + found += self.monocle or [] + found += [self.maximized] if self.maximized is not None else [] + return found + self.floating + + +@dataclass(frozen=True) +class Monitor: + """A monitor, with its workspaces.""" + + id: int + size: Rect + work_area: Rect + workspaces: list[Workspace] + focused_workspace: int + + +@dataclass(frozen=True) +class Snapshot: + """The state of a daemon: its monitors, and which is focused.""" + + monitors: list[Monitor] + focused_monitor: int + paused: bool = False + extra: dict[str, Any] = field(default_factory=dict, compare=False) + """What only this port's state has, such as `has_pending_raise_op` on kfw.""" + + def workspace(self, workspace: int = 0, monitor: int = 0) -> Workspace: + """A workspace of a monitor, by position.""" + return self.monitors[monitor].workspaces[workspace] + + def containers(self, workspace: int = 0, monitor: int = 0) -> list[list[str]]: + """The titles of the windows of each tiled container of a workspace.""" + return [[w.title for w in c] for c in self.workspace(workspace, monitor).containers] + + def managed(self) -> int: + """The number of windows the daemon has, on every workspace of every monitor.""" + return sum(len(ws.windows()) for m in self.monitors for ws in m.workspaces) + + def focused_title(self, workspace: int = 0, monitor: int = 0) -> str: + """The title of the focused window of a workspace: the focused window of its focused + container. Empty if the workspace has no container.""" + ws = self.workspace(workspace, monitor) + if not ws.containers: + return "" + container = ws.containers[min(ws.focused_container, len(ws.containers) - 1)] + return container[0].title if container else "" + + +def _ring(value: dict[str, Any]) -> list[Any]: + return list(value["elements"]) + + +def _focused(value: dict[str, Any]) -> int: + return int(value.get("focused", 0)) + + +def _rect(value: dict[str, Any] | None) -> Rect | None: + if value is None: + return None + return Rect(value["left"], value["top"], value["right"], value["bottom"]) + + +def _window(value: dict[str, Any]) -> Window: + # kfde nests what it knows about the window under `details`; kfw puts it beside the handle + details = value.get("details", value) + return Window( + id=int(value["id"] if "id" in value else value["hwnd"]), + title=str(details.get("title", "")), + exe=str(details.get("exe", "")), + window_class=str(details.get("class", "")), + rect=_rect(value.get("rect")), + ) + + +def _layout(value: Any) -> str: + # `{"Default": "BSP"}` for a built-in layout, `{"Custom": [...]}` for a custom one + if isinstance(value, dict) and value: + name, inner = next(iter(value.items())) + return str(inner) if name == "Default" else str(name) + return str(value) + + +def _workspace(value: dict[str, Any]) -> Workspace: + containers = [[_window(w) for w in _ring(c["windows"])] for c in _ring(value["containers"])] + monocle = value.get("monocle_container") + maximized = value.get("maximized_window") + return Workspace( + name=value.get("name"), + layout=_layout(value.get("layout")), + tile=bool(value.get("tile", True)), + containers=containers, + focused_container=_focused(value["containers"]), + monocle=[_window(w) for w in _ring(monocle["windows"])] if monocle else None, + maximized=_window(maximized) if maximized else None, + floating=[_window(w) for w in _ring(value["floating_windows"])], + latest_layout=[r for r in map(_rect, value.get("latest_layout", [])) if r is not None], + ) + + +def _monitor(value: dict[str, Any]) -> Monitor: + size = _rect(value["size"]) + work_area = _rect(value.get("work_area_size")) or size + assert size is not None and work_area is not None + return Monitor( + id=int(value["id"]), + size=size, + work_area=work_area, + workspaces=[_workspace(w) for w in _ring(value["workspaces"])], + focused_workspace=_focused(value["workspaces"]), + ) + + +_COMMON = {"monitors", "is_paused"} + + +def parse(state: dict[str, Any]) -> Snapshot: + """Reads the JSON of `komorebic state`, from either port.""" + monitors = state["monitors"] + return Snapshot( + monitors=[_monitor(m) for m in _ring(monitors)], + focused_monitor=_focused(monitors), + paused=bool(state.get("is_paused", False)), + extra={k: v for k, v in state.items() if k not in _COMMON}, + ) diff --git a/nix/tests/vm/lib/tests/test_snapshot.py b/nix/tests/vm/lib/tests/test_snapshot.py new file mode 100644 index 00000000..893af625 --- /dev/null +++ b/nix/tests/vm/lib/tests/test_snapshot.py @@ -0,0 +1,99 @@ +"""The same scene, as each port prints it, reads as the same Snapshot. + +The fixtures are written from the `Serialize` code of the two ports (kfde `komorebi/src/window.rs`, +kfw `komorebi/src/window.rs`), not recorded; a recorded state of each replaces them once a run on +each port exists. +""" + +from typing import Any + +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.snapshot import parse + + +def ring(*elements: Any, focused: int = 0) -> dict[str, Any]: + return {"elements": list(elements), "focused": focused} + + +def rect(x: int, y: int, w: int, h: int) -> dict[str, int]: + return {"left": x, "top": y, "right": w, "bottom": h} + + +def kfde_window(id: int, title: str, where: dict[str, int]) -> dict[str, Any]: + details = {"title": title, "exe": "foot", "class": "foot", "path": "/usr/bin/foot"} + return {"id": id, "rect": where, "details": details} + + +def kfw_window(id: int, title: str, where: dict[str, int]) -> dict[str, Any]: + return {"hwnd": id, "title": title, "exe": "foot", "class": "foot", "rect": where} + + +def scene( + window: Any, monitor_extra: dict[str, Any], state_extra: dict[str, Any] +) -> dict[str, Any]: + left, right = rect(0, 0, 960, 1080), rect(960, 0, 960, 1080) + workspace = { + "name": "main", + "containers": ring( + {"id": "a", "locked": False, "windows": ring(window(1, "win1", left))}, + {"id": "b", "locked": False, "windows": ring(window(2, "win2", right))}, + focused=1, + ), + "monocle_container": None, + "maximized_window": None, + "floating_windows": ring(window(3, "float", rect(10, 10, 300, 200))), + "layout": {"Default": "BSP"}, + "tile": True, + "latest_layout": [left, right], + } + monitor = { + "id": 7, + "size": rect(0, 0, 1920, 1080), + "work_area_size": rect(0, 0, 1920, 1040), + "workspaces": ring(workspace), + **monitor_extra, + } + return {"monitors": ring(monitor), "is_paused": False, **state_extra} + + +KFDE = scene(kfde_window, {"serial_number_id": "x"}, {}) +KFW = scene(kfw_window, {"device_id": "d", "name": "DISPLAY1"}, {"has_pending_raise_op": False}) + + +def test_both_ports_read_as_the_same_snapshot() -> None: + assert parse(KFDE) == parse(KFW) + + +def test_a_snapshot_names_the_windows_of_each_container() -> None: + snap = parse(KFDE) + assert snap.containers() == [["win1"], ["win2"]] + assert snap.focused_title() == "win2" + assert snap.managed() == 3 + + +def test_a_window_has_its_frame_and_what_identifies_it() -> None: + window = parse(KFW).workspace().containers[0][0] + assert (window.id, window.exe, window.window_class) == (1, "foot", "foot") + assert window.rect == Rect(0, 0, 960, 1080) + + +def test_the_layout_is_its_name() -> None: + snap = parse(KFDE) + assert snap.workspace().layout == "BSP" + assert snap.workspace().latest_layout == [Rect(0, 0, 960, 1080), Rect(960, 0, 960, 1080)] + + +def test_what_only_one_port_has_is_kept_aside() -> None: + assert parse(KFW).extra == {"has_pending_raise_op": False} + assert parse(KFDE).extra == {} + + +def test_a_monocle_container_lists_its_windows() -> None: + state = scene(kfde_window, {}, {}) + workspace = state["monitors"]["elements"][0]["workspaces"]["elements"][0] + workspace["monocle_container"] = { + "id": "m", + "locked": False, + "windows": ring(kfde_window(1, "win1", rect(0, 0, 1920, 1040))), + } + assert [w.title for w in parse(state).workspace().monocle or []] == ["win1"]