diff --git a/nix/tests/vm/lib/komorebi_vm/core/scenarios/monitors.py b/nix/tests/vm/lib/komorebi_vm/core/scenarios/monitors.py new file mode 100644 index 00000000..e4e73fa1 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/core/scenarios/monitors.py @@ -0,0 +1,390 @@ +"""The commands that take the focus, a window or a workspace to another monitor.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.platform import Client, Platform +from komorebi_vm.core.scenarios.support import os_focused +from komorebi_vm.core.snapshot import Snapshot + +TITLES = ["monitors-1", "monitors-2", "monitors-3", "monitors-4"] +SECOND = "monitors-second" +"""The name of the second workspace of the second monitor, which `send-to-named-workspace` takes a +window to.""" +SLACK = 2 + +Place = tuple[int, int] +"""A monitor and a workspace of it, by the daemon's indexes.""" + + +def _display(platform: Platform, state: Snapshot, monitor: int) -> Rect: + """The display the daemon's monitor is, found by where its top left corner is: the daemon may + number its monitors in another order than the displays are, left to right.""" + size = state.monitors[monitor].size + return min(platform.displays(), key=lambda d: abs(d.x - size.x) + abs(d.y - size.y)) + + +def _monitor_of(platform: Platform, state: Snapshot, display: int) -> int: + """The daemon's index of the monitor that is `displays()[display]`.""" + wanted = platform.displays()[display] + return min( + range(len(state.monitors)), + key=lambda m: ( + abs(state.monitors[m].size.x - wanted.x) + abs(state.monitors[m].size.y - wanted.y) + ), + ) + + +def _places(state: Snapshot, titles: list[str]) -> dict[str, Place]: + found = {} + for m, monitor in enumerate(state.monitors): + for w, workspace in enumerate(monitor.workspaces): + for window in workspace.windows(): + if window.title in titles: + found[window.title] = (m, w) + return found + + +def _view_problem(platform: Platform, titles: list[str]) -> str | None: + """What is wrong with the windows in view, from the operating system's side, or `None`. + + On each monitor, the windows of the workspace it shows are inside its display and not on each + other. The windows of the workspaces it does not show are not looked at: where a platform + keeps them is its own business. + """ + state = platform.state() + for m, monitor in enumerate(state.monitors): + area = _display(platform, state, m) + shown = monitor.workspaces[monitor.focused_workspace] + frames = {} + for window in shown.windows(): + if window.title not in titles: + continue + os_window = platform.os_window(Client(window.title)) + if os_window is None: + return f"{window.title} has no window" + if not os_window.frame.inside(area, SLACK): + return f"{window.title} is not inside the display of monitor {m}" + frames[window.title] = os_window.frame + names = list(frames) + for i, a in enumerate(names): + for b in names[i + 1 :]: + if frames[a].overlaps(frames[b]): + return f"{a} and {b} are on each other" + return None + + +def _focus_problem(platform: Platform, monitor: int, title: str | None) -> str | None: + """What is wrong with the focus, or `None` when the daemon and the operating system agree + that it is on `monitor`, on the window `title` (any window that monitor shows when `None`), + and that window is inside that monitor's display.""" + state = platform.state() + if state.focused_monitor != monitor: + return f"the daemon has the focus on monitor {state.focused_monitor}" + everyone = [ + Client(w.title) for m in state.monitors for ws in m.workspaces for w in ws.windows() + ] + seen = os_focused(platform, everyone) + wanted = title if title is not None else state.focused_title(monitor=monitor) + if not seen: + return "the operating system has no focused window" + if seen != wanted: + return f"the operating system has the focus on {seen} and the daemon on {wanted}" + window = platform.os_window(Client(seen)) + if window is None or not window.frame.inside(_display(platform, state, monitor), SLACK): + return f"{seen} has the focus but is not inside the display of monitor {monitor}" + return None + + +def _after( + platform: Platform, + checks: Checks, + command: str, + expected: dict[str, Place], + monitor: int, + title: str | None = None, + shown: dict[int, int] | None = None, +) -> None: + """Checks what `command` did: each of `expected` is on its monitor and workspace, in view + where its monitor shows it, and the focus is on `monitor`.""" + titles = list(expected) + checks.check( + f"after '{command}' the daemon has every window on the monitor and the workspace that " + "were asked for, and the others where they were", + platform.wait_for(lambda: _places(platform.state(), titles) == expected, timeout=20), + ) + for m, workspace in (shown or {}).items(): + checks.check( + f"after '{command}' monitor {m} shows its workspace {workspace}", + platform.wait_for( + lambda m=m, w=workspace: platform.state().monitors[m].focused_workspace == w + ), + ) + platform.wait_for(lambda: _view_problem(platform, titles) is None, timeout=20) + problem = _view_problem(platform, titles) + checks.check( + f"after '{command}' the windows in view are tiled inside their own display: " + f"{problem or 'ok'}", + problem is None, + ) + platform.wait_for(lambda: _focus_problem(platform, monitor, title) is None, timeout=20) + problem = _focus_problem(platform, monitor, title) + where = f"monitor {monitor}" + (f", on {title}" if title else "") + checks.check(f"after '{command}' the focus is on {where}: {problem or 'ok'}", problem is None) + + +def _focus(platform: Platform, title: str, monitor: int) -> None: + """Gives a window the focus, and waits until the daemon has it.""" + platform.activate(Client(title)) + platform.wait_for( + lambda: ( + platform.state().focused_monitor == monitor + and platform.state().focused_title(monitor=monitor) == title + ), + timeout=20, + ) + + +def _plug(platform: Platform) -> bool: + """Plugs in a display if there is only one, and returns whether it did. Waits until the daemon + has a monitor for each display.""" + plugged = len(platform.displays()) < 2 + if plugged: + platform.add_display() + platform.wait_for( + lambda: len(platform.state().monitors) == len(platform.displays()), timeout=30 + ) + return plugged + + +def run(platform: Platform, checks: Checks) -> None: + """Takes windows, workspaces and the focus from one monitor to the other with each command + that does, and checks where each window is, and where the focus is, in the daemon's state and + on the operating system's screen. + + The daemon must be running. It may manage other windows, which stay out of the checks. The + platform has one display or two; a second is plugged in when there is only one, and unplugged + at the end, so that the machine has the number of displays it had. Both may have any size: + each window is checked against the rectangle of the display its monitor is, not a constant. + + Four windows are opened and then closed. The monitors are named by the daemon's index of + them, `a` for the one on the first display and `b` for the other, and the commands count from + 0. + + What the daemon does (`WindowManager::move_container_to_monitor` and the arms of + `process_command`; the monitors and the workspaces count from 0), and so what is checked: + + - `send-to-monitor` takes the focused window to the target monitor's shown workspace, which + tiles it, and leaves the focus on the monitor it left; `move-to-monitor` does the same and + the focus follows. The `cycle-` forms take the monitor after (or before) the focused one, + counting round: with two monitors it is always the other. + - `send-to-monitor-workspace` and `move-to-monitor-workspace` do the same to a workspace of + the target monitor, which that monitor then shows (it is made if it was not there); the + named forms look the name up on every monitor. + - `focus-monitor` and `cycle-monitor` focus the monitor, and its focused window. + `focus-monitor-workspace` shows a workspace of a monitor and focuses it. + - `cycle-move-workspace-to-monitor` takes the focused workspace, with its windows, to the end + of the other monitor's workspaces, shows it there and focuses the monitor. The monitor it + left shows the workspace before it. It is done here to a workspace the monitor can spare: + done to the only workspace a monitor has, it leaves an empty one in its place. + + Surprising, and so not asserted: `focus-monitor` to a monitor with no window does not move the + focus of the operating system, since there is no window to give it to, while the daemon's + state has the monitor focused. For the same reason every window that is only sent here leaves + another on its monitor. On a machine with one monitor the cycle forms name that monitor, and + `cycle-send-to-monitor` puts the container at the back of its workspace. Nothing here unplugs + a display to look at either. `focus-monitor-at-cursor` needs the pointer: see `at_cursor`. + """ + baseline = platform.state().managed() + clients = [platform.spawn(title) for title in TITLES] + names = list(TITLES) + w1, w2, w3, w4 = names + checks.check( + "the daemon manages the four windows", + platform.wait_for(lambda: platform.state().managed() == baseline + 4, timeout=30), + ) + plugged = _plug(platform) + state = platform.state() + a, b = _monitor_of(platform, state, 0), _monitor_of(platform, state, 1) + + # the windows that are not on the first display's first workspace are taken there + platform.komorebic("focus-monitor", str(a)) + platform.komorebic("focus-workspace", "0") + for title in names: + place = _places(platform.state(), names).get(title) + if place is not None and place != (a, 0): + _focus(platform, title, place[0]) + platform.komorebic("move-to-monitor-workspace", str(a), "0") + platform.komorebic("ensure-named-workspaces", str(b), "monitors-first", SECOND) + expected: dict[str, Place] = {title: (a, 0) for title in names} + checks.check( + "the four windows are on the first display's first workspace", + platform.wait_for(lambda: _places(platform.state(), names) == expected, timeout=30), + ) + checks.check( + "... in view and apart, on the first display", + platform.wait_for(lambda: _view_problem(platform, names) is None, timeout=20), + ) + count_a = len(platform.state().monitors[a].workspaces) + count_b = len(platform.state().monitors[b].workspaces) + + # send-to-monitor: the window goes, the focus stays + _focus(platform, w4, a) + platform.komorebic("send-to-monitor", str(b)) + expected[w4] = (b, 0) + _after(platform, checks, f"send-to-monitor {b}", expected, a) + + # the focus goes to a monitor and to the window it has + platform.komorebic("focus-monitor", str(b)) + _after(platform, checks, f"focus-monitor {b}", expected, b, w4) + platform.komorebic("focus-monitor", str(a)) + _after(platform, checks, f"focus-monitor {a}", expected, a) + for way, monitor, title in ( + ("next", b, w4), + ("next", a, None), + ("previous", b, w4), + ("previous", a, None), + ): + platform.komorebic("cycle-monitor", way) + _after(platform, checks, f"cycle-monitor {way}", expected, monitor, title) + + # move-to-monitor and its cycle form: the window goes, the focus follows + _focus(platform, w3, a) + platform.komorebic("move-to-monitor", str(b)) + expected[w3] = (b, 0) + _after(platform, checks, f"move-to-monitor {b}", expected, b, w3) + platform.komorebic("cycle-move-to-monitor", "next") + expected[w3] = (a, 0) + _after(platform, checks, "cycle-move-to-monitor next", expected, a, w3) + + # cycle-send-to-monitor: it goes, the focus stays + platform.komorebic("cycle-send-to-monitor", "next") + expected[w3] = (b, 0) + _after(platform, checks, "cycle-send-to-monitor next", expected, a) + + # a workspace of the target monitor: sent, it is shown there and the focus stays + _focus(platform, w2, a) + platform.komorebic("send-to-monitor-workspace", str(b), "1") + expected[w2] = (b, 1) + _after(platform, checks, f"send-to-monitor-workspace {b} 1", expected, a, shown={b: 1}) + + # focus-monitor-workspace shows a workspace of a monitor, and focuses it + platform.komorebic("focus-monitor-workspace", str(b), "0") + _after(platform, checks, f"focus-monitor-workspace {b} 0", expected, b, shown={b: 0}) + platform.komorebic("focus-monitor-workspace", str(b), "1") + _after(platform, checks, f"focus-monitor-workspace {b} 1", expected, b, w2, shown={b: 1}) + platform.komorebic("focus-monitor-workspace", str(a), "0") + _after(platform, checks, f"focus-monitor-workspace {a} 0", expected, a, shown={a: 0}) + + # move-to-monitor-workspace: the window goes, the target monitor shows its workspace, and the + # focus follows + platform.komorebic("focus-monitor-workspace", str(b), "1") + platform.wait_for(lambda: _focus_problem(platform, b, w2) is None, timeout=20) + platform.komorebic("move-to-monitor-workspace", str(a), "0") + expected[w2] = (a, 0) + _after(platform, checks, f"move-to-monitor-workspace {a} 0", expected, a, w2, shown={a: 0}) + _focus(platform, w1, a) + platform.komorebic("move-to-monitor-workspace", str(b), "0") + expected[w1] = (b, 0) + _after(platform, checks, f"move-to-monitor-workspace {b} 0", expected, b, w1, shown={b: 0}) + + # sent back to the first monitor, the focus stays on the second + platform.komorebic("send-to-monitor", str(a)) + expected[w1] = (a, 0) + _after(platform, checks, f"send-to-monitor {a}", expected, b) + + # a workspace by its name, which is on the second monitor: sent, it is shown, the focus stays + _focus(platform, w1, a) + platform.komorebic("send-to-named-workspace", SECOND) + expected[w1] = (b, 1) + _after(platform, checks, f"send-to-named-workspace {SECOND}", expected, a, shown={b: 1}) + _focus(platform, w2, a) + platform.komorebic("move-to-named-workspace", SECOND) + expected[w2] = (b, 1) + _after(platform, checks, f"move-to-named-workspace {SECOND}", expected, b, w2, shown={b: 1}) + + # a workspace to the other monitor and back: the workspace with the two windows is the one + # the second monitor can spare. A workspace that is moved goes to the end of the monitor's + platform.komorebic("cycle-move-workspace-to-monitor", "next") + expected[w1] = expected[w2] = (a, count_a) + _after( + platform, checks, "cycle-move-workspace-to-monitor next", expected, a, shown={a: count_a} + ) + checks.check( + "... the monitor it left shows the first workspace it has", + platform.wait_for(lambda: platform.state().monitors[b].focused_workspace == 0), + ) + platform.komorebic("cycle-move-workspace-to-monitor", "next") + expected[w1] = expected[w2] = (b, count_b - 1) + _after( + platform, + checks, + "cycle-move-workspace-to-monitor next, back", + expected, + b, + shown={b: count_b - 1}, + ) + checks.check( + "... and the first monitor has the workspaces it had", + platform.wait_for(lambda: len(platform.state().monitors[a].workspaces) == count_a), + ) + + for client in clients: + platform.close(client) + platform.wait_for(lambda: platform.state().managed() == baseline, timeout=30) + platform.komorebic("focus-monitor", str(a)) + platform.komorebic("focus-workspace", "0") + if plugged: + platform.remove_display() + platform.wait_for( + lambda: len(platform.state().monitors) == len(platform.displays()), timeout=30 + ) + checks.check( + "the daemon has the windows it had before, and a monitor for each display", + platform.state().managed() == baseline + and len(platform.state().monitors) == len(platform.displays()), + ) + + +def at_cursor(platform: Platform, checks: Checks) -> None: + """`focus-monitor-at-cursor` focuses the monitor the pointer is on. + + Only where the platform has a pointer, which is in the pixels of the first display, so that + the pointer can be put on the first monitor and not on the second: the focus is put on the + second monitor with `focus-monitor`, the pointer on the first, and the command must bring the + focus back to it. + + The daemon's state has the focus on the monitor at once. Nothing is asserted of the focus of + the operating system, because the code does only `focus_monitor` for this message and not the + `update_focused_workspace` that the other focus commands do: the window that has the focus on + the screen stays the one it was until the next focus event (it differs from the daemon's + state in the meantime). + """ + if not platform.has("pointer"): + checks.skip("focus-monitor-at-cursor", "the platform has no pointer") + return + plugged = _plug(platform) + state = platform.state() + a, b = _monitor_of(platform, state, 0), _monitor_of(platform, state, 1) + first = platform.displays()[0] + + platform.komorebic("focus-monitor", str(b)) + checks.check( + "the focus is on the second monitor", + platform.wait_for(lambda: platform.state().focused_monitor == b), + ) + platform.pointer.move(first.x + first.w // 2, first.y + first.h // 2) + platform.komorebic("focus-monitor-at-cursor") + checks.check( + "'focus-monitor-at-cursor' with the pointer on the first display focuses the first monitor", + platform.wait_for(lambda: platform.state().focused_monitor == a), + ) + platform.komorebic("focus-monitor-at-cursor") + checks.check( + "... and again, with the focus there already, it stays", + platform.state().focused_monitor == a, + ) + if plugged: + platform.remove_display() + platform.wait_for( + lambda: len(platform.state().monitors) == len(platform.displays()), timeout=30 + ) diff --git a/nix/tests/vm/lib/tests/fake_desk.py b/nix/tests/vm/lib/tests/fake_desk.py new file mode 100644 index 00000000..7e58e51a --- /dev/null +++ b/nix/tests/vm/lib/tests/fake_desk.py @@ -0,0 +1,468 @@ +"""A desktop with monitors, and a daemon that follows the monitor and flip commands. + +Each monitor is a display of its own size, with workspaces of containers that the layout tiles in +the display: columns, rows or BSP, mirrored along the axes the workspace is flipped on. It does +what the real daemon does with `send-to-monitor` and its family, `focus-monitor`, the workspace +moves and `layout_flip`, so that the `monitors` and `layout_flip` scenarios can be run against a +daemon that is right, and against ones that are wrong in one way (`bug`). +""" + +from dataclasses import dataclass, field +from typing import Any + +from PIL import Image + +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.platform import Client, OsWindow +from komorebi_vm.core.snapshot import Snapshot, parse + +DISPLAYS = [Rect(0, 0, 1920, 1080), Rect(1920, 0, 1280, 720), Rect(3200, 0, 1920, 1080)] +"""The displays, left to right: the second is of another size.""" + +AXES = {"horizontal": "Horizontal", "vertical": "Vertical", "horizontal-and-vertical": "HV"} +BOTH = "HorizontalAndVertical" + + +@dataclass +class Space: + name: str | None = None + layout: str = "BSP" + flip: str | None = None + containers: list[str] = field(default_factory=list) + focus: int = 0 + + +@dataclass +class Mon: + spaces: list[Space] + shown: int = 0 + + +def _toggle(current: str | None, axis: str) -> str | None: + """What `flip_layout` makes of the flip a workspace has and the axis it is asked to flip on.""" + axis = BOTH if axis == "HV" else axis + if current is None: + return axis + if current == axis: + return None + if current == BOTH: + return "Vertical" if axis == "Horizontal" else "Horizontal" + return BOTH + + +def _bsp(i: int, n: int, area: Rect, h: bool, v: bool) -> list[Rect]: + if n == 1: + return [area] + if i % 2 == 0: + left = Rect(area.x, area.y, area.w // 2, area.h) + right = Rect(area.x + area.w // 2, area.y, area.w - area.w // 2, area.h) + first, rest = (right, left) if h else (left, right) + else: + top = Rect(area.x, area.y, area.w, area.h // 2) + bottom = Rect(area.x, area.y + area.h // 2, area.w, area.h - area.h // 2) + first, rest = (bottom, top) if v else (top, bottom) + return [first, *_bsp(i + 1, n - 1, rest, h, v)] + + +def tiles(layout: str, n: int, area: Rect, flip: str | None) -> list[Rect]: + """The tiles of a layout, for `n` containers in `area`, as the layouts of the daemon mirror + them: columns by a horizontal flip, rows by a vertical one, BSP by both.""" + h = flip in ("Horizontal", BOTH) + v = flip in ("Vertical", BOTH) + if n == 0: + return [] + if layout == "Columns": + cols = [Rect(area.x + i * area.w // n, area.y, area.w // n, area.h) for i in range(n)] + return cols[::-1] if h and n >= 2 else cols + if layout == "Rows": + rows = [Rect(area.x, area.y + i * area.h // n, area.w, area.h // n) for i in range(n)] + return rows[::-1] if v and n >= 2 else rows + return _bsp(0, n, area, h, v) + + +class FakeDeskPointer: + def __init__(self, desk: "FakeDesk") -> None: + self.desk = desk + + def move(self, x: int, y: int) -> None: + self.desk.cursor = (x, y) + + def down(self) -> None: + pass + + def up(self) -> None: + pass + + def drag( + self, start: tuple[int, int], end: tuple[int, int], steps: int = 25, ms: int = 30 + ) -> None: + pass + + +class FakeDesk: + """The `bug`s: `send_follows` (a send takes the focus along), `move_stays` (a move does not), + `send_ignores_workspace` (the workspace asked for is the one that is shown), `frame_stuck` (the + window is on the other monitor but its frame is not), `focus_ignored` (`focus-monitor` does + nothing), `cycle_stuck` (`cycle-monitor` does nothing), `workspace_stays` (the workspace move + does nothing), `cursor_ignored` (`focus-monitor-at-cursor` does nothing), `ignores_option` (the + config's `layout_flip` is not read), `option_on_all` (it is every workspace's), `swaps_axes` + (it is read as the other axis), `command_sets` (`flip-layout` sets the flip, not toggles it).""" + + tolerance = 24 + + def __init__(self, *, displays: int = 1, bug: str | None = None, pointer: bool = True) -> None: + self.bug = bug + self.has_pointer = pointer + self.display_count = displays + self.mons = [Mon([Space()]) for _ in range(displays)] + self.focus_mon = 0 + self.active: str | None = None + self.order: list[str] = [] + self.home: dict[str, int] = {} + self.rules: list[tuple[str, int]] = [] + self.cursor = (0, 0) + + # -- the machine + def has(self, feature: str) -> bool: + return feature == "pointer" and self.has_pointer + + @property + def pointer(self) -> FakeDeskPointer: + return FakeDeskPointer(self) + + def wait_for(self, predicate: Any, timeout: float = 10) -> bool: + return bool(predicate()) + + def displays(self) -> list[Rect]: + return DISPLAYS[: self.display_count] + + def work_area(self) -> Rect: + return DISPLAYS[0] + + def add_display(self) -> None: + self.display_count += 1 + self.mons.append(Mon([Space()])) + + def remove_display(self) -> None: + gone = self.mons.pop() + self.display_count -= 1 + self.mons[0].spaces[0].containers += [t for s in gone.spaces for t in s.containers] + self.focus_mon = min(self.focus_mon, len(self.mons) - 1) + self._refocus() + + def lock(self) -> None: + raise NotImplementedError + + def unlock(self) -> None: + raise NotImplementedError + + def move_window(self, client: Client, x: int, y: int) -> None: + raise NotImplementedError + + def minimize(self, client: Client) -> None: + raise NotImplementedError + + def rewrite_config(self, config: dict[str, Any]) -> None: + raise NotImplementedError + + def screenshot(self, name: str) -> Image.Image: + return Image.new("RGB", (4, 4)) + + def exe_id(self, program: str) -> str: + return program + + # -- the daemon + def start_komorebi(self) -> None: + self._reset([Space()]) + + def restart_with(self, config: dict[str, Any]) -> None: + configured = config["monitors"][0]["workspaces"] + flips = [w.get("layout_flip") for w in configured] + if self.bug == "ignores_option": + flips = [None] * len(configured) + elif self.bug == "option_on_all": + first = next((f for f in flips if f), None) + flips = [first] * len(configured) + elif self.bug == "swaps_axes": + swap = {"Horizontal": "Vertical", "Vertical": "Horizontal"} + flips = [swap.get(f, f) for f in flips] + spaces = [ + Space(name=w.get("name"), layout=w["layout"], flip=flip) + for w, flip in zip(configured, flips, strict=True) + ] + self._reset(spaces) + self.rules = [ + (rule["id"], index) + for index, w in enumerate(configured) + for rule in w.get("workspace_rules", []) + ] + for title in list(self.order): + target = self._by_rule(title) + if target is not None: + self._remove(title) + self.mons[0].spaces[target].containers.append(title) + self._refocus() + + def _reset(self, spaces: list[Space]) -> None: + """A new daemon knows nothing: every window is tiled on the first workspace of the first + monitor.""" + self.mons = [Mon(spaces)] + [Mon([Space()]) for _ in range(self.display_count - 1)] + self.mons[0].spaces[0].containers = list(self.order) + self.focus_mon = 0 + self.rules = [] + self._refocus() + + def _by_rule(self, title: str) -> int | None: + for prefix, index in self.rules: + if title.startswith(prefix): + return index + return None + + def _remove(self, title: str) -> None: + for mon in self.mons: + for space in mon.spaces: + if title in space.containers: + space.containers.remove(title) + space.focus = max(0, min(space.focus, len(space.containers) - 1)) + + def _find(self, title: str) -> tuple[int, int, int]: + for m, mon in enumerate(self.mons): + for w, space in enumerate(mon.spaces): + if title in space.containers: + return m, w, space.containers.index(title) + raise KeyError(title) + + def _shown(self, monitor: int) -> Space: + mon = self.mons[monitor] + return mon.spaces[mon.shown] + + def _refocus(self) -> None: + """The window of the focused container of the monitor that has the focus has it, if + there is one: the focus is not moved when it has no window to go to.""" + space = self._shown(self.focus_mon) + if space.containers: + self.active = space.containers[min(space.focus, len(space.containers) - 1)] + + def _show(self, monitor: int, workspace: int) -> None: + mon = self.mons[monitor] + while len(mon.spaces) <= workspace: + mon.spaces.append(Space()) + mon.shown = workspace + + def spawn(self, title: str, app_id: str | None = None, exe: str | None = None) -> Client: + self.order.append(title) + target = self._by_rule(title) + if target is not None: + self.mons[0].spaces[target].containers.append(title) + self.home[title] = 0 + else: + space = self._shown(self.focus_mon) + space.containers.append(title) + space.focus = len(space.containers) - 1 + self.home[title] = self.focus_mon + self.active = title + return Client(title) + + def close(self, client: Client) -> None: + self._remove(client.title) + self.order.remove(client.title) + if self.active == client.title: + self.active = None + self._refocus() + + def activate(self, client: Client) -> None: + m, w, i = self._find(client.title) + self.focus_mon = m + self.mons[m].shown = w + self.mons[m].spaces[w].focus = i + self.active = client.title + + def hidden(self, client: Client) -> bool: + m, w, _ = self._find(client.title) + return self.mons[m].shown != w + + def os_window(self, client: Client) -> OsWindow | None: + try: + m, w, i = self._find(client.title) + except KeyError: + return None + space = self.mons[m].spaces[w] + rect = tiles(space.layout, len(space.containers), DISPLAYS[m], space.flip)[i] + if self.bug == "frame_stuck": + dx = DISPLAYS[self.home[client.title]].x - DISPLAYS[m].x + rect = Rect(rect.x + dx, rect.y, rect.w, rect.h) + return OsWindow(client.title, rect, focused=self.active == client.title) + + # -- the commands + def komorebic_status(self, *args: str) -> tuple[int, str]: + try: + return 0, self.komorebic(*args) + except AssertionError: + return 2, f"error: unrecognized subcommand '{args[0]}'" + + def _move(self, target: int, workspace: int | None, follow: bool) -> None: + """`move_container_to_monitor`: the focused container leaves, and the monitor it goes to + shows the workspace it is put on.""" + if target >= len(self.mons): + return + if self.bug == "send_ignores_workspace": + workspace = None + source = self._shown(self.focus_mon) + if not source.containers: + return + title = source.containers.pop(min(source.focus, len(source.containers) - 1)) + source.focus = max(0, min(source.focus, len(source.containers) - 1)) + if workspace is not None: + self._show(target, workspace) + space = self._shown(target) + space.containers.append(title) + space.focus = len(space.containers) - 1 + if follow: + self.focus_mon = target + self._refocus() + + def _move_workspace(self, target: int) -> None: + if target >= len(self.mons) or self.bug == "workspace_stays": + return + mon = self.mons[self.focus_mon] + space = mon.spaces.pop(mon.shown) + mon.shown = max(0, mon.shown - 1) + if not mon.spaces: + mon.spaces.append(Space()) + there = self.mons[target] + there.spaces.append(space) + there.shown = len(there.spaces) - 1 + self.focus_mon = target + self._refocus() + + def _by_name(self, name: str) -> tuple[int, int] | None: + for m, mon in enumerate(self.mons): + for w, space in enumerate(mon.spaces): + if space.name == name: + return m, w + return None + + def _cycle(self, way: str) -> int: + step = 1 if way == "next" else -1 + return (self.focus_mon + step) % len(self.mons) + + def komorebic(self, *args: str) -> str: + sends_follow = self.bug == "send_follows" + moves_follow = self.bug != "move_stays" + match args: + case ("focus-monitor", number): + if int(number) < len(self.mons) and self.bug != "focus_ignored": + self.focus_mon = int(number) + self._refocus() + case ("cycle-monitor", way): + if self.bug != "cycle_stuck": + self.focus_mon = self._cycle(way) + self._refocus() + case ("focus-monitor-at-cursor",): + for m, display in enumerate(self.displays()): + x, y = self.cursor + inside = display.x <= x < display.x + display.w + inside = inside and display.y <= y < display.y + display.h + if inside and self.bug != "cursor_ignored": + self.focus_mon = m + case ("focus-monitor-workspace", monitor, workspace): + if (self.focus_mon, self.mons[self.focus_mon].shown) != ( + int(monitor), + int(workspace), + ): + self.focus_mon = int(monitor) + self._show(self.focus_mon, int(workspace)) + self._refocus() + case ("focus-workspace", workspace): + self._show(self.focus_mon, int(workspace)) + self._refocus() + case ("send-to-monitor", number): + self._move(int(number), None, sends_follow) + case ("move-to-monitor", number): + self._move(int(number), None, moves_follow) + case ("cycle-send-to-monitor", way): + self._move(self._cycle(way), None, sends_follow) + case ("cycle-move-to-monitor", way): + self._move(self._cycle(way), None, moves_follow) + case ("send-to-monitor-workspace", monitor, workspace): + self._move(int(monitor), int(workspace), sends_follow) + case ("move-to-monitor-workspace", monitor, workspace): + self._move(int(monitor), int(workspace), moves_follow) + case ("send-to-named-workspace", name): + if (found := self._by_name(name)) is not None: + self._move(found[0], found[1], sends_follow) + case ("move-to-named-workspace", name): + if (found := self._by_name(name)) is not None: + self._move(found[0], found[1], moves_follow) + case ("cycle-move-workspace-to-monitor", way): + self._move_workspace(self._cycle(way)) + case ("move-workspace-to-monitor", number): + self._move_workspace(int(number)) + case ("ensure-named-workspaces", monitor, *names): + for i, name in enumerate(names): + self._show_free(int(monitor), i).name = name + case ("ensure-workspaces", monitor, count): + self._show_free(int(monitor), int(count) - 1) + case ("flip-layout", axis): + space = self._shown(self.focus_mon) + if self.bug == "command_sets": + space.flip = BOTH if AXES[axis] == "HV" else AXES[axis] + else: + space.flip = _toggle(space.flip, AXES[axis]) + case _: + raise AssertionError(f"the fake does not know komorebic {args}") + return "" + + def _show_free(self, monitor: int, workspace: int) -> Space: + """The workspace of a monitor, made if it is not there. It is not shown.""" + mon = self.mons[monitor] + while len(mon.spaces) <= workspace: + mon.spaces.append(Space()) + return mon.spaces[workspace] + + def state(self) -> Snapshot: + def rect(r: Rect) -> dict[str, int]: + return {"left": r.x, "top": r.y, "right": r.w, "bottom": r.h} + + def window(title: str, r: Rect) -> dict[str, Any]: + return { + "id": hash(title) % 100000, + "rect": rect(r), + "details": {"title": title, "exe": "foot", "class": "", "path": ""}, + } + + def workspace(space: Space, area: Rect) -> dict[str, Any]: + laid = tiles(space.layout, len(space.containers), area, space.flip) + return { + "name": space.name, + "containers": { + "elements": [ + { + "id": str(i), + "locked": False, + "windows": {"elements": [window(t, laid[i])], "focused": 0}, + } + for i, t in enumerate(space.containers) + ], + "focused": space.focus, + }, + "monocle_container": None, + "maximized_window": None, + "floating_windows": {"elements": [], "focused": 0}, + "layout": {"Default": space.layout}, + "tile": True, + "latest_layout": [rect(r) for r in laid], + } + + monitors = [ + { + "id": m + 1, + "size": rect(DISPLAYS[m]), + "workspaces": { + "elements": [workspace(s, DISPLAYS[m]) for s in mon.spaces], + "focused": mon.shown, + }, + } + for m, mon in enumerate(self.mons) + ] + return parse({"monitors": {"elements": monitors, "focused": self.focus_mon}}) diff --git a/nix/tests/vm/lib/tests/test_monitors.py b/nix/tests/vm/lib/tests/test_monitors.py new file mode 100644 index 00000000..deb9d381 --- /dev/null +++ b/nix/tests/vm/lib/tests/test_monitors.py @@ -0,0 +1,78 @@ +"""The `monitors` scenario against a daemon that is right, and against ones that are wrong in one +way each.""" + +import pytest + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.scenarios import monitors +from tests.fake_desk import FakeDesk + + +def run_monitors(desk: FakeDesk) -> Checks: + checks = Checks() + monitors.run(desk, checks) + return checks + + +def test_a_daemon_that_is_right_passes_monitors() -> None: + desk = FakeDesk(displays=2) + checks = run_monitors(desk) + assert checks.failed == 0, checks.failures + assert checks.passed > 60 + assert desk.display_count == 2 + assert desk.order == [] + + +def test_a_platform_with_one_display_gets_a_second_and_gives_it_back() -> None: + desk = FakeDesk(displays=1) + checks = run_monitors(desk) + assert checks.failed == 0, checks.failures + assert desk.display_count == 1 + assert len(desk.state().monitors) == 1 + + +def test_other_windows_stay_where_they_are() -> None: + desk = FakeDesk(displays=1) + other = desk.spawn("someone else") + checks = run_monitors(desk) + assert checks.failed == 0, checks.failures + assert desk.state().workspace_of(other.title) == 0 + + +@pytest.mark.parametrize( + ("bug", "what"), + [ + ("send_follows", "send-to-monitor"), + ("move_stays", "move-to-monitor"), + ("send_ignores_workspace", "send-to-monitor-workspace"), + ("frame_stuck", "tiled inside their own display"), + ("focus_ignored", "focus-monitor"), + ("cycle_stuck", "cycle-monitor"), + ("workspace_stays", "cycle-move-workspace-to-monitor"), + ], +) +def test_a_daemon_that_is_wrong_fails_monitors(bug: str, what: str) -> None: + checks = run_monitors(FakeDesk(displays=2, bug=bug)) + assert any(what in f for f in checks.failures), (bug, checks.failures) + + +def test_a_daemon_that_ignores_the_cursor_fails_at_cursor() -> None: + checks = Checks() + monitors.at_cursor(FakeDesk(displays=2, bug="cursor_ignored"), checks) + assert any("focus-monitor-at-cursor" in f for f in checks.failures), checks.failures + + +def test_a_daemon_that_follows_the_cursor_passes_at_cursor() -> None: + desk = FakeDesk(displays=1) + checks = Checks() + monitors.at_cursor(desk, checks) + assert checks.failed == 0, checks.failures + assert checks.passed == 3 + assert desk.display_count == 1 + + +def test_without_a_pointer_at_cursor_is_skipped() -> None: + checks = Checks() + monitors.at_cursor(FakeDesk(displays=1, pointer=False), checks) + assert checks.passed == 0 and checks.failed == 0 + assert len(checks.skipped) == 1 diff --git a/nix/tests/vm/suites/core-e2e/test.py b/nix/tests/vm/suites/core-e2e/test.py index 58b0eacf..48c6a107 100644 --- a/nix/tests/vm/suites/core-e2e/test.py +++ b/nix/tests/vm/suites/core-e2e/test.py @@ -27,6 +27,7 @@ from komorebi_vm.core.scenarios import ( manage_rules, maximizing, minimizing, + monitors, monocle, moving, padding, @@ -58,8 +59,11 @@ 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) +# two outputs, of which the second is unplugged before the daemon starts: the scenarios see one +# display, as they always did, and `monitors` plugs the second in and out again +kde = Kde.headless(machine, "main", size=(W, H), outputs=2, scale=SCALE) platform = KdePlatform(kde, (W, H)) +platform.remove_display() platform.start_komorebi() recorder = Recorder(kde, RECORDER) @@ -170,6 +174,10 @@ checks.check( # workspace (fixed: it used to be lost, as a known failure on both ports; docs/dev/BEHAVIOUR.md). run_suite( checks, + # the commands that take the focus, a window or a workspace to the other monitor: it plugs the + # second output in, and out again + shared(monitors.run, platform, checks), + shared(monitors.at_cursor, platform, checks), shared(commands.unknown_monitor, platform, checks, [Client("afterwards")]), # what only KDE can tell about the daemon stopping, crashing, and KWin restarting platform_only("kde", kde_core.parking, platform, checks, []),