diff --git a/e2e/lib/komorebi_vm/__init__.py b/e2e/lib/komorebi_vm/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/e2e/lib/komorebi_vm/core/__init__.py b/e2e/lib/komorebi_vm/core/__init__.py new file mode 100644 index 00000000..3a09e014 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/__init__.py @@ -0,0 +1,5 @@ +"""What does not depend on the platform: the vocabulary and the helpers a scenario is made of. + +Nothing in this package may import from `komorebi_vm.kde` or know the name of a compositor, +so that it can move to the Windows port unchanged. +""" diff --git a/e2e/lib/komorebi_vm/core/checks.py b/e2e/lib/komorebi_vm/core/checks.py new file mode 100644 index 00000000..9e48b145 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/checks.py @@ -0,0 +1,47 @@ +"""Counted checks, so that one failure does not hide the ones after it.""" + +from collections.abc import Callable + + +class Checks: + """Collects the outcome of every check and fails once, at the end. + + A suite is a long scenario: a failure in the middle should not stop the + rest from running, because the rest says what else is broken. `finish` + prints the totals and raises if any check failed. + """ + + def __init__(self) -> None: + self.passed = 0 + self.failed = 0 + self.failures: list[str] = [] + + def ok(self, description: str) -> None: + """Records a check that passed.""" + self.passed += 1 + print(f" ok {description}") + + def bad(self, description: str) -> None: + """Records a check that failed.""" + self.failed += 1 + self.failures.append(description) + print(f" FAIL {description}") + + def check(self, description: str, condition: bool | Callable[[], bool]) -> bool: + """Records `condition` (or what calling it returns) and returns it.""" + holds = condition() if callable(condition) else condition + if holds: + self.ok(description) + else: + self.bad(description) + return holds + + def finish(self) -> None: + """Prints `passed: N failed: M` and raises if any check failed. + + The error names the checks that failed, so that the last lines of a failed run, which + are all `nix build` shows, say which they were. + """ + print(f"passed: {self.passed} failed: {self.failed}") + if self.failed: + raise AssertionError(f"{self.failed} checks failed: {'; '.join(self.failures)}") diff --git a/e2e/lib/komorebi_vm/core/geometry.py b/e2e/lib/komorebi_vm/core/geometry.py new file mode 100644 index 00000000..30805608 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/geometry.py @@ -0,0 +1,32 @@ +"""Rectangles, in the pixels of a screen.""" + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Rect: + """A window's position and size, in pixels.""" + + x: int + y: int + w: int + h: int + + def overlaps(self, other: "Rect") -> bool: + """Returns true if and only if the two rectangles share at least one pixel.""" + return ( + self.x < other.x + other.w + and other.x < self.x + self.w + and self.y < other.y + other.h + and other.y < self.y + self.h + ) + + def inside(self, area: "Rect", slack: int = 0) -> bool: + """Returns true if and only if every pixel of this rectangle is a pixel of `area`, give + or take `slack` pixels at each edge.""" + return ( + self.x >= area.x - slack + and self.y >= area.y - slack + and self.x + self.w <= area.x + area.w + slack + and self.y + self.h <= area.y + area.h + slack + ) diff --git a/e2e/lib/komorebi_vm/core/pixels.py b/e2e/lib/komorebi_vm/core/pixels.py new file mode 100644 index 00000000..047adf79 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/pixels.py @@ -0,0 +1,58 @@ +"""Reading what a screenshot shows: the color of a pixel, and the ring around a window.""" + +from PIL import Image + +from komorebi_vm.core.geometry import Rect + +Color = tuple[int, int, int] + + +def pixel(image: Image.Image, x: int, y: int) -> Color: + """The color of the pixel at `(x, y)`, as red, green and blue.""" + value = image.convert("RGB").getpixel((x, y)) + assert isinstance(value, tuple) + return (int(value[0]), int(value[1]), int(value[2])) + + +def near(a: Color, b: Color, tolerance: int = 12) -> bool: + """Returns true if and only if the two colors differ by at most `tolerance` on every channel. + + A screenshot is of a compositor that blends the shadow and the edge of a border into what is + behind it, so a color is never asked for exactly. + """ + return all(abs(x - y) <= tolerance for x, y in zip(a, b, strict=True)) + + +def leftmost(image: Image.Image, y: int, color: Color, tolerance: int = 12) -> int | None: + """Returns the `x` of the leftmost pixel of row `y` that is near `color`, or `None`. + + A window that moves across the screen has its left edge where this finds the first pixel of its + color, which is how a test sees how far along it is. + """ + for x in range(image.width): + if near(pixel(image, x, y), color, tolerance): + return x + return None + + +def ring(image: Image.Image, frame: Rect, color: Color, margin: int = 5) -> list[str]: + """Returns what is wrong with the ring around a window: a line for each side that has none. + + The ring is looked for `margin` pixels outside the middle of each of the four edges of + `frame`, which is the window with its title bar, as KWin reports it. A side where that pixel is + not near `color` is named, with the pixel it has. An empty list is a ring all round. + """ + middle_x = frame.x + frame.w // 2 + middle_y = frame.y + frame.h // 2 + sides = { + "above": (middle_x, frame.y - margin), + "below": (middle_x, frame.y + frame.h + margin), + "left": (frame.x - margin, middle_y), + "right": (frame.x + frame.w + margin, middle_y), + } + wrong = [] + for name, (x, y) in sides.items(): + found = pixel(image, x, y) + if not near(found, color): + wrong.append(f"{name}: ({x}, {y}) is {found}, not {color}") + return wrong diff --git a/e2e/lib/komorebi_vm/core/platform.py b/e2e/lib/komorebi_vm/core/platform.py new file mode 100644 index 00000000..134918fb --- /dev/null +++ b/e2e/lib/komorebi_vm/core/platform.py @@ -0,0 +1,99 @@ +"""What a scenario needs of a platform: the hands and the eyes, behind methods. + +A scenario drives the daemon and looks at the desktop only through a +[`Platform`](komorebi_vm.core.platform.Platform), so that the same scenario runs on KDE and on +Windows. A platform may implement a method on the host (QMP on QEMU) or in the guest (an agent); a +scenario cannot tell. + +Only what a scenario uses today is here. A method is added with the first scenario that needs it, +and takes the shape both platforms can give. +""" + +from dataclasses import dataclass +from typing import Protocol + +from PIL import Image + +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.snapshot import Snapshot + + +@dataclass(frozen=True) +class Client: + """A window a scenario opened. `title` is its identity: a scenario gives each its own.""" + + title: str + + +@dataclass(frozen=True) +class OsWindow: + """What the operating system says about a window, which is the oracle of a scenario. + + The daemon's own state is the thing under test and is never its own oracle. + """ + + title: str + frame: Rect + """The visible frame: the compositor's on KDE, the DWM's extended frame on Windows.""" + focused: bool + + +class Platform(Protocol): + """A machine with a desktop and a daemon to test.""" + + @property + def tolerance(self) -> int: + """How far a window's frame may be short of the one asked for, in pixels. + + A terminal sizes itself to whole cells; a test window has no granularity. + """ + ... + + def wait_for(self, predicate: "Predicate", timeout: float = 10) -> bool: + """Polls `predicate` until it holds or `timeout` seconds, scaled for this host, pass.""" + ... + + def start_komorebi(self) -> None: + """Starts the daemon from a clean state and waits until it answers.""" + ... + + def komorebic(self, *args: str) -> str: + """Runs `komorebic` with `args` and returns what it printed. Fails if it does.""" + ... + + def state(self) -> Snapshot: + """The daemon's state.""" + ... + + def spawn(self, title: str) -> Client: + """Opens a window with this title and waits until the platform has it.""" + ... + + def os_window(self, client: Client) -> OsWindow | None: + """What the operating system says about the window, or `None` if it has none.""" + ... + + def hidden(self, client: Client) -> bool: + """The window exists but is out of sight because the daemon put it away: the other windows + of a stack, the windows of another workspace, those behind a monocle. + + That is a window parked on a desktop of its own on KDE, and cloaked on Windows. A window + the user minimized is not hidden in this sense. + """ + ... + + def work_area(self) -> Rect: + """The area of the first display that windows may take.""" + ... + + def activate(self, client: Client) -> None: + """Gives the window the focus, as a click on it would.""" + ... + + def screenshot(self, name: str) -> Image.Image: + """The display as an image, kept under `name` with the other artifacts of the run.""" + ... + + +class Predicate(Protocol): + def __call__(self) -> bool: ... diff --git a/e2e/lib/komorebi_vm/core/scenarios/__init__.py b/e2e/lib/komorebi_vm/core/scenarios/__init__.py new file mode 100644 index 00000000..6bb8983a --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/__init__.py @@ -0,0 +1 @@ +"""Scenarios that run on every platform, written against `komorebi_vm.core.platform.Platform`.""" diff --git a/e2e/lib/komorebi_vm/core/scenarios/focus.py b/e2e/lib/komorebi_vm/core/scenarios/focus.py new file mode 100644 index 00000000..bef1b7d0 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/focus.py @@ -0,0 +1,50 @@ +"""The focus moves where komorebic says, and the operating system and the daemon agree on it.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.platform import Client, Platform +from komorebi_vm.core.scenarios.support import focus_agrees, os_focused, positions + + +def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Moves the focus among `clients`, which are tiled windows of the first workspace, each in a + container of its own, with `focus` and `cycle-focus`.""" + first = clients[0].title + before = positions(platform, clients) + + platform.activate(clients[0]) + checks.check( + f"{first} has the focus, and the daemon agrees", + platform.wait_for(lambda: focus_agrees(platform, clients, first)), + ) + + platform.komorebic("focus", "right") + checks.check( + "after 'focus right' the operating system has given the focus to another window", + platform.wait_for(lambda: os_focused(platform, clients) not in ("", first)), + ) + moved_to = os_focused(platform, clients) + checks.check( + "... and the daemon's state focuses the same one", + platform.wait_for(lambda: focus_agrees(platform, clients, moved_to)), + ) + + platform.komorebic("focus", "left") + checks.check( + "'focus left' gives the focus back", + platform.wait_for(lambda: focus_agrees(platform, clients, first)), + ) + + # the next container is whichever follows in the daemon's own order + order = [titles[0] for titles in platform.state().containers() if titles] + after = order[(order.index(first) + 1) % len(order)] + platform.komorebic("cycle-focus", "next") + checks.check( + f"'cycle-focus next' focuses {after}, the next container in the daemon's order", + platform.wait_for(lambda: focus_agrees(platform, clients, after)), + ) + platform.komorebic("cycle-focus", "previous") + checks.check( + "'cycle-focus previous' goes back", + platform.wait_for(lambda: focus_agrees(platform, clients, first)), + ) + checks.check("moving the focus moved no window", positions(platform, clients) == before) diff --git a/e2e/lib/komorebi_vm/core/scenarios/moving.py b/e2e/lib/komorebi_vm/core/scenarios/moving.py new file mode 100644 index 00000000..a2c1bd73 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/moving.py @@ -0,0 +1,45 @@ +"""Windows swap tiles on `move` and `cycle-move`, and the focus stays with the window.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.platform import Client, Platform +from komorebi_vm.core.scenarios.support import focus_agrees, positions + + +def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Moves the first of `clients`, which are tiled windows of the first workspace, each in a + container of its own, to the tile on its right and back.""" + first = clients[0].title + platform.activate(clients[0]) + platform.wait_for(lambda: focus_agrees(platform, clients, first)) + before = positions(platform, clients) + + def swapped_with_another() -> bool: + now = positions(platform, clients) + return any( + title != first + and now[first] == before[title] + and now[title] == before[first] + and now[first] != before[first] + for title in before + ) + + platform.komorebic("move", "right") + checks.check( + f"after 'move right' {first} and a neighbor have swapped tiles", + platform.wait_for(swapped_with_another, timeout=20), + ) + checks.check( + f"... and {first} keeps the focus", + platform.wait_for(lambda: focus_agrees(platform, clients, first)), + ) + others = {t: p for t, p in positions(platform, clients).items() if t != first} + checks.check( + "... and the other windows are on tiles of their own", + len(set(others.values()) | {positions(platform, clients)[first]}) == len(clients), + ) + + platform.komorebic("cycle-move", "previous") + checks.check( + "'cycle-move previous' puts every window back", + platform.wait_for(lambda: positions(platform, clients) == before, timeout=20), + ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/stacks.py b/e2e/lib/komorebi_vm/core/scenarios/stacks.py new file mode 100644 index 00000000..53e87690 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/stacks.py @@ -0,0 +1,83 @@ +"""A stack shows one window and puts the others away, and the window in view has the focus.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.platform import Client, Platform +from komorebi_vm.core.scenarios.support import focus_agrees, os_focused + + +def _sizes(platform: Platform) -> list[int]: + return sorted(len(titles) for titles in platform.state().containers()) + + +def _away(platform: Platform, clients: list[Client]) -> list[str]: + return [c.title for c in clients if platform.hidden(c)] + + +def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Stacks the focused one of `clients` onto its neighbor, cycles the stack and takes it apart. + + `clients` are three tiled windows of the first workspace, each in a container of its own, + and the last of them has the focus. + """ + last = clients[-1] + platform.activate(last) + platform.wait_for(lambda: focus_agrees(platform, clients, last.title)) + checks.check("there are three tiles", _sizes(platform) == [1, 1, 1]) + checks.check("nothing is put away yet", _away(platform, clients) == []) + + platform.komorebic("stack", "left") + checks.check( + "two containers, one of them a stack of two", + platform.wait_for(lambda: _sizes(platform) == [1, 2]), + ) + checks.check( + "exactly one window is put away", + platform.wait_for(lambda: len(_away(platform, clients)) == 1), + ) + shown = os_focused(platform, clients) + checks.check( + "the window in view has the focus", shown != "" and shown not in _away(platform, clients) + ) + checks.check( + "... and the daemon's state agrees", + platform.wait_for(lambda: focus_agrees(platform, clients, shown)), + ) + frame = platform.os_window(Client(shown)) + + platform.komorebic("cycle-stack", "next") + checks.check( + "after 'cycle-stack next' the other window of the stack is in view and the first is away", + platform.wait_for( + lambda: ( + os_focused(platform, clients) not in ("", shown) + and _away(platform, clients) == [shown] + ) + ), + ) + other = os_focused(platform, clients) + checks.check( + "... with the focus agreed", + platform.wait_for(lambda: focus_agrees(platform, clients, other)), + ) + now = platform.os_window(Client(other)) + checks.check( + "... and it fills the tile the first one had", + frame is not None and now is not None and now.frame == frame.frame, + ) + platform.komorebic("cycle-stack", "previous") + checks.check( + "cycling back, the first is in view again", + platform.wait_for( + lambda: os_focused(platform, clients) == shown and len(_away(platform, clients)) == 1 + ), + ) + + platform.komorebic("unstack") + checks.check("three tiles again", platform.wait_for(lambda: _sizes(platform) == [1, 1, 1])) + checks.check("nothing is put away", platform.wait_for(lambda: _away(platform, clients) == [])) + frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None] + checks.check( + "and they tile, not on each other", + len(frames) == len(clients) + and not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]), + ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/support.py b/e2e/lib/komorebi_vm/core/scenarios/support.py new file mode 100644 index 00000000..fe0c0e19 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/support.py @@ -0,0 +1,34 @@ +"""What more than one scenario needs of a platform.""" + +from komorebi_vm.core.platform import Client, Platform + + +def os_focused(platform: Platform, clients: list[Client]) -> str: + """The title of the window the operating system says has the focus, among `clients`. + + The empty string when none of them does. + """ + for client in clients: + window = platform.os_window(client) + if window is not None and window.focused: + return window.title + return "" + + +def positions(platform: Platform, clients: list[Client]) -> dict[str, tuple[int, int]]: + """Where the operating system has each window, by title. + + Only the position: a client may round its size to what suits it (a terminal's cells), and + a window that moved is told by where it is. + """ + found = {} + for client in clients: + window = platform.os_window(client) + if window is not None: + found[client.title] = (window.frame.x, window.frame.y) + return found + + +def focus_agrees(platform: Platform, clients: list[Client], title: str) -> bool: + """The operating system and the daemon's state both have `title` focused.""" + return os_focused(platform, clients) == title and platform.state().focused_title() == title diff --git a/e2e/lib/komorebi_vm/core/scenarios/tiling.py b/e2e/lib/komorebi_vm/core/scenarios/tiling.py new file mode 100644 index 00000000..0a9f871a --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/tiling.py @@ -0,0 +1,67 @@ +"""Windows that open are tiled: each where the layout says, none over another, all on screen.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.platform import Client, Platform + + +def _where_the_layout_says(frame: Rect, want: Rect, tolerance: int) -> bool: + """The same place, and the size up to `tolerance` short of what was asked for.""" + return ( + (frame.x, frame.y) == (want.x, want.y) + and 0 <= want.w - frame.w <= tolerance + and 0 <= want.h - frame.h <= tolerance + ) + + +def run( + platform: Platform, checks: Checks, titles: tuple[str, ...] = ("win1", "win2", "win3") +) -> list[Client]: + """Opens a window for each title and checks, against the OS's own account of the frames, that + the daemon has tiled them. + + The daemon must be running, on a workspace with no window, with a tiling layout. Returns the + windows it opened, for a scenario that goes on from them. + """ + clients = [platform.spawn(title) for title in titles] + area = platform.work_area() + + def managed() -> bool: + return platform.state().managed() == len(titles) + + checks.check("the daemon manages every window", platform.wait_for(managed, timeout=20)) + + def placed() -> bool: + workspace = platform.state().workspace() + layout = workspace.latest_layout + frames = [platform.os_window(c) for c in clients] + if len(layout) != len(titles) or any(f is None for f in frames): + return False + # the layout's rectangles are in the order of the containers, which is not the order the + # windows opened in: each window is matched with its own container's rectangle + by_title = {w.title: layout[i] for i, c in enumerate(workspace.containers) for w in c[:1]} + return all( + f is not None and _where_the_layout_says(f.frame, by_title[f.title], platform.tolerance) + for f in frames + ) + + checks.check( + "every window is where the layout says, as the OS reports it", + platform.wait_for(placed, timeout=20), + ) + + frames = [f.frame for c in clients if (f := platform.os_window(c)) is not None] + checks.check("the OS has a frame for every window", len(frames) == len(titles)) + for client, frame in zip(clients, frames, strict=False): + checks.check(f"{client.title} is inside the work area", frame.inside(area)) + for i, a in enumerate(frames): + for j in range(i + 1, len(frames)): + checks.check( + f"{clients[i].title} and {clients[j].title} do not overlap", + not a.overlaps(frames[j]), + ) + checks.check( + "the windows share the work area: none takes all of its width", + all(f.w < area.w - platform.tolerance for f in frames), + ) + return clients diff --git a/e2e/lib/komorebi_vm/core/scenarios/workspaces.py b/e2e/lib/komorebi_vm/core/scenarios/workspaces.py new file mode 100644 index 00000000..249a61da --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/workspaces.py @@ -0,0 +1,59 @@ +"""A window sent to another workspace is put away, and switching to it brings it and takes the +others away.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.platform import Client, Platform +from komorebi_vm.core.scenarios.support import focus_agrees, os_focused + + +def _in_view(platform: Platform, clients: list[Client]) -> list[str]: + return sorted(c.title for c in clients if not platform.hidden(c)) + + +def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Sends the focused one of `clients` to workspace 1, switches to it and back. + + `clients` are tiled windows of workspace 0, each in a container of its own, with more than one + of them. Workspace 1 is empty. + """ + last = clients[-1] + rest = sorted(c.title for c in clients if c != last) + platform.activate(last) + platform.wait_for(lambda: focus_agrees(platform, clients, last.title)) + checks.check( + "every window is in view", _in_view(platform, clients) == sorted(c.title for c in clients) + ) + + platform.komorebic("send-to-workspace", "1") + checks.check( + f"after 'send-to-workspace 1' {last.title} is put away", + platform.wait_for(lambda: platform.hidden(last)), + ) + checks.check( + "... the daemon has it on workspace 1", + platform.wait_for(lambda: platform.state().containers(1) == [[last.title]]), + ) + checks.check( + "... and the others are still in view", + platform.wait_for(lambda: _in_view(platform, clients) == rest), + ) + + platform.komorebic("focus-workspace", "1") + checks.check( + "after 'focus-workspace 1' only the window sent there is in view", + platform.wait_for(lambda: _in_view(platform, clients) == [last.title]), + ) + checks.check( + "... it has the focus, and the daemon agrees", + platform.wait_for(lambda: focus_agrees(platform, clients, last.title)), + ) + + platform.komorebic("focus-workspace", "0") + checks.check( + "after 'focus-workspace 0' the others are in view and the one sent away is put away", + platform.wait_for(lambda: _in_view(platform, clients) == rest), + ) + checks.check( + "... and one of them has the focus", + platform.wait_for(lambda: os_focused(platform, clients) in rest), + ) diff --git a/e2e/lib/komorebi_vm/core/snapshot.py b/e2e/lib/komorebi_vm/core/snapshot.py new file mode 100644 index 00000000..ef5d2a7f --- /dev/null +++ b/e2e/lib/komorebi_vm/core/snapshot.py @@ -0,0 +1,185 @@ +"""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 + focused_windows: list[int] + """For each container, the place in it of the window that has the focus (a stack's top).""" + 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 | None = None, monitor: int = 0) -> Workspace: + """A workspace of a monitor, by position; the focused one when none is given.""" + m = self.monitors[monitor] + return m.workspaces[m.focused_workspace if workspace is None else workspace] + + 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] + + 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 | None = None, monitor: int = 0) -> str: + """The title of the focused window of a workspace (the focused one when none is given): the + focused window of its focused container. Empty if the workspace has no container.""" + ws = self.workspace(workspace, monitor) + if not ws.containers: + return "" + index = min(ws.focused_container, len(ws.containers) - 1) + container = ws.containers[index] + if not container: + return "" + return container[min(ws.focused_windows[index], len(container) - 1)].title + + +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"]), + focused_windows=[_focused(c["windows"]) for c in _ring(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/e2e/lib/tests/__init__.py b/e2e/lib/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/e2e/lib/tests/fake_platform.py b/e2e/lib/tests/fake_platform.py new file mode 100644 index 00000000..5f408bb1 --- /dev/null +++ b/e2e/lib/tests/fake_platform.py @@ -0,0 +1,186 @@ +"""A desktop in memory with a daemon that follows the commands of the scenarios. + +Three tiles in a row, a window in each. `focus`, `cycle-focus`, `move` and `cycle-move` do what the +real daemon does with windows laid out left to right, so that a scenario can be run against a daemon +that is right, and against ones that are wrong in one way. +""" + +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 + +TILES = [Rect(0, 0, 640, 1080), Rect(640, 0, 640, 1080), Rect(1280, 0, 640, 1080)] + + +class FakePlatform: + tolerance = 24 + + def __init__(self, *, moves: bool = True, focus_follows_move: bool = True) -> None: + 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.current = 0 + self.moves = moves + self.focus_follows_move = focus_follows_move + + def wait_for(self, predicate: Any, timeout: float = 10) -> bool: + return bool(predicate()) + + def start_komorebi(self) -> None: + pass + + @property + def containers(self) -> list[list[str]]: + return self.spaces[self.current] + + @property + def focus(self) -> int: + return self.focuses[self.current] + + @focus.setter + def focus(self, value: int) -> None: + self.focuses[self.current] = value + + @property + def order(self) -> list[str]: + """The titles in view, in the order of the tiles.""" + return [stack[0] for stack in self.containers] + + def spawn(self, title: str) -> Client: + self.containers.append([title]) + return Client(title) + + def _find(self, title: str) -> tuple[int, int]: + for s, containers in enumerate(self.spaces): + for i, stack in enumerate(containers): + if title in stack: + return s, i + raise AssertionError(f"no window {title}") + + def _container(self, title: str) -> int: + return self._find(title)[1] + + def hidden(self, client: Client) -> bool: + s, i = self._find(client.title) + return s != self.current or self.spaces[s][i][0] != client.title + + def work_area(self) -> Rect: + return Rect(0, 0, 1920, 1080) + + def activate(self, client: Client) -> None: + self.current, self.focus = self._find(client.title) + stack = self.containers[self.focus] + stack.insert(0, stack.pop(stack.index(client.title))) + + def screenshot(self, name: str) -> Image.Image: + return Image.new("RGB", (4, 4)) + + def os_window(self, client: Client) -> OsWindow | None: + i = self._container(client.title) + return OsWindow( + client.title, + TILES[i], + focused=i == self.focus and self.containers[i][0] == client.title, + ) + + def komorebic(self, *args: str) -> str: + n = len(self.containers) + match args: + case ("focus", "right"): + self.focus = min(self.focus + 1, n - 1) + case ("focus", "left"): + self.focus = max(self.focus - 1, 0) + case ("cycle-focus", "next"): + self.focus = (self.focus + 1) % n + case ("cycle-focus", "previous"): + self.focus = (self.focus - 1) % n + case ("move", "right"): + self._swap(min(self.focus + 1, n - 1)) + case ("cycle-move", "previous"): + self._swap((self.focus - 1) % n) + case ("stack", "left"): + if self.focus > 0: + stack = self.containers.pop(self.focus) + self.focus -= 1 + self.containers[self.focus][:0] = stack + case ("cycle-stack", "next" | "previous" as way): + stack = self.containers[self.focus] + stack.append(stack.pop(0)) if way == "next" else stack.insert(0, stack.pop()) + case ("send-to-workspace", number): + stack = self.containers[self.focus] + window = stack.pop(0) + if not stack: + self.containers.pop(self.focus) + self.focus = max(0, min(self.focus, len(self.containers) - 1)) + self.spaces[int(number)].append([window]) + case ("focus-workspace", number): + self.current = int(number) + case ("unstack",): + stack = self.containers.pop(self.focus) + self.containers[self.focus : self.focus] = [[t] for t in stack] + case _: + raise AssertionError(f"the fake does not know komorebic {args}") + return "" + + def _swap(self, other: int) -> None: + if not self.moves: + return + self.containers[self.focus], self.containers[other] = ( + self.containers[other], + self.containers[self.focus], + ) + if self.focus_follows_move: + self.focus = other + + def state(self) -> Snapshot: + def window(title: str, tile: Rect) -> dict[str, Any]: + return { + "id": hash(title) % 1000, + "rect": {"left": tile.x, "top": tile.y, "right": tile.w, "bottom": tile.h}, + "details": {"title": title, "exe": "", "class": "", "path": ""}, + } + + def rect(r: Rect) -> dict[str, int]: + return {"left": r.x, "top": r.y, "right": r.w, "bottom": r.h} + + def workspace(containers: list[list[str]], focus: int) -> dict[str, Any]: + return { + "name": None, + "containers": { + "elements": [ + { + "id": str(i), + "locked": False, + "windows": { + "elements": [window(t, TILES[i]) for t in stack], + "focused": 0, + }, + } + for i, stack in enumerate(containers) + ], + "focused": focus, + }, + "monocle_container": None, + "maximized_window": None, + "floating_windows": {"elements": [], "focused": 0}, + "layout": {"Default": "Columns"}, + "tile": True, + "latest_layout": [rect(r) for r in TILES[: len(containers)]], + } + + monitor = { + "id": 1, + "size": rect(Rect(0, 0, 1920, 1080)), + "workspaces": { + "elements": [ + workspace(c, f) for c, f in zip(self.spaces, self.focuses, strict=True) + ], + "focused": self.current, + }, + } + return parse({"monitors": {"elements": [monitor], "focused": 0}}) diff --git a/e2e/lib/tests/test_checks.py b/e2e/lib/tests/test_checks.py new file mode 100644 index 00000000..dede6580 --- /dev/null +++ b/e2e/lib/tests/test_checks.py @@ -0,0 +1,33 @@ +import pytest + +from komorebi_vm.core.checks import Checks + + +def test_counts_passes_and_failures(capsys: pytest.CaptureFixture[str]) -> None: + checks = Checks() + + assert checks.check("a holds", True) + assert not checks.check("b does not hold", False) + + assert (checks.passed, checks.failed) == (1, 1) + out = capsys.readouterr().out + assert " ok a holds" in out + assert " FAIL b does not hold" in out + + +def test_a_callable_condition_is_called() -> None: + checks = Checks() + + assert checks.check("lazy", lambda: 1 + 1 == 2) + + +def test_finish_raises_only_when_something_failed(capsys: pytest.CaptureFixture[str]) -> None: + checks = Checks() + checks.check("fine", True) + checks.finish() + assert "passed: 1 failed: 0" in capsys.readouterr().out + + checks.check("broken", False) + with pytest.raises(AssertionError, match="^1 checks failed: broken$"): + checks.finish() + assert "passed: 1 failed: 1" in capsys.readouterr().out diff --git a/e2e/lib/tests/test_focus_moving.py b/e2e/lib/tests/test_focus_moving.py new file mode 100644 index 00000000..a207304d --- /dev/null +++ b/e2e/lib/tests/test_focus_moving.py @@ -0,0 +1,53 @@ +"""The focus and moving scenarios against a daemon that is right, and against ones that are not.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.scenarios import focus, moving, stacks, tiling, workspaces +from tests.fake_platform import FakePlatform + + +def opened(platform: FakePlatform, checks: Checks): # noqa: ANN201 + return tiling.run(platform, checks) + + +def test_a_daemon_that_is_right_passes_both() -> None: + platform = FakePlatform() + checks = Checks() + clients = opened(platform, checks) + focus.run(platform, checks, clients) + moving.run(platform, checks, clients) + assert checks.failed == 0, checks.failures + assert checks.passed > 10 + + +def test_a_move_that_moves_nothing_fails() -> None: + platform = FakePlatform(moves=False) + checks = Checks() + clients = opened(platform, checks) + moving.run(platform, checks, clients) + assert any("swapped tiles" in f for f in checks.failures) + + +def test_a_move_that_loses_the_focus_fails() -> None: + platform = FakePlatform(focus_follows_move=False) + checks = Checks() + clients = opened(platform, checks) + moving.run(platform, checks, clients) + assert any("keeps the focus" in f for f in checks.failures) + + +def test_a_daemon_that_is_right_passes_stacks() -> None: + platform = FakePlatform() + checks = Checks() + clients = opened(platform, checks) + stacks.run(platform, checks, clients) + assert checks.failed == 0, checks.failures + assert checks.passed > 10 + + +def test_a_daemon_that_is_right_passes_workspaces() -> None: + platform = FakePlatform() + checks = Checks() + clients = opened(platform, checks) + workspaces.run(platform, checks, clients) + assert checks.failed == 0, checks.failures + assert checks.passed > 7 diff --git a/e2e/lib/tests/test_pixels.py b/e2e/lib/tests/test_pixels.py new file mode 100644 index 00000000..609bce09 --- /dev/null +++ b/e2e/lib/tests/test_pixels.py @@ -0,0 +1,74 @@ +from PIL import Image, ImageDraw + +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.pixels import leftmost, near, pixel, ring + +BLUE = (66, 165, 245) +GRAY = (128, 128, 128) + + +def window_in_a_frame(frame: Rect, color: tuple[int, int, int], width: int) -> Image.Image: + """A screen of 200x200 with a black window and a border of `width` pixels outside it.""" + image = Image.new("RGB", (200, 200), (0, 0, 0)) + draw = ImageDraw.Draw(image) + draw.rectangle( + ( + frame.x - width, + frame.y - width, + frame.x + frame.w + width - 1, + frame.y + frame.h + width - 1, + ), + fill=color, + ) + draw.rectangle((frame.x, frame.y, frame.x + frame.w - 1, frame.y + frame.h - 1), fill=(9, 9, 9)) + return image + + +def test_a_pixel_is_red_green_and_blue() -> None: + image = Image.new("RGBA", (4, 4), (1, 2, 3, 255)) + + assert pixel(image, 2, 2) == (1, 2, 3) + + +def test_near_allows_a_difference_on_every_channel_up_to_the_tolerance() -> None: + assert near((10, 10, 10), (22, 0, 10)) + assert not near((10, 10, 10), (23, 10, 10)) + assert near((10, 10, 10), (30, 10, 10), tolerance=20) + + +def test_a_border_all_round_the_window_is_a_ring() -> None: + frame = Rect(60, 60, 80, 80) + + assert ring(window_in_a_frame(frame, BLUE, 10), frame, BLUE) == [] + + +def test_a_side_with_no_border_is_named_with_the_pixel_it_has() -> None: + frame = Rect(60, 60, 80, 80) + image = window_in_a_frame(frame, BLUE, 10) + ImageDraw.Draw(image).rectangle((130, 50, 150, 150), fill=(0, 0, 0)) + + assert ring(image, frame, BLUE) == ["right: (145, 100) is (0, 0, 0), not (66, 165, 245)"] + + +def test_the_ring_of_another_color_is_not_the_ring_asked_for() -> None: + frame = Rect(60, 60, 80, 80) + image = window_in_a_frame(frame, GRAY, 10) + + assert len(ring(image, frame, BLUE)) == 4 + + +def test_a_thin_border_is_not_found_further_out_than_it_is() -> None: + frame = Rect(60, 60, 80, 80) + image = window_in_a_frame(frame, BLUE, 3) + + assert len(ring(image, frame, BLUE)) == 4 + assert ring(image, frame, BLUE, margin=2) == [] + + +def test_leftmost_is_where_a_row_first_has_the_color() -> None: + image = Image.new("RGB", (100, 10), (0, 0, 0)) + ImageDraw.Draw(image).rectangle((30, 4, 60, 4), fill=BLUE) + + assert leftmost(image, 4, BLUE) == 30 + assert leftmost(image, 5, BLUE) is None + assert leftmost(image, 4, GRAY) is None diff --git a/e2e/lib/tests/test_snapshot.py b/e2e/lib/tests/test_snapshot.py new file mode 100644 index 00000000..6d6d8aff --- /dev/null +++ b/e2e/lib/tests/test_snapshot.py @@ -0,0 +1,108 @@ +"""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"] + + +def test_the_focused_window_of_a_stack_is_the_one_the_ring_names() -> None: + state = scene(kfde_window, {}, {}) + workspace = state["monitors"]["elements"][0]["workspaces"]["elements"][0] + stack = workspace["containers"]["elements"][1]["windows"] + stack["elements"].append(kfde_window(4, "under", rect(960, 0, 960, 1080))) + stack["focused"] = 1 + assert parse(state).focused_title() == "under" diff --git a/e2e/lib/tests/test_tiling.py b/e2e/lib/tests/test_tiling.py new file mode 100644 index 00000000..a5cd2328 --- /dev/null +++ b/e2e/lib/tests/test_tiling.py @@ -0,0 +1,112 @@ +"""The tiling scenario against a platform that tiles correctly, and against ones that do not.""" + +from PIL import Image + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.platform import Client, OsWindow +from komorebi_vm.core.scenarios import tiling +from komorebi_vm.core.snapshot import Snapshot, parse + + +class FakePlatform: + """A desktop in memory: `spawn` opens a window, and the frames are the ones it is given.""" + + tolerance = 24 + + def __init__(self, frames: list[Rect]) -> None: + self.frames = frames + self.opened: list[str] = [] + + def wait_for(self, predicate, timeout: float = 10) -> bool: # noqa: ANN001 + return predicate() + + def spawn(self, title: str) -> Client: + self.opened.append(title) + return Client(title) + + def state(self) -> Snapshot: + return parse(_state(self.opened)) + + def os_window(self, client: Client) -> OsWindow | None: + i = self.opened.index(client.title) + return OsWindow(client.title, self.frames[i], focused=False) + + def hidden(self, client: Client) -> bool: + return False + + def work_area(self) -> Rect: + return Rect(0, 0, 1920, 1080) + + def start_komorebi(self) -> None: + pass + + def komorebic(self, *args: str) -> str: + return "" + + def activate(self, client: Client) -> None: + pass + + def screenshot(self, name: str) -> Image.Image: + return Image.new("RGB", (4, 4)) + + +def _state(titles: list[str]) -> dict: + width = 1920 // len(titles) + rects = [ + {"left": i * width, "top": 0, "right": width, "bottom": 1080} for i in range(len(titles)) + ] + windows = [ + {"id": i + 1, "rect": rects[i], "details": {"title": t, "exe": "", "class": "", "path": ""}} + for i, t in enumerate(titles) + ] + workspace = { + "name": None, + "containers": { + "elements": [ + {"id": str(i), "locked": False, "windows": {"elements": [w], "focused": 0}} + for i, w in enumerate(windows) + ], + "focused": 0, + }, + "monocle_container": None, + "maximized_window": None, + "floating_windows": {"elements": [], "focused": 0}, + "layout": {"Default": "Columns"}, + "tile": True, + "latest_layout": rects, + } + monitor = { + "id": 1, + "size": {"left": 0, "top": 0, "right": 1920, "bottom": 1080}, + "workspaces": {"elements": [workspace], "focused": 0}, + } + return {"monitors": {"elements": [monitor], "focused": 0}} + + +def test_windows_that_are_tiled_pass() -> None: + platform = FakePlatform( + [Rect(0, 0, 640, 1080), Rect(640, 0, 640, 1080), Rect(1280, 0, 640, 1080)] + ) + checks = Checks() + tiling.run(platform, checks) + assert checks.failed == 0 + assert checks.passed > 0 + + +def test_windows_over_each_other_fail() -> None: + platform = FakePlatform( + [Rect(0, 0, 700, 1080), Rect(640, 0, 640, 1080), Rect(1280, 0, 640, 1080)] + ) + checks = Checks() + tiling.run(platform, checks) + assert any("overlap" in f for f in checks.failures) + + +def test_a_window_off_the_screen_fails() -> None: + platform = FakePlatform( + [Rect(0, 0, 640, 1080), Rect(640, 0, 640, 1080), Rect(1500, 0, 640, 1080)] + ) + checks = Checks() + tiling.run(platform, checks) + assert any("inside the work area" in f for f in checks.failures)