diff --git a/nix/tests/vm/lib/komorebi_vm/core/checks.py b/nix/tests/vm/lib/komorebi_vm/core/checks.py index 9e48b145..627460a4 100644 --- a/nix/tests/vm/lib/komorebi_vm/core/checks.py +++ b/nix/tests/vm/lib/komorebi_vm/core/checks.py @@ -15,6 +15,7 @@ class Checks: self.passed = 0 self.failed = 0 self.failures: list[str] = [] + self.skipped: list[str] = [] def ok(self, description: str) -> None: """Records a check that passed.""" @@ -27,6 +28,11 @@ class Checks: self.failures.append(description) print(f" FAIL {description}") + def skip(self, description: str, reason: str) -> None: + """Records a check that was not made, and why: the platform cannot do what it asks.""" + self.skipped.append(f"{description} ({reason})") + print(f" skip {description}: {reason}") + def check(self, description: str, condition: bool | Callable[[], bool]) -> bool: """Records `condition` (or what calling it returns) and returns it.""" holds = condition() if callable(condition) else condition @@ -43,5 +49,7 @@ class Checks: are all `nix build` shows, say which they were. """ print(f"passed: {self.passed} failed: {self.failed}") + if self.skipped: + print(f"skipped: {len(self.skipped)}") if self.failed: raise AssertionError(f"{self.failed} checks failed: {'; '.join(self.failures)}") diff --git a/nix/tests/vm/lib/komorebi_vm/core/platform.py b/nix/tests/vm/lib/komorebi_vm/core/platform.py index 25f3c34c..5a037907 100644 --- a/nix/tests/vm/lib/komorebi_vm/core/platform.py +++ b/nix/tests/vm/lib/komorebi_vm/core/platform.py @@ -97,6 +97,11 @@ class Platform(Protocol): """Runs `komorebic` with `args` and returns what it printed. Fails if it does.""" ... + def komorebic_status(self, *args: str) -> tuple[int, str]: + """Runs `komorebic` with `args` and returns its exit status and what it printed, whether + it succeeded or not.""" + ... + def state(self) -> Snapshot: """The daemon's state.""" ... @@ -118,6 +123,22 @@ class Platform(Protocol): """ ... + def displays(self) -> list[Rect]: + """The displays the operating system has, left to right: each one's rectangle in the + coordinates of the desktop. The daemon is not asked.""" + ... + + def add_display(self) -> None: + """Plugs in another display, to the right of the others, and returns when the operating + system has it. The daemon learns of it later, so a scenario waits for its state to follow. + A platform may give it another size than the others; `displays()` says which.""" + ... + + def remove_display(self) -> None: + """Unplugs the display that was plugged in last, and returns when the operating system no + longer has it.""" + ... + def close(self, client: Client) -> None: """Closes the window, as its close button would.""" ... diff --git a/nix/tests/vm/lib/komorebi_vm/core/scenarios/commands.py b/nix/tests/vm/lib/komorebi_vm/core/scenarios/commands.py new file mode 100644 index 00000000..d9a3087f --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/core/scenarios/commands.py @@ -0,0 +1,348 @@ +"""Every layout, and a sweep of komorebic's commands: none may break the daemon. + +After each command the same things have to be true: the daemon is alive, it answers `komorebic +state`, and it manages every window the operating system has. A command is also expected to be +understood (exit status 0). A command the port does not have (`error: unrecognized subcommand`) is +skipped, with its name, which is what the behaviour matrix of the two ports is made of. What each +command does is checked elsewhere; this says none of them breaks a running daemon. +""" + +from collections.abc import Sequence + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.platform import Client, Platform + +LAYOUTS: tuple[str, ...] = ( + "bsp", + "columns", + "rows", + "vertical-stack", + "horizontal-stack", + "ultrawide-vertical-stack", + "grid", + "right-main-vertical-stack", + "scrolling", +) + +# Every command the ports share that changes something, in an order that leaves the daemon with +# windows to act on. `{config}` is the path of a configuration file for `replace-configuration`. +SWEEP: tuple[str, ...] = ( + "focus left", + "focus right", + "focus up", + "focus down", + "move left", + "move right", + "move up", + "move down", + "cycle-focus next", + "cycle-focus previous", + "cycle-move next", + "cycle-move previous", + "stack left", + "cycle-stack next", + "cycle-stack previous", + "cycle-stack-index next", + "focus-stack-window 0", + "unstack", + "stack-all", + "unstack-all", + "resize-edge left increase", + "resize-edge right decrease", + "resize-edge up increase", + "resize-edge down decrease", + "resize-axis horizontal increase", + "resize-axis vertical decrease", + "resize-delta 50", + "resize-delta 100", + "promote", + "promote-swap", + "promote-focus", + "promote-window left", + "retile", + "flip-layout horizontal", + "flip-layout vertical", + "flip-layout horizontal-and-vertical", + "flip-layout horizontal-and-vertical", + "cycle-layout next", + "cycle-layout previous", + "layout-ratios --columns 0.6 0.4", + "change-layout columns", + "scrolling-layout-columns 2", + "change-layout bsp", + "preselect-direction left", + "cancel-preselect", + "toggle-monocle", + "toggle-monocle", + "toggle-maximize", + "toggle-maximize", + "toggle-float", + "toggle-float", + "toggle-lock", + "toggle-lock", + "toggle-tiling", + "toggle-tiling", + "toggle-pause", + "toggle-pause", + "toggle-workspace-layer", + "toggle-workspace-layer", + "toggle-window-container-behaviour", + "toggle-window-container-behaviour", + "toggle-float-override", + "toggle-float-override", + "toggle-workspace-window-container-behaviour", + "toggle-workspace-window-container-behaviour", + "toggle-workspace-float-override", + "toggle-workspace-float-override", + "ensure-named-workspaces 0 one two three", + "workspace-name 0 0 one", + "ensure-workspaces 0 3", + "workspace-tiling 0 0 disable", + "workspace-tiling 0 0 enable", + "named-workspace-tiling one disable", + "named-workspace-tiling one enable", + "focus-workspace 1", + "focus-workspace 0", + "focus-last-workspace", + "focus-last-workspace", + "focus-workspaces 1", + "focus-workspaces 0", + "cycle-workspace next", + "cycle-workspace previous", + "cycle-empty-workspace next", + "focus-workspace 0", + "focus-named-workspace two", + "focus-named-workspace one", + "send-to-workspace 1", + "focus-workspace 1", + "move-to-workspace 0", + "focus-workspace 0", + "cycle-send-to-workspace next", + "focus-workspace 1", + "cycle-move-to-workspace previous", + "focus-workspace 0", + "send-to-last-workspace", + "move-to-last-workspace", + "focus-workspace 0", + "new-workspace", + "close-workspace", + "focus-workspace 0", + "workspace-layout 0 0 columns", + "workspace-layout 0 0 bsp", + "named-workspace-layout one columns", + "named-workspace-layout one bsp", + "workspace-layout-rule 0 0 2 rows", + "workspace-layout-rule 0 0 3 columns", + "clear-workspace-layout-rules 0 0", + "named-workspace-layout-rule one 3 columns", + "clear-named-workspace-layout-rules one", + "workspace-layout 0 0 bsp", + "focus-monitor 1", + "focus-monitor 0", + "cycle-monitor next", + "cycle-monitor previous", + "focus-monitor-workspace 1 1", + "focus-monitor-workspace 0 0", + "focus-monitor-at-cursor", + "focus-monitor 0", + "send-to-named-workspace two", + "focus-named-workspace two", + "move-to-named-workspace one", + "focus-named-workspace one", + "send-to-monitor 1", + "focus-monitor 1", + "move-to-monitor 0", + "focus-monitor 0", + "cycle-send-to-monitor next", + "focus-monitor 1", + "cycle-move-to-monitor next", + "focus-monitor 0", + "send-to-monitor-workspace 1 1", + "focus-monitor-workspace 1 1", + "move-to-monitor-workspace 0 0", + "focus-monitor 0", + "focus-workspace 0", + "move-workspace-to-monitor 1", + "cycle-move-workspace-to-monitor next", + "swap-workspaces-with-monitor 1", + "swap-workspaces-with-monitor 1", + "global-work-area-offset 10 10 20 20", + "global-work-area-offset 0 0 0 0", + "monitor-work-area-offset 0 10 10 20 20", + "monitor-work-area-offset 0 0 0 0 0", + "workspace-work-area-offset 0 0 10 10 20 20", + "workspace-work-area-offset 0 0 0 0 0 0", + "toggle-window-based-work-area-offset", + "toggle-window-based-work-area-offset", + "focused-workspace-container-padding 20", + "focused-workspace-container-padding 10", + "focused-workspace-padding 20", + "focused-workspace-padding 10", + "adjust-container-padding increase 5", + "adjust-container-padding decrease 5", + "adjust-workspace-padding increase 5", + "adjust-workspace-padding decrease 5", + "container-padding 0 0 12", + "container-padding 0 0 10", + "workspace-padding 0 0 12", + "workspace-padding 0 0 10", + "named-workspace-container-padding one 12", + "named-workspace-container-padding one 10", + "named-workspace-padding one 12", + "named-workspace-padding one 10", + "cross-monitor-move-behaviour insert", + "cross-monitor-move-behaviour swap", + "toggle-cross-monitor-move-behaviour", + "toggle-cross-monitor-move-behaviour", + "monocle-focus-behaviour cycle", + "toggle-monocle-focus-behaviour", + "toggle-monocle-focus-behaviour", + "unmanaged-window-operation-behaviour op", + "unmanaged-window-operation-behaviour no-op", + "unmanaged-window-operation-behaviour op", + "display-index-preference 0 Virtual-0", + "mouse-follows-focus enable", + "mouse-follows-focus disable", + "toggle-mouse-follows-focus", + "toggle-mouse-follows-focus", + "focus-follows-mouse enable", + "focus-follows-mouse disable", + "toggle-focus-follows-mouse", + "toggle-focus-follows-mouse", + "transparency enable", + "transparency-alpha 150", + "toggle-transparency", + "toggle-transparency", + "transparency disable", + "border enable", + "border-width 8", + "border-offset 1", + "border-colour --window-kind single 10 20 30", + "border disable", + "animation enable", + "animation-duration 120", + "animation-fps 30", + "animation-style --style linear", + "animation disable", + "session-float-rule", + "session-float-rules", + "clear-session-float-rules", + "toggle-float", + "ignore-rule exe nonexistent", + "manage-rule exe nonexistent", + "initial-workspace-rule exe nonexistent 0 1", + "workspace-rule exe nonexistent 0 1", + "initial-named-workspace-rule exe nonexistent two", + "named-workspace-rule exe nonexistent two", + "enforce-workspace-rules", + "clear-workspace-rules 0 1", + "clear-named-workspace-rules two", + "clear-all-workspace-rules", + "manage", + "close", + "retile", + "replace-configuration {config}", + "eager-focus foot", +) + +# What komorebic only prints. +PRINTED: tuple[str, ...] = ( + "state", + "global-state", + "visible-windows", + "monitor-information", + "data-directory", + "configuration", + "generate-static-config", + "static-config-schema", + "application-specific-configuration-schema", + "notification-schema", + "socket-schema", + "session-float-rules", +) + + +NOT_A_COMMAND = "unrecognized subcommand" + + +def unhealthy(platform: Platform, clients: list[Client]) -> str | None: + """Why the daemon is not healthy, or `None`: it answers `state` and manages the windows the + operating system has.""" + status, _ = platform.komorebic_status("state") + if status != 0: + return "it does not answer `komorebic state`" + try: + managed = platform.state().managed() + except (AssertionError, ValueError, KeyError) as error: + return f"its state cannot be read ({error})" + present = sum(1 for c in clients if platform.os_window(c) is not None) + if managed != present: + return f"it manages {managed} windows and the operating system has {present}" + return None + + +def layouts(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Changes to every layout, and checks that the windows stay inside the work area and apart + from each other, and that the daemon stays healthy. The scrolling layout is a strip whose + columns can be past the edge, so its frames are not looked at.""" + area = platform.work_area() + for layout in LAYOUTS: + status, out = platform.komorebic_status("change-layout", layout) + if status != 0 and NOT_A_COMMAND in out: + checks.skip(f"change-layout {layout}", "the port has no such layout") + continue + problems = [] + if status != 0: + problems.append(f"exit {status}") + platform.wait_for(lambda: unhealthy(platform, clients) is None, timeout=10) + if (why := unhealthy(platform, clients)) is not None: + problems.append(why) + if layout != "scrolling": + frames = {c.title: w.frame for c in clients if (w := platform.os_window(c)) is not None} + problems += [ + f"{t} is outside the work area" for t, f in frames.items() if not f.inside(area, 2) + ] + titles = list(frames) + problems += [ + f"{a} and {b} overlap" + for i, a in enumerate(titles) + for b in titles[i + 1 :] + if frames[a].overlaps(frames[b]) + ] + checks.check(f"change-layout {layout}: " + ("; ".join(problems) or "ok"), not problems) + + +def sweep( + platform: Platform, + checks: Checks, + clients: list[Client], + config: str, + commands: Sequence[str] = SWEEP, +) -> None: + """Runs every command of `commands` (`SWEEP`), and checks that it is understood and leaves the + daemon healthy. `config` is the path, on the platform, of a file the daemon can be told to + load.""" + for line in commands: + words = line.format(config=config).split() + status, out = platform.komorebic_status(*words) + if status != 0 and NOT_A_COMMAND in out: + checks.skip(f"komorebic {line}", "the port has no such command") + continue + if status != 0: + checks.bad(f"komorebic {line}: exit {status}: {' '.join(out.splitlines()[:2])}") + continue + platform.wait_for(lambda: unhealthy(platform, clients) is None, timeout=5) + if (why := unhealthy(platform, clients)) is not None: + checks.bad(f"komorebic {line}: afterwards {why}") + continue + checks.ok(f"komorebic {line}") + + +def prints(platform: Platform, checks: Checks) -> None: + """Runs every command that only prints something, and checks that each exits 0.""" + for line in PRINTED: + status, out = platform.komorebic_status(*line.split()) + if status != 0 and NOT_A_COMMAND in out: + checks.skip(f"komorebic {line}", "the port has no such command") + continue + checks.check(f"komorebic {line}", status == 0) diff --git a/nix/tests/vm/lib/komorebi_vm/core/scenarios/hotplug.py b/nix/tests/vm/lib/komorebi_vm/core/scenarios/hotplug.py new file mode 100644 index 00000000..2b5a0c6a --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/core/scenarios/hotplug.py @@ -0,0 +1,104 @@ +"""A display that is unplugged takes its windows to the other, and one plugged in is a monitor.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.platform import Client, Platform + + +def _monitors(platform: Platform) -> int: + return len(platform.state().monitors) + + +def _in_one_of(platform: Platform, clients: list[Client], displays: list[Rect]) -> bool: + frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None] + return len(frames) == len(clients) and all( + any(f.inside(d, 1) for d in displays) for f in frames + ) + + +def _tiled_in(platform: Platform, clients: list[Client], area: Rect) -> bool: + frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None] + return ( + len(frames) == len(clients) + and all(f.inside(area, 1) for f in frames) + and not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]) + ) + + +def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Unplugs a display, plugs one in again, and sends a window to it. + + `clients` are windows the daemon manages, each in a container of its own, on any display. The + platform has one display or more; one is plugged in first if it has only one. + """ + if len(platform.displays()) < 2: + platform.add_display() + checks.check( + "the daemon has a monitor for each display", + platform.wait_for(lambda: _monitors(platform) == len(platform.displays()), timeout=30), + ) + managed = platform.state().managed() + + platform.remove_display() + first = platform.displays()[0] + checks.check( + "after a display is unplugged the daemon has one monitor fewer", + platform.wait_for(lambda: _monitors(platform) == len(platform.displays()), timeout=30), + ) + checks.check( + "... every window is on the displays that are left, tiled and clear of each other", + platform.wait_for( + lambda: ( + _in_one_of(platform, clients, platform.displays()) + and (len(platform.displays()) > 1 or _tiled_in(platform, clients, first)) + ), + timeout=30, + ), + ) + checks.check( + "... and the daemon still manages every window", + platform.wait_for(lambda: platform.state().managed() == managed, timeout=20), + ) + + platform.add_display() + checks.check( + "after a display is plugged in the daemon has a monitor for it again", + platform.wait_for(lambda: _monitors(platform) == len(platform.displays()), timeout=30), + ) + checks.check( + "... still manages every window, each where it can be seen", + platform.wait_for( + lambda: ( + platform.state().managed() == managed + and _in_one_of(platform, clients, platform.displays()) + ), + timeout=30, + ), + ) + + # the focused window goes to the other monitor + displays = platform.displays() + focused = next( + (c for c in clients if (w := platform.os_window(c)) is not None and w.focused), None + ) + checks.check("a window has the focus", focused is not None) + if focused is None: + return + window = platform.os_window(focused) + assert window is not None + here = next((i for i, d in enumerate(displays) if window.frame.inside(d, 1)), None) + checks.check("it is on one of the displays", here is not None) + if here is None: + return + there = 1 if here == 0 else 0 + platform.komorebic("move-to-monitor", str(there)) + checks.check( + "after move-to-monitor it is on the other display", + platform.wait_for( + lambda: ( + (w := platform.os_window(focused)) is not None + and w.frame.inside(displays[there], 1) + ), + timeout=30, + ), + ) diff --git a/nix/tests/vm/lib/komorebi_vm/core/scenarios/rules.py b/nix/tests/vm/lib/komorebi_vm/core/scenarios/rules.py new file mode 100644 index 00000000..b6aa06c7 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/core/scenarios/rules.py @@ -0,0 +1,76 @@ +"""Rules that match a window by its title decide where it goes, or that it is left alone.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.platform import Platform + + +def _on(platform: Platform, title: str) -> int | None: + return platform.state().workspace_of(title) + + +def run(platform: Platform, checks: Checks) -> None: + """Gives the daemon three rules, opens a window that each matches, and checks where it went. + + An initial rule sends a window when it opens, so that moving it back leaves it there. A rule + that is not initial sends it again whenever the rules are enforced, and an ignore rule leaves + it alone. The daemon must be running, on the first workspace, which is the one in view, with + no window. + """ + + platform.komorebic("ensure-workspaces", "0", "3") + platform.komorebic("initial-workspace-rule", "title", "sent-once", "0", "1") + platform.komorebic("workspace-rule", "title", "sent-always", "0", "2") + platform.komorebic("ignore-rule", "title", "left-alone") + + once = platform.spawn("sent-once") + checks.check( + "a window an initial rule matches goes to the workspace the rule names", + platform.wait_for(lambda: _on(platform, "sent-once") == 1, timeout=20), + ) + checks.check( + "... where it is put away while another workspace is in view", + platform.wait_for(lambda: platform.hidden(once)), + ) + platform.komorebic("focus-workspace", "1") + checks.check( + "... and in view when its workspace is", + platform.wait_for(lambda: not platform.hidden(once)), + ) + platform.komorebic("move-to-workspace", "0") + checks.check( + "moved back to the first workspace, it is there", + platform.wait_for(lambda: _on(platform, "sent-once") == 0, timeout=20), + ) + # an initial rule is for the window that opens; `enforce-workspace-rules` applies it again + # on purpose, so what is checked is that the daemon does not send the window back on its own + checks.check( + "... and an initial rule does not send it there again on its own", + not platform.wait_for(lambda: _on(platform, "sent-once") != 0, timeout=3), + ) + + always = platform.spawn("sent-always") + checks.check( + "a window a rule that is not initial matches goes to its workspace too", + platform.wait_for(lambda: _on(platform, "sent-always") == 2, timeout=20), + ) + platform.komorebic("focus-workspace", "2") + platform.komorebic("move-to-workspace", "0") + platform.wait_for(lambda: _on(platform, "sent-always") == 0, timeout=20) + platform.komorebic("enforce-workspace-rules") + checks.check( + "... and when the rules are enforced it is sent back", + platform.wait_for(lambda: _on(platform, "sent-always") == 2, timeout=20), + ) + + managed = platform.state().managed() + ignored = platform.spawn("left-alone") + checks.check( + "a window an ignore rule matches is not managed", + platform.wait_for(lambda: platform.os_window(ignored) is not None) + and platform.wait_for(lambda: platform.state().managed() == managed) + and _on(platform, "left-alone") is None, + ) + + platform.komorebic("clear-all-workspace-rules") + for client in (once, always, ignored): + platform.close(client) diff --git a/nix/tests/vm/lib/komorebi_vm/core/snapshot.py b/nix/tests/vm/lib/komorebi_vm/core/snapshot.py index ef5d2a7f..0c104445 100644 --- a/nix/tests/vm/lib/komorebi_vm/core/snapshot.py +++ b/nix/tests/vm/lib/komorebi_vm/core/snapshot.py @@ -85,6 +85,13 @@ class Snapshot: m = self.monitors[monitor] return m.workspaces[m.focused_workspace if workspace is None else workspace] + def workspace_of(self, title: str, monitor: int = 0) -> int | None: + """The place of the workspace of a monitor that has a window with this title, or `None`.""" + for i, workspace in enumerate(self.monitors[monitor].workspaces): + if any(w.title == title for w in workspace.windows()): + return i + return None + def containers(self, workspace: int | None = None, 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] diff --git a/nix/tests/vm/lib/komorebi_vm/kde_platform.py b/nix/tests/vm/lib/komorebi_vm/kde_platform.py index 9bdaac84..8b2f467d 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde_platform.py +++ b/nix/tests/vm/lib/komorebi_vm/kde_platform.py @@ -1,6 +1,8 @@ """KDE as a [`Platform`](komorebi_vm.core.platform.Platform): a `Kde` session, seen through the neutral vocabulary.""" +import shlex + from PIL import Image from komorebi_vm.core import snapshot @@ -51,6 +53,9 @@ class KdePlatform: def komorebic(self, *args: str) -> str: return self.kde.komorebic(*args) + def komorebic_status(self, *args: str) -> tuple[int, str]: + return self.kde.run(shlex.join(["komorebic", *args])) + def state(self) -> Snapshot: return snapshot.parse(self.kde.state()) @@ -80,6 +85,28 @@ class KdePlatform: return True return desk != 0 and desk != self.kde.shown() + def displays(self) -> list[Rect]: + """The enabled outputs, which this session gives the size it was started with, side by side + from the left (at the scale of 1 that a scenario leaves them at).""" + width, height = self.size + return [Rect(i * width, 0, width, height) for i in range(len(self.kde.outputs.names()))] + + def add_display(self) -> None: + """Enables an output that was disabled, which is as near to a plug as KWin gets.""" + disabled = self.kde.outputs.names(enabled=False) + if not disabled: + raise AssertionError("every output is plugged in") + self.kde.outputs.enable(disabled[0]) + self.kde.wait_for(lambda: self.kde.outputs() == len(self.kde.outputs.names()), timeout=20) + + def remove_display(self) -> None: + """Disables the last of the enabled outputs, which is KWin's way to unplug one.""" + names = self.kde.outputs.names() + if len(names) < 2: + raise AssertionError("there is only one output to remove") + self.kde.outputs.disable(names[-1]) + self.kde.wait_for(lambda: len(self.kde.outputs.names()) == len(names) - 1, timeout=20) + def close(self, client: Client) -> None: self.kde.close(self.kde.wid(client.title)) diff --git a/nix/tests/vm/lib/tests/fake_platform.py b/nix/tests/vm/lib/tests/fake_platform.py index b858636f..8a6c4e5f 100644 --- a/nix/tests/vm/lib/tests/fake_platform.py +++ b/nix/tests/vm/lib/tests/fake_platform.py @@ -11,6 +11,7 @@ from PIL import Image from komorebi_vm.core.geometry import Rect from komorebi_vm.core.platform import Client, OsWindow +from komorebi_vm.core.scenarios.commands import PRINTED from komorebi_vm.core.snapshot import Snapshot, parse TILES = [Rect(0, 0, 640, 1080), Rect(640, 0, 640, 1080), Rect(1280, 0, 640, 1080)] @@ -52,12 +53,19 @@ class FakePlatform: self.tiles = list(TILES) self.has_pointer = pointer self.follows_pointer = follows_pointer - self.spaces: list[list[list[str]]] = [[], []] + self.spaces: list[list[list[str]]] = [[], [], []] """The two workspaces: for each, the stack of each container, in the order of the tiles, and the first window of a stack is the one in view.""" - self.focuses = [0, 0] + self.focuses = [0, 0, 0] self.current = 0 self.monocle: str | None = None + self.initial_rules: dict[str, int] = {} + self.rules: dict[str, int] = {} + self.ignored: set[str] = set() + self.unmanaged: list[str] = [] + self.display_count = 2 + self.display_of: dict[str, int] = {} + self.forgets_displays = False self.moves = moves self.focus_follows_move = focus_follows_move @@ -104,7 +112,14 @@ class FakePlatform: return [stack[0] for stack in self.containers] def spawn(self, title: str) -> Client: - self.containers.append([title]) + if title in self.ignored: + self.unmanaged.append(title) + elif title in self.initial_rules: + self.spaces[self.initial_rules.pop(title)].append([title]) + elif title in self.rules: + self.spaces[self.rules[title]].append([title]) + else: + self.containers.append([title]) return Client(title) def _find(self, title: str) -> tuple[int, int]: @@ -114,7 +129,22 @@ class FakePlatform: return s, i raise KeyError(title) + def displays(self) -> list[Rect]: + return [Rect(i * 1920, 0, 1920, 1080) for i in range(self.display_count)] + + def add_display(self) -> None: + self.display_count += 1 + + def remove_display(self) -> None: + self.display_count -= 1 + for title, display in self.display_of.items(): + if display >= self.display_count: + self.display_of[title] = 0 + def close(self, client: Client) -> None: + if client.title in self.unmanaged: + self.unmanaged.remove(client.title) + return s, i = self._find(client.title) stack = self.spaces[s][i] stack.remove(client.title) @@ -137,6 +167,8 @@ class FakePlatform: return self._find(title)[1] def hidden(self, client: Client) -> bool: + if client.title in self.unmanaged: + return False s, i = self._find(client.title) away = self.monocle is not None and client.title != self.monocle return s != self.current or self.spaces[s][i][0] != client.title or away @@ -153,6 +185,8 @@ class FakePlatform: return Image.new("RGB", (4, 4)) def os_window(self, client: Client) -> OsWindow | None: + if client.title in self.unmanaged: + return OsWindow(client.title, Rect(100, 100, 400, 300), focused=False) try: s, i = self._find(client.title) except KeyError: @@ -162,7 +196,18 @@ class FakePlatform: focused = ( s == self.current and i == self.focuses[s] and self.spaces[s][i][0] == client.title ) - return OsWindow(client.title, self.tiles[i], focused=focused) + tile = self.tiles[i] + shift = 1920 * self.display_of.get(client.title, 0) + return OsWindow(client.title, Rect(tile.x + shift, tile.y, tile.w, tile.h), focused=focused) + + def komorebic_status(self, *args: str) -> tuple[int, str]: + """The fake's answer as a real `komorebic` gives it: exit 0, or 2 for what it lacks.""" + if args[:1] == ("state",) or " ".join(args) in PRINTED: + return 0, "{}" + try: + return 0, self.komorebic(*args) + except AssertionError: + return 2, f"error: unrecognized subcommand '{args[0]}'" def komorebic(self, *args: str) -> str: n = len(self.containers) @@ -194,9 +239,37 @@ class FakePlatform: self.containers.pop(self.focus) self.focus = max(0, min(self.focus, len(self.containers) - 1)) self.spaces[int(number)].append([window]) + case ("change-layout", _): + pass + case ("move-to-monitor", number): + if int(number) < self.display_count: + self.display_of[self.containers[self.focus][0]] = int(number) case ("toggle-monocle",): top = self.containers[self.focus][0] self.monocle = None if self.monocle else top + case ("ensure-workspaces", _, _) | ("clear-all-workspace-rules",): + if args[0] == "clear-all-workspace-rules": + self.rules.clear() + self.initial_rules.clear() + case ("initial-workspace-rule", "title", title, _, number): + self.initial_rules[title] = int(number) + case ("workspace-rule", "title", title, _, number): + self.rules[title] = int(number) + case ("ignore-rule", "title", title): + self.ignored.add(title) + case ("move-to-workspace", number): + self.komorebic("send-to-workspace", number) + self.current = int(number) + case ("enforce-workspace-rules",): + for title, number in self.rules.items(): + for s, containers in enumerate(self.spaces): + for stack in containers: + if title in stack and s != number: + stack.remove(title) + if not stack: + containers.remove(stack) + self.spaces[number].append([title]) + break case ("focus-workspace", number): self.current = int(number) case ("unstack",): @@ -268,4 +341,12 @@ class FakePlatform: "focused": self.current, }, } - return parse({"monitors": {"elements": [monitor], "focused": 0}}) + extra = [ + { + "id": n + 1, + "size": rect(Rect(n * 1920, 0, 1920, 1080)), + "workspaces": {"elements": [workspace([], 0, False)], "focused": 0}, + } + for n in range(1, 1 if self.forgets_displays else self.display_count) + ] + return parse({"monitors": {"elements": [monitor, *extra], "focused": 0}}) diff --git a/nix/tests/vm/lib/tests/test_focus_moving.py b/nix/tests/vm/lib/tests/test_focus_moving.py index cf6d43af..b6f3fc48 100644 --- a/nix/tests/vm/lib/tests/test_focus_moving.py +++ b/nix/tests/vm/lib/tests/test_focus_moving.py @@ -3,10 +3,13 @@ from komorebi_vm.core.checks import Checks from komorebi_vm.core.scenarios import ( closing, + commands, focus, + hotplug, monocle, moving, resize, + rules, stacks, tiling, workspaces, @@ -104,3 +107,98 @@ def test_a_daemon_that_is_right_passes_closing() -> None: closing.run(platform, checks, clients, clients[-1]) assert checks.failed == 0, checks.failures assert checks.passed > 4 + + +def test_a_command_the_port_lacks_is_skipped_by_name() -> None: + platform = FakePlatform() + checks = Checks() + clients = opened(platform, checks) + commands.layouts(platform, checks, clients) + assert checks.failed == 0, checks.failures + assert checks.skipped == [] + + commands.sweep( + platform, checks, clients, config="unused", commands=("focus right", "no-such-command") + ) + assert checks.failed == 0, checks.failures + assert [s.split(" (")[0] for s in checks.skipped] == ["komorebic no-such-command"] + + +def test_a_command_that_breaks_the_daemon_is_a_failure() -> None: + class Breaks(FakePlatform): + """After `cycle-focus next` the daemon forgets a window the operating system still has.""" + + broken = False + + def komorebic(self, *args: str) -> str: + self.broken = self.broken or args == ("cycle-focus", "next") + return super().komorebic(*args) + + def state(self): # noqa: ANN201 + if not self.broken: + return super().state() + forgotten = self.spaces[0].pop() + try: + return super().state() + finally: + self.spaces[0].append(forgotten) + + platform = Breaks() + checks = Checks() + clients = opened(platform, checks) + commands.sweep(platform, checks, clients, config="unused", commands=("cycle-focus next",)) + assert any("afterwards it manages" in f for f in checks.failures) + + +def test_the_commands_that_only_print_are_checked_for_their_exit() -> None: + platform = FakePlatform() + checks = Checks() + commands.prints(platform, checks) + assert checks.failed == 0 + assert checks.skipped == [] + + +def test_a_daemon_that_follows_its_rules_passes_rules() -> None: + platform = FakePlatform() + checks = Checks() + rules.run(platform, checks) + assert checks.failed == 0, checks.failures + assert checks.passed > 7 + + +def test_a_daemon_that_forgets_an_ignore_rule_fails_rules() -> None: + class Forgets(FakePlatform): + def komorebic(self, *args: str) -> str: + return "" if args[:1] == ("ignore-rule",) else super().komorebic(*args) + + platform = Forgets() + checks = Checks() + rules.run(platform, checks) + assert any("ignore rule matches" in f for f in checks.failures) + + +def test_a_daemon_that_follows_the_displays_passes_hotplug() -> None: + platform = FakePlatform() + checks = Checks() + clients = opened(platform, checks) + hotplug.run(platform, checks, clients) + assert checks.failed == 0, checks.failures + assert checks.passed > 6 + + +def test_a_platform_with_one_display_gets_a_second_first() -> None: + platform = FakePlatform() + platform.display_count = 1 + checks = Checks() + clients = opened(platform, checks) + hotplug.run(platform, checks, clients) + assert checks.failed == 0, checks.failures + + +def test_a_daemon_that_does_not_see_the_displays_fails_hotplug() -> None: + platform = FakePlatform() + platform.forgets_displays = True + checks = Checks() + clients = opened(platform, checks) + hotplug.run(platform, checks, clients) + assert any("a monitor for each display" in f for f in checks.failures) diff --git a/nix/tests/vm/lib/tests/test_tiling.py b/nix/tests/vm/lib/tests/test_tiling.py index 4fa6fa8b..a5c0583b 100644 --- a/nix/tests/vm/lib/tests/test_tiling.py +++ b/nix/tests/vm/lib/tests/test_tiling.py @@ -38,6 +38,18 @@ class FakePlatform: def close(self, client: Client) -> None: pass + def displays(self) -> list[Rect]: + return [Rect(0, 0, 1920, 1080)] + + def add_display(self) -> None: + pass + + def remove_display(self) -> None: + pass + + def komorebic_status(self, *args: str) -> tuple[int, str]: + return 0, "" + def has(self, feature: str) -> bool: return False diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 8c3e257d..6449a44e 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -11,6 +11,9 @@ import shlex from komorebi_vm import Checks, Kde, daemon +from komorebi_vm.core.platform import Client +from komorebi_vm.core.scenarios import commands +from komorebi_vm.kde_platform import KdePlatform W, H = 1920, 1080 OUTPUTS = 2 @@ -146,238 +149,20 @@ for layout in LAYOUTS: kde.komorebic("change-layout", "bsp") print("== 3. a sweep of commands (each must be understood, and leave komorebi healthy)") -SWEEP = """ -focus left -focus right -focus up -focus down -move left -move right -move up -move down -cycle-focus next -cycle-focus previous -cycle-move next -cycle-move previous -stack left -cycle-stack next -cycle-stack previous -cycle-stack-index next -focus-stack-window 0 -unstack -stack-all -unstack-all -resize-edge left increase -resize-edge right decrease -resize-edge up increase -resize-edge down decrease -resize-axis horizontal increase -resize-axis vertical decrease -resize-delta 50 -resize-delta 100 -promote -promote-swap -promote-focus -promote-window left -retile -flip-layout horizontal -flip-layout vertical -flip-layout horizontal-and-vertical -flip-layout horizontal-and-vertical -cycle-layout next -cycle-layout previous -layout-ratios --columns 0.6 0.4 -change-layout columns -scrolling-layout-columns 2 -change-layout bsp -preselect-direction left -cancel-preselect -toggle-monocle -toggle-monocle -toggle-maximize -toggle-maximize -toggle-float -toggle-float -toggle-lock -toggle-lock -toggle-tiling -toggle-tiling -toggle-pause -toggle-pause -toggle-workspace-layer -toggle-workspace-layer -toggle-window-container-behaviour -toggle-window-container-behaviour -toggle-float-override -toggle-float-override -toggle-workspace-window-container-behaviour -toggle-workspace-window-container-behaviour -toggle-workspace-float-override -toggle-workspace-float-override -ensure-named-workspaces 0 one two three -workspace-name 0 0 one -ensure-workspaces 0 3 -workspace-tiling 0 0 disable -workspace-tiling 0 0 enable -named-workspace-tiling one disable -named-workspace-tiling one enable -focus-workspace 1 -focus-workspace 0 -focus-last-workspace -focus-last-workspace -focus-workspaces 1 -focus-workspaces 0 -cycle-workspace next -cycle-workspace previous -cycle-empty-workspace next -focus-workspace 0 -focus-named-workspace two -focus-named-workspace one -send-to-workspace 1 -focus-workspace 1 -move-to-workspace 0 -focus-workspace 0 -cycle-send-to-workspace next -focus-workspace 1 -cycle-move-to-workspace previous -focus-workspace 0 -send-to-last-workspace -move-to-last-workspace -focus-workspace 0 -new-workspace -close-workspace -focus-workspace 0 -workspace-layout 0 0 columns -workspace-layout 0 0 bsp -named-workspace-layout one columns -named-workspace-layout one bsp -workspace-layout-rule 0 0 2 rows -workspace-layout-rule 0 0 3 columns -clear-workspace-layout-rules 0 0 -named-workspace-layout-rule one 3 columns -clear-named-workspace-layout-rules one -workspace-layout 0 0 bsp -focus-monitor 1 -focus-monitor 0 -cycle-monitor next -cycle-monitor previous -focus-monitor-workspace 1 1 -focus-monitor-workspace 0 0 -focus-monitor-at-cursor -focus-monitor 0 -send-to-named-workspace two -focus-named-workspace two -move-to-named-workspace one -focus-named-workspace one -send-to-monitor 1 -focus-monitor 1 -move-to-monitor 0 -focus-monitor 0 -cycle-send-to-monitor next -focus-monitor 1 -cycle-move-to-monitor next -focus-monitor 0 -send-to-monitor-workspace 1 1 -focus-monitor-workspace 1 1 -move-to-monitor-workspace 0 0 -focus-monitor 0 -focus-workspace 0 -move-workspace-to-monitor 1 -cycle-move-workspace-to-monitor next -swap-workspaces-with-monitor 1 -swap-workspaces-with-monitor 1 -global-work-area-offset 10 10 20 20 -global-work-area-offset 0 0 0 0 -monitor-work-area-offset 0 10 10 20 20 -monitor-work-area-offset 0 0 0 0 0 -workspace-work-area-offset 0 0 10 10 20 20 -workspace-work-area-offset 0 0 0 0 0 0 -toggle-window-based-work-area-offset -toggle-window-based-work-area-offset -focused-workspace-container-padding 20 -focused-workspace-container-padding 10 -focused-workspace-padding 20 -focused-workspace-padding 10 -adjust-container-padding increase 5 -adjust-container-padding decrease 5 -adjust-workspace-padding increase 5 -adjust-workspace-padding decrease 5 -container-padding 0 0 12 -container-padding 0 0 10 -workspace-padding 0 0 12 -workspace-padding 0 0 10 -named-workspace-container-padding one 12 -named-workspace-container-padding one 10 -named-workspace-padding one 12 -named-workspace-padding one 10 -cross-monitor-move-behaviour insert -cross-monitor-move-behaviour swap -toggle-cross-monitor-move-behaviour -toggle-cross-monitor-move-behaviour -monocle-focus-behaviour cycle -toggle-monocle-focus-behaviour -toggle-monocle-focus-behaviour -unmanaged-window-operation-behaviour op -unmanaged-window-operation-behaviour no-op -unmanaged-window-operation-behaviour op -display-index-preference 0 Virtual-0 -mouse-follows-focus enable -mouse-follows-focus disable -toggle-mouse-follows-focus -toggle-mouse-follows-focus -focus-follows-mouse enable -focus-follows-mouse disable -toggle-focus-follows-mouse -toggle-focus-follows-mouse -transparency enable -transparency-alpha 150 -toggle-transparency -toggle-transparency -transparency disable -border enable -border-width 8 -border-offset 1 -border-colour --window-kind single 10 20 30 -border disable -animation enable -animation-duration 120 -animation-fps 30 -animation-style --style linear -animation disable -session-float-rule -session-float-rules -clear-session-float-rules -toggle-float -ignore-rule exe nonexistent -manage-rule exe nonexistent -initial-workspace-rule exe nonexistent 0 1 -workspace-rule exe nonexistent 0 1 -initial-named-workspace-rule exe nonexistent two -named-workspace-rule exe nonexistent two -enforce-workspace-rules -clear-workspace-rules 0 1 -clear-named-workspace-rules two -clear-all-workspace-rules -manage -close -retile -replace-configuration /tmp/e2e-config.json -eager-focus foot -""" +platform = KdePlatform(kde, (W * OUTPUTS, H)) +clients = [Client(f"win{n}") for n in range(1, 6)] +# the same layouts and the same commands run against kfw: komorebi_vm.core.scenarios.commands has the +# list, and a command a port lacks is skipped there with its name +print(" the layouts, through the neutral platform") +commands.layouts(platform, checks, clients) +kde.komorebic("change-layout", "bsp") +CONFIG = "/tmp/e2e-config.json" kde.sh( "printf %s " + shlex.quote('{ "monitors": [ { "workspaces": [ { "name": "again", "layout": "BSP" } ] } ] }') - + " > /tmp/e2e-config.json" + + f" > {CONFIG}" ) -for line in SWEEP.strip().splitlines(): - status, out = kde.run(shlex.join(["komorebic", *line.split()])) - if status != 0: - checks.bad(f"komorebic {line}: exit {status}: {' '.join(out.splitlines()[:2])}") - continue - if not kde.wait_for(lambda: healthy() == 0, timeout=5): - checks.bad(f"komorebic {line}: komorebi is not healthy afterwards ({healthy()})") - continue - checks.ok(f"komorebic {line}") +commands.sweep(platform, checks, clients, CONFIG) first_workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] checks.check( @@ -458,21 +243,7 @@ checks.check( ) print("== 4. what komorebic only prints") -for args in [ - "state", - "global-state", - "visible-windows", - "monitor-information", - "data-directory", - "configuration", - "generate-static-config", - "static-config-schema", - "application-specific-configuration-schema", - "notification-schema", - "socket-schema", - "session-float-rules", -]: - checks.check(f"komorebic {args}", kde.run(f"komorebic {args}")[0] == 0) +commands.prints(platform, checks) for query in [ "focused-monitor-index", "focused-workspace-index", diff --git a/nix/tests/vm/suites/core-e2e/test.py b/nix/tests/vm/suites/core-e2e/test.py index bffd8029..8be1377d 100644 --- a/nix/tests/vm/suites/core-e2e/test.py +++ b/nix/tests/vm/suites/core-e2e/test.py @@ -19,6 +19,7 @@ from komorebi_vm.core.scenarios import ( focus, monocle, moving, + rules, stacks, tiling, workspaces, @@ -333,7 +334,11 @@ checks.check( kde.wait_for(lambda: len(parked()) == 1), ) kde.komorebic("stop") -checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running())) +exited = kde.wait_for(lambda: not kde.komorebi_running()) +if not exited: + print(kde.systemctl("status", "komorebi@main.service", "--no-pager", "-l")) + print("\n".join(daemon_log().splitlines()[-15:])) +checks.check("the daemon exited", exited) checks.check( "the parking desktop is gone", kde.wait_for(lambda: PARK not in kde.desktop_names()) ) @@ -444,6 +449,16 @@ workspaces.run(platform, checks, neutral) # the third window is on workspace 1 now: the first is closed, and the second takes its room closing.run(platform, checks, neutral, Client("neutral1")) +# the rules start from a workspace with no window: close what is left, wherever it is +for title in ("neutral2", "neutral3"): + platform.close(Client(title)) +checks.check("no window is left", kde.wait_for(lambda: kde.managed_all() == 0, timeout=20)) +platform.komorebic("focus-workspace", "0") +rules.run(platform, checks) +# a window for the stop to leave behind +platform.spawn("afterwards") +checks.check("it is managed", kde.wait_for(lambda: kde.managed_all() == 1, timeout=20)) + print("== 13. komorebic stop") kde.komorebic("stop") checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running())) @@ -454,7 +469,7 @@ checks.check( checks.check( "the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded()) ) -checks.check("the windows stay", kde.wid("neutral2") != "") +checks.check("the window stays", kde.wid("afterwards") != "") kde.stop() checks.finish() diff --git a/nix/tests/vm/suites/hotplug/test.py b/nix/tests/vm/suites/hotplug/test.py index d546c768..bef7b528 100644 --- a/nix/tests/vm/suites/hotplug/test.py +++ b/nix/tests/vm/suites/hotplug/test.py @@ -10,6 +10,9 @@ import time from komorebi_vm import Checks, Kde, Rect, daemon +from komorebi_vm.core.platform import Client +from komorebi_vm.core.scenarios import hotplug +from komorebi_vm.kde_platform import KdePlatform W, H = 1920, 1080 @@ -221,6 +224,11 @@ checks.check( show("after the second move") print(" " + "\n ".join(output_lines())) +print("== 7b. the same, through the neutral platform") +# the scenario of komorebi_vm.core.scenarios.hotplug is what runs on Windows too: it unplugs a +# display, plugs one in and sends a window to it, and asks the operating system where the windows are +hotplug.run(KdePlatform(kde, (W, H)), checks, [Client(t) for t in TITLES]) + print("== 8. nothing is left behind") checks.check( "komorebi is running and answers",