From 81b12ba0b92d429d16ee88ebb6107a2cbed2908a Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 19:33:26 -0700 Subject: [PATCH] feat(e2e): sync the neutral core from kfde c71c8fd0 --- e2e/lib/komorebi_vm/core/platform.py | 117 +++++- .../komorebi_vm/core/scenarios/commands.py | 56 ++- .../core/scenarios/config_reload.py | 3 +- .../core/scenarios/display_change.py | 68 +++ .../core/scenarios/focus_follows_mouse.py | 18 +- .../komorebi_vm/core/scenarios/fullscreen.py | 73 ++++ .../komorebi_vm/core/scenarios/handover.py | 64 +++ e2e/lib/komorebi_vm/core/scenarios/hotplug.py | 78 +++- .../komorebi_vm/core/scenarios/layout_flip.py | 277 +++++++++++++ e2e/lib/komorebi_vm/core/scenarios/layouts.py | 36 +- .../core/scenarios/lifecycle_hidden.py | 63 +++ e2e/lib/komorebi_vm/core/scenarios/locking.py | 17 +- .../core/scenarios/manage_rules.py | 4 +- .../komorebi_vm/core/scenarios/maximizing.py | 114 +++++ .../komorebi_vm/core/scenarios/monitors.py | 390 ++++++++++++++++++ e2e/lib/komorebi_vm/core/scenarios/monocle.py | 75 +++- e2e/lib/komorebi_vm/core/scenarios/padding.py | 7 +- e2e/lib/komorebi_vm/core/scenarios/pausing.py | 4 +- .../komorebi_vm/core/scenarios/placement.py | 31 +- e2e/lib/komorebi_vm/core/scenarios/queries.py | 103 +++++ e2e/lib/komorebi_vm/core/scenarios/resize.py | 223 +++++++++- .../core/scenarios/resize_commands.py | 28 +- e2e/lib/komorebi_vm/core/scenarios/rules.py | 45 +- .../komorebi_vm/core/scenarios/rules_class.py | 3 +- .../komorebi_vm/core/scenarios/rules_exe.py | 3 +- e2e/lib/komorebi_vm/core/scenarios/support.py | 32 ++ .../komorebi_vm/core/scenarios/tiling_off.py | 4 +- .../komorebi_vm/core/scenarios/title_rule.py | 48 +++ .../core/scenarios/workspace_moves.py | 14 +- .../komorebi_vm/core/scenarios/workspaces.py | 18 +- e2e/lib/tests/fake_platform.py | 341 +++++++++++++-- e2e/lib/tests/test_focus_moving.py | 141 ++++++- e2e/lib/tests/test_tiling.py | 27 +- 33 files changed, 2394 insertions(+), 131 deletions(-) create mode 100644 e2e/lib/komorebi_vm/core/scenarios/display_change.py create mode 100644 e2e/lib/komorebi_vm/core/scenarios/fullscreen.py create mode 100644 e2e/lib/komorebi_vm/core/scenarios/handover.py create mode 100644 e2e/lib/komorebi_vm/core/scenarios/layout_flip.py create mode 100644 e2e/lib/komorebi_vm/core/scenarios/monitors.py create mode 100644 e2e/lib/komorebi_vm/core/scenarios/queries.py create mode 100644 e2e/lib/komorebi_vm/core/scenarios/title_rule.py diff --git a/e2e/lib/komorebi_vm/core/platform.py b/e2e/lib/komorebi_vm/core/platform.py index 9309d6a8..1b92b3aa 100644 --- a/e2e/lib/komorebi_vm/core/platform.py +++ b/e2e/lib/komorebi_vm/core/platform.py @@ -34,8 +34,12 @@ class OsWindow: title: str frame: Rect - """The visible frame: the compositor's on KDE, the DWM's extended frame on Windows.""" + """The visible frame: the compositor's on KDE, the DWM's extended frame on Windows, without + the invisible borders and the shadow. A scenario does not read the frame of a window that is + minimized: it is where the system keeps it, which is not the same on every port.""" focused: bool + """The window has the keyboard focus, as the operating system says. At most one window of a + desktop does; none does while another program's window has it.""" class Pointer(Protocol): @@ -81,18 +85,36 @@ class Platform(Protocol): 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. + A client that sizes itself to a grid (a terminal's cells) ends up short of the tile; one + that does not (a test window) has only the rounding of the system's own frame. The frame + is never past what was asked, so a check that something is inside an area allows no slack + for it, and a check that two sizes are the same allows this much. + + It is a bound on what a client rounds to, not a measure of a change: a scenario that + asks whether the daemon changed a size compares the daemon's layout (`latest_layout`, + which no client rounds) and then that the frame follows it within this. """ ... def wait_for(self, predicate: "Predicate", timeout: float = 10) -> bool: - """Polls `predicate` until it holds or `timeout` seconds, scaled for this host, pass.""" + """Polls `predicate` until it holds or `timeout` seconds, scaled for this host, pass. + + A predicate answers false for what it cannot tell yet. A port may treat a `komorebic` + that fails, in a predicate, as a false (Windows does, while the host is busy), and one may + not (KDE raises): a predicate does not rely on either. + """ ... def start_komorebi(self) -> None: """Starts the daemon from a clean state and waits until it answers.""" ... + def crash(self) -> None: + """Kills the daemon abruptly, as a crash does, and returns when it is gone. Nothing of + what it had set up is put back: a window it hid is as it left it, until a daemon starts + again and finds it.""" + ... + def restart_with(self, config: dict[str, Any]) -> None: """Stops the daemon if it runs, and starts it from a clean state with `config` as its `komorebi.json`, and waits until it answers. @@ -116,12 +138,27 @@ class Platform(Protocol): it succeeded or not.""" ... + def temp_path(self, name: str) -> str: + """A path, on the machine the daemon runs on, of a file `komorebic` and the daemon may + write and read (`save-resize` takes one), in the form `komorebic` is given it.""" + ... + def state(self) -> Snapshot: """The daemon's state.""" ... - def spawn(self, title: str, app_id: str | None = None, exe: str | None = None) -> Client: - """Opens a window with this title and waits until the platform has it. + def spawn( + self, + title: str, + app_id: str | None = None, + exe: str | None = None, + rename_to: str | None = None, + after: float = 0, + ) -> Client: + """Opens a window with this title and waits until the platform has it, and raises if it + never does: a scenario that waits for a window to stay unmanaged must be sure it is there. + + A title is a name that no other window has, taken as it is: it is never a pattern. `app_id` is the class of the window (its app id on Wayland, its window class on Windows) for a rule that matches by it; the platform's own when there is none. @@ -129,6 +166,10 @@ class Platform(Protocol): `exe` is the name of the program that opens it, without an extension (`e2e-exe` is `e2e-exe.exe` on Windows and `e2e-exe` on Linux), for a rule that matches by it. The platform makes a program of that name, and `exe_id` spells the id of a rule for it. + + `rename_to` is a title the window gives itself `after` seconds after it opens (a terminal + escape on KDE, a title update on Windows), as a program that sets its title late does. The + window is then known to the platform by the new title: `Client(rename_to)`. """ ... @@ -143,16 +184,25 @@ class Platform(Protocol): 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. + of a stack, the windows of a workspace that is not the one its display shows, 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. + It is false for a window the system does not have, for one the user minimized, and for one + that floats. A scenario that asks for a window to be put away also asks the daemon where + it is (`state()`), because a port may answer true for any window that is not on the + screen, whoever took it off: on KDE that is one on a virtual desktop that is not shown, + on Windows a cloaked one, which includes the windows of another virtual desktop. A scenario + that asks for windows to be in view counts those the system has (`support.in_view`). """ ... 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.""" + coordinates of the desktop. The daemon is not asked. + + Displays are not the same size (the one `add_display` plugs in may be smaller than the + first) and need not touch: a scenario uses each one's own rectangle and does not compute + where the next begins.""" ... def add_display(self) -> None: @@ -162,16 +212,34 @@ class Platform(Protocol): ... def remove_display(self) -> None: - """Unplugs the display that was plugged in last, and returns when the operating system no - longer has it.""" + """Unplugs the last display (the rightmost, which is the one `add_display` plugged in last), + and returns when the operating system no longer has it. + + Only a display `add_display` plugged in is certain to be removable: Windows refuses + any other, KDE unplugs the last of the outputs it has. A scenario unplugs a display only + after it plugged one in, unless its suite started the platform with more than one.""" + ... + + def resizable_display(self) -> int | None: + """The place in `displays()` of a display whose mode (its resolution) can be changed, or + `None` when the platform has none that can, and a scenario that needs one is skipped with + the reason. A scenario plugs in a display with `add_display` before it asks.""" + ... + + def resize_display(self, index: int, width: int, height: int) -> None: + """Gives the display `resizable_display` named another mode, `width` by `height` pixels, + and returns when the operating system has it: `displays()` says so. The daemon learns of + it later, so a scenario waits for its state to follow.""" ... def close(self, client: Client) -> None: - """Closes the window, as its close button would.""" + """Closes the window, as its close button would, and returns without waiting for it to be + gone. Raises if there is no such window.""" ... def minimize(self, client: Client) -> None: - """Minimizes the window, as its title bar button would. `activate` restores it.""" + """Minimizes the window, as its title bar button would. `activate` restores it. Raises if + there is no such window.""" ... def lock(self) -> None: @@ -190,12 +258,31 @@ class Platform(Protocol): size.""" ... + def fullscreen(self, client: Client, on: bool = True) -> None: + """Takes the window fullscreen, as the program's own key does it (`on`), or brings it back + from fullscreen (`on` false). The daemon is not asked: it learns of it from the system, and + has to leave the window alone. Returns when the system has done it.""" + ... + + def user_maximize(self, client: Client, on: bool = True) -> None: + """Maximizes the window, as its title bar button does (`on`), or restores it from being + maximized (`on` false). The daemon is not asked: it learns of it from the system. Returns + when the system has done it.""" + ... + def work_area(self) -> Rect: - """The area of the first display that windows may take.""" + """The area of the first display that windows may take, in the coordinates of the + desktop: the display less what the operating system keeps for itself (a panel, a dock, the + taskbar), as the operating system says and not the daemon. + + It is the whole display only where there is nothing of the kind. A scenario that asks + whether a window is "inside the work area" asks this, so a platform that answers with the + display where the system has a bar makes that check weaker than it says.""" ... def activate(self, client: Client) -> None: - """Gives the window the focus, as a click on it would.""" + """Gives the window the focus, as a click on it would, and restores it if it was minimized. + Raises if there is no such window.""" ... def screenshot(self, name: str) -> Image.Image: diff --git a/e2e/lib/komorebi_vm/core/scenarios/commands.py b/e2e/lib/komorebi_vm/core/scenarios/commands.py index 23935f0a..509a61e8 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/commands.py +++ b/e2e/lib/komorebi_vm/core/scenarios/commands.py @@ -10,6 +10,7 @@ command does is checked elsewhere; this says none of them breaks a running daemo from collections.abc import Sequence from komorebi_vm.core.checks import Checks +from komorebi_vm.core.geometry import Rect from komorebi_vm.core.platform import Client, Platform LAYOUTS: tuple[str, ...] = ( @@ -285,15 +286,18 @@ def unhealthy(platform: Platform, clients: list[Client]) -> str | None: 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() +FEWER = (3, 2, 1) +"""The counts of windows below the one `layouts` starts with that it tries every layout with.""" + + +def _each_layout( + platform: Platform, checks: Checks, clients: list[Client], label: str, area: Rect +) -> None: + """Changes to every layout, with `clients` the windows there are, and checks them.""" 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") + checks.skip(f"change-layout {layout}{label}", "the port has no such layout") continue problems = [] if status != 0: @@ -313,7 +317,45 @@ def layouts(platform: Platform, checks: Checks, clients: list[Client]) -> None: for b in titles[i + 1 :] if frames[a].overlaps(frames[b]) ] - checks.check(f"change-layout {layout}: " + ("; ".join(problems) or "ok"), not problems) + checks.check( + f"change-layout {layout}{label}: " + ("; ".join(problems) or "ok"), not problems + ) + + +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. + + It does the same with three, two and one windows (those of `FEWER` that `clients` has more + than): the others are closed from the end, and opened again with their own titles at the end, + with the layout `bsp`. + """ + area = platform.work_area() + _each_layout(platform, checks, clients, "", area) + closed: list[Client] = [] + for keep in (n for n in FEWER if n < len(clients)): + for client in clients[keep:]: + if client not in closed: + platform.close(client) + closed.append(client) + left = clients[:keep] + platform.wait_for(lambda n=keep: platform.state().managed() == n, timeout=20) + _each_layout(platform, checks, left, f" with {keep} windows", area) + if closed: + platform.komorebic("change-layout", "bsp") + for client in closed: + platform.spawn(client.title) + checks.check( + "the windows that were closed are opened again and managed", + platform.wait_for( + lambda: ( + unhealthy(platform, clients) is None + and platform.state().managed() == len(clients) + ), + timeout=30, + ), + ) def sweep( diff --git a/e2e/lib/komorebi_vm/core/scenarios/config_reload.py b/e2e/lib/komorebi_vm/core/scenarios/config_reload.py index d4274679..6c34c0d0 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/config_reload.py +++ b/e2e/lib/komorebi_vm/core/scenarios/config_reload.py @@ -4,6 +4,7 @@ from typing import Any from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Platform +from komorebi_vm.core.scenarios.support import QUIET def _config(names: list[str], layout: str, rule: str | None = None) -> dict[str, Any]: @@ -60,7 +61,7 @@ def run(platform: Platform, checks: Checks) -> None: platform.rewrite_config(_config(["uno", "dos", "tres"], "Columns")) # the reload does not say when it is done: the next window shows whether the rule is - platform.wait_for(lambda: False, timeout=3) + platform.wait_for(lambda: False, timeout=QUIET) later = platform.spawn("reload-sent-2") checks.check( "once the file loses the rule, a window of that title stays on the first workspace", diff --git a/e2e/lib/komorebi_vm/core/scenarios/display_change.py b/e2e/lib/komorebi_vm/core/scenarios/display_change.py new file mode 100644 index 00000000..64b91873 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/display_change.py @@ -0,0 +1,68 @@ +"""A display whose mode changes: the daemon's monitor follows, and the windows stay put.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.platform import Client, Platform +from komorebi_vm.core.scenarios.hotplug import _in_one_of +from komorebi_vm.core.scenarios.support import positions + + +def _size_follows(platform: Platform, index: int, size: tuple[int, int]) -> bool: + """The operating system's display and the daemon's monitor both have this size.""" + displays, monitors = platform.displays(), platform.state().monitors + return ( + index < len(displays) + and index < len(monitors) + and (displays[index].w, displays[index].h) == size + and (monitors[index].size.w, monitors[index].size.h) == size + ) + + +def _clear(platform: Platform, clients: list[Client]) -> bool: + """Every window is on a display, and none is over another.""" + frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None] + return _in_one_of(platform, clients, platform.displays()) 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: + """Changes the mode of a display to a smaller one and back, and checks that the daemon's + monitor has the size of each, that the windows are inside the displays and apart while it is + small, and that they are where they were when the display is as it was. + + `clients` are windows the daemon manages, each in a container of its own. A second display is + plugged in first if the platform has only one, and the platform says which display can change + its mode: where none can, the scenario is skipped. + """ + if len(platform.displays()) < 2: + platform.add_display() + platform.wait_for(lambda: len(platform.state().monitors) == len(platform.displays())) + index = platform.resizable_display() + if index is None: + checks.skip( + "a display changes its mode", "the platform cannot change the mode of a display" + ) + return + before = platform.displays()[index] + size = (1280, 720) if before.w > 1280 else (1024, 768) + there = positions(platform, clients) + + platform.resize_display(index, *size) + checks.check( + f"the display has the mode {size[0]}x{size[1]} and the daemon's monitor follows", + platform.wait_for(lambda: _size_follows(platform, index, size), timeout=30), + ) + checks.check( + "... every window is on a display and clear of the others", + platform.wait_for(lambda: _clear(platform, clients), timeout=30), + ) + + platform.resize_display(index, before.w, before.h) + checks.check( + "changed back, the display and the monitor have their size again", + platform.wait_for(lambda: _size_follows(platform, index, (before.w, before.h)), timeout=30), + ) + checks.check( + "... and every window is where it was", + platform.wait_for(lambda: positions(platform, clients) == there, timeout=30), + ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/focus_follows_mouse.py b/e2e/lib/komorebi_vm/core/scenarios/focus_follows_mouse.py index aca4d4f1..8f343520 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/focus_follows_mouse.py +++ b/e2e/lib/komorebi_vm/core/scenarios/focus_follows_mouse.py @@ -2,6 +2,7 @@ from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Client, Platform +from komorebi_vm.core.scenarios.support import QUIET def _middle(platform: Platform, client: Client) -> tuple[int, int] | None: @@ -16,10 +17,16 @@ def _focused(platform: Platform, client: Client) -> bool: return window is not None and window.focused +# how long a setting is given to be taken up before the pointer is moved. A port may read it a +# moment after it is written, or follow the pointer after a delay of its own: this is more than +# either, and it is scaled for the host like every wait +SETTLE = 1 + + def _settle(platform: Platform) -> None: - """Gives a platform the time to take up a setting: KWin reads its focus policy about 200 ms - after it is written, and a pointer that is moved before that is moved under the old one.""" - platform.wait_for(lambda: False, timeout=1) + """Gives the platform the time to take up a setting: a pointer that is moved before is moved + under the old one.""" + platform.wait_for(lambda: False, timeout=SETTLE) def run(platform: Platform, checks: Checks, first: Client, second: Client) -> None: @@ -56,12 +63,13 @@ def run(platform: Platform, checks: Checks, first: Client, second: Client) -> No platform.wait_for(lambda: platform.state().focused_title() == first.title, timeout=10), ) - platform.komorebic("toggle-focus-follows-mouse", "--implementation", "windows") + # no `--implementation`: each port has one, and the command's default is it + platform.komorebic("toggle-focus-follows-mouse") _settle(platform) platform.pointer.move(*b) checks.check( "turned off, the pointer over the second window no longer moves the focus", - not platform.wait_for(lambda: _focused(platform, second), timeout=3) + not platform.wait_for(lambda: _focused(platform, second), timeout=QUIET) and _focused(platform, first), ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/fullscreen.py b/e2e/lib/komorebi_vm/core/scenarios/fullscreen.py new file mode 100644 index 00000000..f7bb8978 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/fullscreen.py @@ -0,0 +1,73 @@ +"""A window the user takes fullscreen is left alone by the daemon, and goes back to its tile.""" + +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 focus_agrees + + +def _covers(frame: Rect, display: Rect) -> bool: + """The frame has the whole display, give or take a pixel.""" + return ( + frame.x <= display.x + 1 + and frame.y <= display.y + 1 + and frame.x + frame.w >= display.x + display.w - 1 + and frame.y + frame.h >= display.y + display.h - 1 + ) + + +def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Takes the last of `clients` fullscreen, opens a window, and brings it back. + + `clients` are tiled windows of the first workspace on the first display, each in a container + of its own. The window opened is closed at the end. + """ + target = clients[-1] + count = platform.state().managed() + display = platform.displays()[0] + platform.activate(target) + platform.wait_for(lambda: focus_agrees(platform, clients, target.title)) + # the daemon asks again for the frames of what it moved, for a little while after a command + platform.wait_for(lambda: False, timeout=3) + + def covers() -> bool: + window = platform.os_window(target) + return window is not None and _covers(window.frame, display) + + platform.fullscreen(target) + checks.check( + "a window taken fullscreen covers the display", + platform.wait_for(covers, timeout=20), + ) + extra = platform.spawn("fullscreen-extra") + checks.check( + "the daemon manages a window that opens meanwhile", + platform.wait_for(lambda: platform.state().managed() == count + 1, timeout=20), + ) + platform.wait_for(lambda: False, timeout=3) + checks.check("... and it does not take the window out of fullscreen", covers()) + + platform.fullscreen(target, on=False) + + def in_a_tile() -> bool: + window = platform.os_window(target) + return ( + window is not None + and window.frame.w < display.w - 100 + and window.frame.inside(display, 1) + ) + + checks.check( + "back from fullscreen it is in a tile, inside the display", + platform.wait_for(in_a_tile, timeout=20), + ) + frames = [w.frame for c in [*clients, extra] if (w := platform.os_window(c)) is not None] + checks.check( + "... not on any other window", + not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]), + ) + checks.check( + "... and the daemon still has every window", platform.state().managed() == count + 1 + ) + platform.close(extra) + platform.wait_for(lambda: platform.state().managed() == count, timeout=20) diff --git a/e2e/lib/komorebi_vm/core/scenarios/handover.py b/e2e/lib/komorebi_vm/core/scenarios/handover.py new file mode 100644 index 00000000..3222fd8a --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/handover.py @@ -0,0 +1,64 @@ +"""`minimize`, `unmanage` and `manage`: the daemon lets go of the focused window, and takes it up +again.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.platform import Client, Platform +from komorebi_vm.core.scenarios.support import focus_agrees +from komorebi_vm.core.scenarios.tiling import _where_the_layout_says + + +def _on_a_tile(platform: Platform, client: Client) -> bool: + """The window is where the daemon's layout puts one of its tiles.""" + window = platform.os_window(client) + layout = platform.state().workspace().latest_layout + return window is not None and any( + _where_the_layout_says(window.frame, tile, platform.tolerance) for tile in layout + ) + + +def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Runs `minimize`, `unmanage` and `manage` on the window that has the focus, which is one of + `clients`: tiled windows of the first workspace, in a container each. + + They take a window out of the daemon's hands, so a sweep of commands does not run them. The + window is tiled again at the end. + """ + title = platform.state().focused_title() + target = Client(title) + before = platform.state().managed() + platform.wait_for(lambda: focus_agrees(platform, clients, title), timeout=10) + + def has_let_go() -> bool: + return platform.state().managed() == before - 1 and platform.os_window(target) is not None + + def has_it() -> bool: + return platform.state().managed() == before and _on_a_tile(platform, target) + + platform.komorebic("minimize") + checks.check( + f"minimize: the daemon lets go of {title}, which stays open", + platform.wait_for(has_let_go, timeout=10), + ) + platform.activate(target) + checks.check(f"{title}, restored, is tiled again", platform.wait_for(has_it, timeout=10)) + + platform.wait_for(lambda: focus_agrees(platform, clients, title), timeout=10) + platform.komorebic("unmanage") + checks.check( + f"unmanage: the daemon lets go of {title}, which stays open", + platform.wait_for(has_let_go, timeout=10), + ) + area = platform.work_area() + + def left_alone() -> bool: + window = platform.os_window(target) + return ( + window is not None and window.frame.inside(area, 2) and not _on_a_tile(platform, target) + ) + + checks.check( + f"{title} is inside the work area and not on a tile of the layout", + platform.wait_for(left_alone, timeout=10), + ) + platform.komorebic("manage") + checks.check(f"manage: {title} is tiled again", platform.wait_for(has_it, timeout=10)) diff --git a/e2e/lib/komorebi_vm/core/scenarios/hotplug.py b/e2e/lib/komorebi_vm/core/scenarios/hotplug.py index 2b5a0c6a..2031e19f 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/hotplug.py +++ b/e2e/lib/komorebi_vm/core/scenarios/hotplug.py @@ -40,7 +40,6 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: 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), @@ -50,7 +49,10 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: platform.wait_for( lambda: ( _in_one_of(platform, clients, platform.displays()) - and (len(platform.displays()) > 1 or _tiled_in(platform, clients, first)) + and ( + len(platform.displays()) > 1 + or _tiled_in(platform, clients, platform.work_area()) + ) ), timeout=30, ), @@ -102,3 +104,75 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: timeout=30, ), ) + + +def _display_of(frame: Rect, displays: list[Rect]) -> int | None: + """The display the middle of the frame is on.""" + x, y = frame.x + frame.w // 2, frame.y + frame.h // 2 + for i, d in enumerate(displays): + if d.x <= x < d.x + d.w and d.y <= y < d.y + d.h: + return i + return None + + +def _split(platform: Platform, clients: list[Client]) -> dict[int, list[Client]]: + """The windows on each display, by the middle of their frames.""" + displays = platform.displays() + found: dict[int, list[Client]] = {i: [] for i in range(len(displays))} + for client in clients: + window = platform.os_window(client) + if window is not None and (i := _display_of(window.frame, displays)) is not None: + found[i].append(client) + return found + + +def _containers(platform: Platform, monitor: int) -> int: + return len(platform.state().workspace(monitor=monitor).containers) + + +def _each_tiled_on_its_display(platform: Platform, clients: list[Client]) -> bool: + displays = platform.displays() + return all(_tiled_in(platform, on, displays[i]) for i, on in _split(platform, clients).items()) + + +def user_move(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """A window that something other than the daemon moves to the other display is tiled on that + monitor, and the windows that are left are tiled on the first. + + `clients` are windows the daemon manages, each in a container of its own, on the first display, + two of them or more. A second display is plugged in first if the platform has only one. The + window that moves is the last of `clients` on the first display, and it stays on the second. + """ + if len(platform.displays()) < 2: + platform.add_display() + platform.wait_for(lambda: _monitors(platform) == len(platform.displays()), timeout=30) + displays = platform.displays() + on_first = _split(platform, clients)[0] + if len(on_first) < 2: + checks.skip("a window moved to the other display", "fewer than two windows on the first") + return + window = on_first[-1] + first, second = _containers(platform, 0), _containers(platform, 1) + # the daemon asks again for the frames of the windows it moved, for a little while after a + # command: a user moves a window later than that + platform.wait_for(lambda: False, timeout=2) + platform.move_window(window, displays[1].x + 180, displays[1].y + 300) + checks.check( + "the daemon has the window on the other monitor", + platform.wait_for( + lambda: ( + _containers(platform, 0) == first - 1 and _containers(platform, 1) == second + 1 + ), + timeout=30, + ), + ) + checks.check( + "every window is tiled inside the display it is on, and the moved one is on the second", + platform.wait_for( + lambda: ( + window in _split(platform, clients)[1] + and _each_tiled_on_its_display(platform, clients) + ), + timeout=30, + ), + ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/layout_flip.py b/e2e/lib/komorebi_vm/core/scenarios/layout_flip.py new file mode 100644 index 00000000..51e64e1b --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/layout_flip.py @@ -0,0 +1,277 @@ +"""The `layout_flip` option of a workspace, in the config: the layout is mirrored from the start.""" + +from typing import Any + +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.layouts import tiled + +CLI = { + "Horizontal": "horizontal", + "Vertical": "vertical", + "HorizontalAndVertical": "horizontal-and-vertical", +} +"""The values the option takes, and how `flip-layout` spells each.""" + +# (layout, windows, value of the option): where a flip along an axis shows. The columns are in a +# row, so only a horizontal flip moves them; the rows are in a column, so only a vertical one does; +# BSP with three windows has one tile on a side and two stacked on the other, so both do. +CASES = [ + ("Columns", 2, "Horizontal"), + ("BSP", 2, "Horizontal"), + ("Columns", 3, "Horizontal"), + ("Columns", 3, "Vertical"), + ("Columns", 3, "HorizontalAndVertical"), + ("Rows", 3, "Vertical"), + ("BSP", 3, "Horizontal"), + ("BSP", 3, "Vertical"), + ("BSP", 3, "HorizontalAndVertical"), +] + +Flip = tuple[bool, bool] +"""Whether the layout is mirrored along x (left to right) and along y (top to bottom).""" + + +def _flip(value: str | None) -> Flip: + return ( + value in ("Horizontal", "HorizontalAndVertical"), + value in ("Vertical", "HorizontalAndVertical"), + ) + + +def _config(layout: str, value: str | None) -> dict[str, Any]: + workspace: dict[str, Any] = {"name": "flip", "layout": layout} + if value is not None: + workspace["layout_flip"] = value + return {"monitors": [{"workspaces": [workspace]}]} + + +def _witnesses(layout: str, count: int) -> list[tuple[int, str]]: + """The containers whose side of the work area says which way the layout is mirrored, each with + the axis. Unflipped, the first column is on the left, the first row at the top, the first BSP + tile on the left and the second at the top right.""" + return { + "Columns": [(0, "x")], + "Rows": [(0, "y")], + "BSP": [(0, "x")] + ([(1, "y")] if count >= 3 else []), + }[layout] + + +def _beyond_the_middle(platform: Platform, title: str, axis: str, area: Rect) -> bool | None: + """Whether the window is on the far side of the middle of the work area (right, or below).""" + window = platform.os_window(Client(title)) + if window is None: + return None + f = window.frame + if axis == "x": + return 2 * f.x + f.w > 2 * area.x + area.w + return 2 * f.y + f.h > 2 * area.y + area.h + + +def _on_the_side(platform: Platform, layout: str, count: int, flip: Flip, area: Rect) -> bool: + """Every witness is on the side that a layout flipped as `flip` puts it.""" + order = [c[0] for c in platform.state().containers()] + for index, axis in _witnesses(layout, count): + if index >= len(order): + return False + side = _beyond_the_middle(platform, order[index], axis, area) + if side is None or side != flip[0 if axis == "x" else 1]: + return False + return True + + +def _centres(platform: Platform, clients: list[Client]) -> dict[str, tuple[int, int]]: + """The middle of each window, doubled so that it is a whole number.""" + found = {} + for client in clients: + window = platform.os_window(client) + if window is not None: + f = window.frame + found[client.title] = (2 * f.x + f.w, 2 * f.y + f.h) + return found + + +def _mirrored( + platform: Platform, + before: dict[str, tuple[int, int]], + now: dict[str, tuple[int, int]], + flip: Flip, + area: Rect, +) -> bool: + """Every window of `now` is where the mirror of its place in `before` along `flip` is.""" + middle = (2 * area.x + area.w, 2 * area.y + area.h) + tolerance = 2 * platform.tolerance + return len(now) == len(before) and all( + t in now + and abs((2 * middle[0] - x if flip[0] else x) - now[t][0]) <= tolerance + and abs((2 * middle[1] - y if flip[1] else y) - now[t][1]) <= tolerance + for t, (x, y) in before.items() + ) + + +def _check_case( + platform: Platform, + checks: Checks, + clients: list[Client], + layout: str, + value: str, + compose: bool, +) -> None: + count = len(clients) + label = f"{layout}, {count} windows, layout_flip {value}" + area = platform.work_area() + flip = _flip(value) + unflipped: Flip = (False, False) + + platform.restart_with(_config(layout, value)) + platform.wait_for(lambda: platform.state().managed() == count, timeout=30) + checks.check( + f"{label}: the daemon starts with the layout mirrored: the windows are where it says", + platform.wait_for(lambda: tiled(platform, clients), timeout=30), + ) + checks.check( + f"{label}: ... and on the side of the work area that the flip puts them", + platform.wait_for(lambda: _on_the_side(platform, layout, count, flip, area), timeout=20), + ) + mirrored = _centres(platform, clients) + + # the command and the option are one flip: the command flips it off + platform.komorebic("flip-layout", CLI[value]) + checks.check( + f"{label}: 'flip-layout {CLI[value]}' turns it off: the windows are on the other side", + platform.wait_for( + lambda: _on_the_side(platform, layout, count, unflipped, area), timeout=20 + ), + ) + checks.check( + f"{label}: ... each where the mirror of its place is", + platform.wait_for( + lambda: _mirrored(platform, mirrored, _centres(platform, clients), flip, area), + timeout=20, + ), + ) + checks.check( + f"{label}: ... and where the layout says", + platform.wait_for(lambda: tiled(platform, clients), timeout=20), + ) + platform.komorebic("flip-layout", CLI[value]) + checks.check( + f"{label}: flipped again with the command, the windows are where the option put them", + platform.wait_for( + lambda: ( + _mirrored(platform, mirrored, _centres(platform, clients), unflipped, area) + and _on_the_side(platform, layout, count, flip, area) + ), + timeout=20, + ), + ) + + if compose: + # on top of a horizontal flip, a vertical one is both + platform.komorebic("flip-layout", "vertical") + both = _flip("HorizontalAndVertical") + checks.check( + f"{label}: 'flip-layout vertical' adds to it: flipped along both axes", + platform.wait_for( + lambda: _on_the_side(platform, layout, count, both, area), timeout=20 + ), + ) + checks.check( + f"{label}: ... the windows have only gone from top to bottom", + platform.wait_for( + lambda: _mirrored( + platform, mirrored, _centres(platform, clients), (False, True), area + ), + timeout=20, + ), + ) + + +def _left_to_right(platform: Platform, workspace: int) -> list[str] | None: + """The titles of the containers of a workspace, ordered by where the window is, left to right; + `None` when a window is not there.""" + order = [c[0] for c in platform.state().containers(workspace)] + centres = _centres(platform, [Client(t) for t in order]) + if len(centres) != len(order): + return None + return sorted(order, key=lambda t: centres[t][0]) + + +def _two_workspaces(platform: Platform, checks: Checks, flipped: int) -> None: + """Two workspaces of columns, one of them flipped, each with two windows.""" + rule = {"kind": "Title", "id": "flip plain", "matching_strategy": "StartsWith"} + workspaces: list[dict[str, Any]] = [ + {"name": "first", "layout": "Columns"}, + {"name": "second", "layout": "Columns", "workspace_rules": [rule]}, + ] + workspaces[flipped]["layout_flip"] = "Horizontal" + homes = [platform.spawn("flip home 1"), platform.spawn("flip home 2")] + plains = [platform.spawn("flip plain 1"), platform.spawn("flip plain 2")] + platform.restart_with({"monitors": [{"workspaces": workspaces}]}) + label = f"layout_flip on workspace {flipped} of two" + checks.check( + f"{label}: the windows are on the workspaces the rule gives them", + platform.wait_for( + lambda: ( + all(platform.state().workspace_of(c.title) == 0 for c in homes) + and all(platform.state().workspace_of(c.title) == 1 for c in plains) + ), + timeout=30, + ), + ) + for workspace in (0, 1): + platform.komorebic("focus-workspace", str(workspace)) + members = homes if workspace == 0 else plains + platform.wait_for(lambda m=members: not any(platform.hidden(c) for c in m), timeout=20) + order = [c[0] for c in platform.state().containers(workspace)] + want = order[::-1] if workspace == flipped else order + checks.check( + f"{label}: workspace {workspace} has its windows " + + ("mirrored" if workspace == flipped else "in the order of the layout"), + platform.wait_for(lambda w=workspace, e=want: _left_to_right(platform, w) == e), + ) + platform.komorebic("focus-workspace", "0") + for client in homes + plains: + platform.close(client) + platform.wait_for(lambda: platform.state().managed() == 0, timeout=30) + + +def run(platform: Platform, checks: Checks) -> None: + """Starts the daemon with `layout_flip` in the config of a workspace, for each value the + option takes, and checks that the windows are mirrored as the value says, that `flip-layout` + and the option are the one flip, and that the option is the workspace's own. + + The daemon must be running and have no window open: `restart_with` makes a daemon that takes + up every window in view, and opening the windows before it is the usual way to have them + there. The daemon is left running on the last config this makes. + + The option is `layout_flip` of a workspace in `komorebi.json` (`WorkspaceConfig` in + `komorebi/src/static_config.rs`, which `Workspace::load_static_config` copies to the + workspace, as `komorebic flip-layout` sets it). Its values are `Horizontal`, `Vertical` and + `HorizontalAndVertical`: the layout is mirrored left to right, top to bottom, or both, which + is what `Axis` means in `flip_layout`. `flip-layout X` along an axis the layout is already + flipped along turns that flip off, and along another axis adds it, so that `flip-layout + horizontal` on a layout the config flipped horizontally gives the layout back. + + Where a flip shows depends on the layout: columns are only mirrored by a horizontal flip and + rows by a vertical one (the layouts say so), and BSP with three windows by both. So each case + looks at the windows whose side tells: the first column, the first row, and the first and + second tile of BSP. A flip along an axis the layout does not have changes nothing, which a + case checks too. + + A window that was opened before the daemon is taken up by it, so the windows the cases use are + the same ones, two and then three, and are closed at the end. + """ + clients = [platform.spawn("layout_flip 1"), platform.spawn("layout_flip 2")] + for layout, count, value in CASES: + if count == 3 and len(clients) == 2: + clients.append(platform.spawn("layout_flip 3")) + # the flip is added to by a command in one case, which has all of the axes to show it + compose = (layout, count, value) == ("BSP", 3, "Horizontal") + _check_case(platform, checks, clients, layout, value, compose) + for client in clients: + platform.close(client) + platform.wait_for(lambda: platform.state().managed() == 0, timeout=30) + for flipped in (0, 1): + _two_workspaces(platform, checks, flipped) diff --git a/e2e/lib/komorebi_vm/core/scenarios/layouts.py b/e2e/lib/komorebi_vm/core/scenarios/layouts.py index 45d2043e..da2a3d74 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/layouts.py +++ b/e2e/lib/komorebi_vm/core/scenarios/layouts.py @@ -49,9 +49,42 @@ def _check_layout(platform: Platform, checks: Checks, clients: list[Client], lay ) +FEWER = (3, 2, 1) +"""The counts of windows below the one the scenario starts with that every layout is tried with.""" + + +def _fewer(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Every layout with fewer windows: those of `FEWER` that `clients` has more than, the others + closed from the end, and opened again with their own titles at the end.""" + closed: list[Client] = [] + for keep in (n for n in FEWER if n < len(clients)): + for client in clients[keep:]: + if client not in closed: + platform.close(client) + closed.append(client) + left = clients[:keep] + checks.check( + f"{keep} windows are left managed", + platform.wait_for(lambda n=keep: platform.state().managed() == n, timeout=20), + ) + for layout in LAYOUTS: + _check_layout(platform, checks, left, layout) + platform.komorebic("change-layout", "bsp") + for client in closed: + platform.spawn(client.title) + checks.check( + "the windows that were closed are opened again and tiled", + platform.wait_for( + lambda: platform.state().managed() == len(clients) and tiled(platform, clients), + timeout=30, + ), + ) + + def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: """Changes the layout of the first workspace to each of `LAYOUTS` with `clients`, which are - tiled windows in a container each, and then with two windows more, which it closes. + tiled windows in a container each, and then with two windows more, which it closes, and with + three, two and one windows of `clients`, which it closes, and opens again. The layout is `bsp` again at the end. """ @@ -77,3 +110,4 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: timeout=20, ), ) + _fewer(platform, checks, clients) diff --git a/e2e/lib/komorebi_vm/core/scenarios/lifecycle_hidden.py b/e2e/lib/komorebi_vm/core/scenarios/lifecycle_hidden.py index 57adc120..3b2bbc3c 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/lifecycle_hidden.py +++ b/e2e/lib/komorebi_vm/core/scenarios/lifecycle_hidden.py @@ -48,3 +48,66 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: "... and not on each other", not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]), ) + + +def crash(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Turns a monocle on, which puts the other windows away, kills the daemon, and starts it + again: nothing is left out of sight for the new daemon to find, and it manages every window. + + `clients` are two tiled windows or more of the first workspace, each in a container of its own. + The monocle is off at the end. + """ + target, other = clients[-1], clients[0] + + def in_front() -> None: + # a window that already has the focus gives the daemon no event: another one first + platform.activate(other) + platform.activate(target) + platform.wait_for(lambda: focus_agrees(platform, clients, target.title)) + + def only_target_in_view() -> bool: + return all(platform.hidden(c) for c in clients if c != target) and not platform.hidden( + target + ) + + in_front() + platform.komorebic("toggle-monocle") + checks.check( + "with a monocle on, the other windows are out of sight", + platform.wait_for(only_target_in_view, timeout=20), + ) + platform.crash() + checks.check( + "the killed daemon no longer answers", + platform.wait_for(lambda: platform.komorebic_status("state")[0] != 0, timeout=20), + ) + + platform.start_komorebi() + checks.check( + "the next daemon manages every window", + platform.wait_for(lambda: platform.state().managed() >= len(clients), timeout=30), + ) + checks.check( + "... and none is left out of sight", + platform.wait_for(lambda: not any(platform.hidden(c) for c in clients), timeout=20), + ) + area = platform.work_area() + frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None] + checks.check( + "... inside the work area and not on each other", + len(frames) == len(clients) + and all(f.inside(area) for f in frames) + and not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]), + ) + + in_front() + platform.komorebic("toggle-monocle") + checks.check( + "after a crash and a restart a monocle still puts the other windows away", + platform.wait_for(only_target_in_view, timeout=20), + ) + platform.komorebic("toggle-monocle") + checks.check( + "... and turned off, nothing is out of sight", + platform.wait_for(lambda: not any(platform.hidden(c) for c in clients), timeout=20), + ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/locking.py b/e2e/lib/komorebi_vm/core/scenarios/locking.py index b17d82f7..b1573222 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/locking.py +++ b/e2e/lib/komorebi_vm/core/scenarios/locking.py @@ -36,7 +36,22 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: "while the screen is locked the daemon has the same windows: the lock screen is not one", platform.state().managed() == len(clients), ) - platform.move_window(clients[0], 400, 300) + # a third of the way into the work area, and not on the tile the window is on + area = platform.work_area() + tile = platform.os_window(clients[0]) + assert tile is not None + target = (area.x + area.w // 3, area.y + area.h // 3) + if target == (tile.frame.x, tile.frame.y): + target = (target[0] + 50, target[1] + 50) + platform.move_window(clients[0], *target) + moved = platform.wait_for( + lambda: ( + (w := platform.os_window(clients[0])) is not None + and (w.frame.x, w.frame.y) != (tile.frame.x, tile.frame.y) + ), + timeout=10, + ) + checks.check("the window was moved while the screen was locked", moved) after = [platform.os_window(c) for c in clients] checks.check( "the others did not move for it", diff --git a/e2e/lib/komorebi_vm/core/scenarios/manage_rules.py b/e2e/lib/komorebi_vm/core/scenarios/manage_rules.py index 7bcff874..65ec0de0 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/manage_rules.py +++ b/e2e/lib/komorebi_vm/core/scenarios/manage_rules.py @@ -4,9 +4,7 @@ from typing import Any from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Client, Platform - -# how long a window has to stay unmanaged for it to be left alone -QUIET = 3 +from komorebi_vm.core.scenarios.support import QUIET def _kinds(platform: Platform) -> list[tuple[str, str, dict[str, Any]]]: diff --git a/e2e/lib/komorebi_vm/core/scenarios/maximizing.py b/e2e/lib/komorebi_vm/core/scenarios/maximizing.py index 66106a09..c1027c54 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/maximizing.py +++ b/e2e/lib/komorebi_vm/core/scenarios/maximizing.py @@ -33,6 +33,11 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: f"after 'toggle-maximize' {target.title} fills the work area", platform.wait_for(fills, timeout=20), ) + window = platform.os_window(target) + checks.check( + "... without going past the work area", + window is not None and window.frame.inside(area), + ) checks.check( "... and the daemon has it as the maximized window", platform.wait_for(lambda: maximized() == target.title, timeout=20), @@ -51,3 +56,112 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: "... and every window is tiled where the layout says", platform.wait_for(lambda: tiled(platform, clients), timeout=20), ) + + +# What is asked of the layout, which a maximized window is not in: none of it does anything. +IGNORED = ( + "move left", + "move right", + "move up", + "move down", + "stack left", + "stack right", + "unstack", + "cycle-move next", + "promote", + "toggle-float", + "toggle-monocle", + "resize-edge left increase", + "send-to-workspace 1", + "move-to-workspace 1", + "toggle-lock", +) + + +def user(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """A window the user maximizes, not the command, is taken out of the layout like one that + `toggle-maximize` maximized: the daemon has it as its maximized window, the others are left + alone, what is asked of the layout does nothing, and it goes back to its tile when it is + restored, by `toggle-maximize` or by the user. + + `clients` are three tiled windows or more of the first workspace, each in a container of its + own. The first workspace has the second one, so that `send-to-workspace 1` can name it. + """ + count = len(clients) + target, other = clients[1], clients[-1] + area = platform.work_area() + tiles = positions(platform, clients) + + def maximized() -> str | None: + window = platform.state().workspace().maximized + return window.title if window else None + + def containers() -> int: + return len(platform.state().workspace().containers) + + def fills(client: Client) -> bool: + window = platform.os_window(client) + return ( + window is not None + and window.frame.w >= area.w - 2 * platform.tolerance + and window.frame.h >= area.h - 4 * platform.tolerance + ) + + platform.user_maximize(target) + checks.check( + f"after the user maximizes {target.title} the daemon has it as its maximized window", + platform.wait_for(lambda: maximized() == target.title, timeout=20), + ) + checks.check("... it fills the work area", platform.wait_for(lambda: fills(target), timeout=10)) + checks.check( + "... its tile is gone, and the daemon still has every window", + containers() == count - 1 and platform.state().managed() == count, + ) + + beside = positions(platform, [c for c in clients if c != target]) + for command in IGNORED: + platform.komorebic_status(*command.split()) + platform.wait_for(lambda: False, timeout=1) + checks.check( + "what is asked of the layout does nothing: it is still maximized, and the others did not" + " move", + fills(target) + and maximized() == target.title + and positions(platform, [c for c in clients if c != target]) == beside, + ) + workspace = platform.state().workspace() + checks.check( + "... and nothing floats or is in the monocle", + containers() == count - 1 and workspace.floating == [] and workspace.monocle is None, + ) + + platform.komorebic("toggle-maximize") + checks.check( + f"toggle-maximize restores it: nothing is maximized and {target.title} is in its tile", + platform.wait_for( + lambda: ( + maximized() is None + and containers() == count + and positions(platform, [target]) == {target.title: tiles[target.title]} + ), + timeout=20, + ), + ) + + platform.user_maximize(other) + checks.check( + f"the user maximizes {other.title} too", + platform.wait_for(lambda: maximized() == other.title and containers() == count - 1), + ) + platform.user_maximize(other, on=False) + checks.check( + f"restored by the user, {other.title} is back in its tile and nothing is maximized", + platform.wait_for( + lambda: ( + maximized() is None + and containers() == count + and positions(platform, [other]) == {other.title: tiles[other.title]} + ), + timeout=20, + ), + ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/monitors.py b/e2e/lib/komorebi_vm/core/scenarios/monitors.py new file mode 100644 index 00000000..e4e73fa1 --- /dev/null +++ b/e2e/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/e2e/lib/komorebi_vm/core/scenarios/monocle.py b/e2e/lib/komorebi_vm/core/scenarios/monocle.py index 4b3c3b65..272e2cf4 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/monocle.py +++ b/e2e/lib/komorebi_vm/core/scenarios/monocle.py @@ -8,6 +8,17 @@ from komorebi_vm.core.scenarios.support import focus_agrees, os_focused, positio PADDING = 120 +def _fills(platform: Platform, client: Client) -> bool: + """The window has the work area, up to the padding of the layout.""" + window = platform.os_window(client) + area = platform.work_area() + return ( + window is not None + and window.frame.w >= area.w - PADDING + and window.frame.h >= area.h - PADDING + ) + + def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: """Toggles monocle on the focused one of `clients`, which are tiled windows of the first workspace, each in a container of its own, and toggles it off again.""" @@ -15,21 +26,20 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: platform.activate(last) platform.wait_for(lambda: focus_agrees(platform, clients, last.title)) before = positions(platform, clients) - area = platform.work_area() def fills_the_work_area() -> bool: - window = platform.os_window(last) - return ( - window is not None - and window.frame.w >= area.w - PADDING - and window.frame.h >= area.h - PADDING - ) + return _fills(platform, last) platform.komorebic("toggle-monocle") checks.check( "in monocle the focused window fills the work area", platform.wait_for(fills_the_work_area, timeout=20), ) + window = platform.os_window(last) + checks.check( + "... without going past the work area", + window is not None and window.frame.inside(platform.work_area()), + ) checks.check( "... the daemon's state has it as the monocle container", platform.wait_for( @@ -59,3 +69,54 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: "... and the state has no monocle container", platform.wait_for(lambda: platform.state().workspace().monocle is None), ) + + +def focus_behaviour(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """What `monocle-focus-behaviour` makes of focusing in a direction in a monocle: with `no-op` + the window keeps the work area, and with `cycle` another window gets it. + + `clients` are two or more tiled windows of the first workspace, each in a container of its + own. The monocle is off and the behaviour is `no-op` at the end. + """ + first = clients[0] + platform.activate(first) + platform.wait_for(lambda: focus_agrees(platform, clients, first.title)) + before = positions(platform, clients) + + platform.komorebic("monocle-focus-behaviour", "no-op") + platform.komorebic("toggle-monocle") + platform.wait_for(lambda: _fills(platform, first), timeout=20) + platform.komorebic("focus", "right") + checks.check( + "with the no-op behaviour, focusing in a direction leaves the window the work area", + not platform.wait_for(lambda: os_focused(platform, clients) != first.title, timeout=3) + and _fills(platform, first), + ) + + platform.komorebic("monocle-focus-behaviour", "cycle") + platform.komorebic("focus", "right") + + def another_has_it() -> bool: + title = os_focused(platform, clients) + return title not in ("", first.title) and _fills(platform, Client(title)) + + checks.check( + "with the cycle behaviour, focusing in a direction gives another window the work area", + platform.wait_for(another_has_it, timeout=20), + ) + checks.check( + "... and the daemon's state has that window as the monocle container", + platform.wait_for( + lambda: ( + [w.title for w in platform.state().workspace().monocle or []] + == [os_focused(platform, clients)] + ) + ), + ) + + platform.komorebic("toggle-monocle") + platform.komorebic("monocle-focus-behaviour", "no-op") + checks.check( + "the windows are tiled again, each on the tile it had", + platform.wait_for(lambda: positions(platform, clients) == before, timeout=20), + ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/padding.py b/e2e/lib/komorebi_vm/core/scenarios/padding.py index 94f249bb..1e644b92 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/padding.py +++ b/e2e/lib/komorebi_vm/core/scenarios/padding.py @@ -21,6 +21,9 @@ def run( container = configured[1] if state.container_padding is None else state.container_padding print(f" padding of the workspace {workspace}, of its containers {container}") area = platform.work_area() + # how much room the windows must lose or regain, in square pixels: a small part of the work + # area, for the display is not the same size on every platform + unit = area.w * area.h // 400 def frames() -> list[Rect]: return [w.frame for c in clients if (w := platform.os_window(c)) is not None] @@ -61,7 +64,7 @@ def run( platform.komorebic("focused-workspace-container-padding", str(container + 30)) checks.check( "a container padding 30 px more leaves the windows less room", - platform.wait_for(lambda: room() < base - 5000, timeout=20), + platform.wait_for(lambda: room() < base - unit, timeout=20), ) checks.check( "... and none is over another, or outside the work area", @@ -77,5 +80,5 @@ def run( print(f" margin {margin()} (was {start}), room {room()} (was {base})") checks.check( "... and have the room they had", - platform.wait_for(lambda: abs(room() - base) <= 2000, timeout=20), + platform.wait_for(lambda: abs(room() - base) <= unit // 2, timeout=20), ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/pausing.py b/e2e/lib/komorebi_vm/core/scenarios/pausing.py index 3ea3c424..e759bce7 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/pausing.py +++ b/e2e/lib/komorebi_vm/core/scenarios/pausing.py @@ -3,9 +3,7 @@ from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Client, Platform from komorebi_vm.core.scenarios.layouts import tiled - -# how long a daemon that is paused has to leave a window alone for it to count -QUIET = 3 +from komorebi_vm.core.scenarios.support import QUIET def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: diff --git a/e2e/lib/komorebi_vm/core/scenarios/placement.py b/e2e/lib/komorebi_vm/core/scenarios/placement.py index 76f9a8ec..a6d1761c 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/placement.py +++ b/e2e/lib/komorebi_vm/core/scenarios/placement.py @@ -5,12 +5,13 @@ from typing import Any from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Client, Platform -CASES: list[tuple[str, Any, list[str], list[str]]] = [ - # (what it says, the placement rules, the titles in the order they open, the order they end in) - ("no rules: after the one in focus", None, ["a", "b", "c"], ["a", "b", "c"]), - ("every window to the primary tile", "Primary", ["a", "b", "c"], ["c", "b", "a"]), - ("by the number of the place, counted from 1", 2, ["a", "b", "c"], ["a", "c", "b"]), - ("text that is a number is the same place", "2", ["a", "b", "c"], ["a", "c", "b"]), +CASES: list[tuple[str, Any, list[str], list[str], dict[str, str]]] = [ + # (what it says, the placement rules, the titles in the order they open, the order they end in, + # the class of the windows that have one, by title) + ("no rules: after the one in focus", None, ["a", "b", "c"], ["a", "b", "c"], {}), + ("every window to the primary tile", "Primary", ["a", "b", "c"], ["c", "b", "a"], {}), + ("by the number of the place, counted from 1", 2, ["a", "b", "c"], ["a", "c", "b"], {}), + ("text that is a number is the same place", "2", ["a", "b", "c"], ["a", "c", "b"], {}), ( "by the title: first, last, and after the one in focus", { @@ -19,6 +20,17 @@ CASES: list[tuple[str, Any, list[str], list[str]]] = [ }, ["one", "two", "special", "a chat room", "four"], ["special", "one", "two", "a chat room", "four"], + {}, + ), + ( + "by the class: first, and by the title: last", + { + "Primary": {"kind": "Class", "id": "special-class", "matching_strategy": "Equals"}, + "Last": [{"kind": "Title", "id": "chat", "matching_strategy": "Contains"}], + }, + ["one", "two", "three", "a chat room", "four"], + ["three", "one", "two", "a chat room", "four"], + {"three": "special-class"}, ), ] @@ -46,7 +58,8 @@ def _settled(platform: Platform, title: str, count: int) -> None: def run(platform: Platform, checks: Checks, known_failures: dict[str, str] | None = None) -> None: """Starts the daemon with each case's rules, opens its windows one after the other, and checks - the order they are in. + the order they are in. A window that has a class in the case is opened with it, for a rule that + matches by its class. `known_failures` maps the description of a case to why a port is known to fail it, whether its daemon does not start with the rules or puts the windows in another order. The case is @@ -57,7 +70,7 @@ def run(platform: Platform, checks: Checks, known_failures: dict[str, str] | Non the one before is managed and has the focus, because "after the one in focus" depends on it. """ known = known_failures or {} - for description, rules, titles, want in CASES: + for description, rules, titles, want, classes in CASES: reason = known.get(description) try: platform.restart_with(_config(rules)) @@ -68,7 +81,7 @@ def run(platform: Platform, checks: Checks, known_failures: dict[str, str] | Non continue clients: list[Client] = [] for title in titles: - clients.append(platform.spawn(title)) + clients.append(platform.spawn(title, app_id=classes.get(title))) _settled(platform, title, len(clients)) got = _order(platform) message = f"{description}: {', '.join(want)} ({got})" diff --git a/e2e/lib/komorebi_vm/core/scenarios/queries.py b/e2e/lib/komorebi_vm/core/scenarios/queries.py new file mode 100644 index 00000000..44ef0c35 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/queries.py @@ -0,0 +1,103 @@ +"""`komorebic query` answers with what the daemon's state says, and the resize a workspace has can +be saved and loaded.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.geometry import Rect +from komorebi_vm.core.platform import Platform +from komorebi_vm.core.scenarios.commands import NOT_A_COMMAND +from komorebi_vm.core.snapshot import Snapshot + +# the layouts that `change-layout` takes by a name that is the lower case of the one a query gives +BY_NAME = {"BSP": "bsp", "Columns": "columns", "Rows": "rows"} + + +def _expected(state: Snapshot) -> dict[str, str]: + """What each query that depends on the focus should answer, from the daemon's own state.""" + monitor = state.monitors[state.focused_monitor] + workspace = state.workspace(monitor=state.focused_monitor) + expected = { + "focused-monitor-index": str(state.focused_monitor), + "focused-workspace-index": str(monitor.focused_workspace), + "focused-workspace-name": workspace.name or str(monitor.focused_workspace), + "focused-workspace-layout": workspace.layout, + } + if workspace.containers: + container = workspace.containers[workspace.focused_container] + expected["focused-container-index"] = str(workspace.focused_container) + expected["focused-window-index"] = str( + workspace.focused_windows[workspace.focused_container] + ) + expected["focused-container-kind"] = "Stack" if len(container) > 1 else "Single" + return expected + + +def _query(platform: Platform, checks: Checks, state: Snapshot) -> None: + for query, want in _expected(state).items(): + status, out = platform.komorebic_status("query", query) + if status != 0 and NOT_A_COMMAND in out: + checks.skip(f"query {query}", "the port has no such query") + continue + checks.check(f"query {query} answers {want!r}", status == 0 and out.strip() == want) + + +def _layout(platform: Platform) -> list[Rect]: + return platform.state().workspace().latest_layout + + +def _round_trip( + platform: Platform, checks: Checks, name: str, save: tuple[str, ...], load: tuple[str, ...] +) -> None: + """Saves the resize, resizes the focused container, loads it, and checks that the layout is + the one it was.""" + before = _layout(platform) + status, _ = platform.komorebic_status(*save) + platform.komorebic("resize-axis", "horizontal", "increase") + resized = platform.wait_for(lambda: _layout(platform) != before, timeout=10) + status_load, _ = platform.komorebic_status(*load) + checks.check( + f"{name}: a resize is undone by loading what was saved", + status == 0 + and resized + and status_load == 0 + and platform.wait_for(lambda: _layout(platform) == before, timeout=10), + ) + + +def run(platform: Platform, checks: Checks) -> None: + """Asks every query and checks the answer against the daemon's state, after changing the + focus and the layout so that the answers are not the ones of a fresh daemon, and saves and + loads the resize both ways. + + The focused workspace has two containers or more. The focus and the layout are as they were at + the end. + """ + _query(platform, checks, platform.state()) + status, out = platform.komorebic_status("query", "version") + checks.check("query version answers", status == 0 and out.strip() != "") + + workspace = platform.state().workspace() + if len(workspace.containers) < 2: + checks.skip("queries after a change, and the saved resize", "fewer than two containers") + return + + platform.komorebic("cycle-focus", "next") + platform.wait_for( + lambda: platform.state().workspace().focused_container != workspace.focused_container, + timeout=10, + ) + _query(platform, checks, platform.state()) + platform.komorebic("cycle-focus", "previous") + + if workspace.layout in BY_NAME: + other = "columns" if workspace.layout == "Rows" else "rows" + platform.komorebic("change-layout", other) + platform.wait_for(lambda: platform.state().workspace().layout != workspace.layout) + _query(platform, checks, platform.state()) + platform.komorebic("change-layout", BY_NAME[workspace.layout]) + platform.wait_for(lambda: platform.state().workspace().layout == workspace.layout) + + _round_trip( + platform, checks, "quick-save-resize", ("quick-save-resize",), ("quick-load-resize",) + ) + path = platform.temp_path("e2e-resize.json") + _round_trip(platform, checks, "save-resize", ("save-resize", path), ("load-resize", path)) diff --git a/e2e/lib/komorebi_vm/core/scenarios/resize.py b/e2e/lib/komorebi_vm/core/scenarios/resize.py index 506c170c..439513ca 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/resize.py +++ b/e2e/lib/komorebi_vm/core/scenarios/resize.py @@ -6,6 +6,8 @@ from komorebi_vm.core.platform import Client, Platform # how far outside a window's frame its resize border is pressed: the gap between two tiles OFFSET = 4 +# the shortest drag, in pixels: far enough to be a drag on any display +MIN_DRAG = 60 # how far the edge may end up from where the pointer put it, in pixels SLACK = 6 @@ -20,8 +22,9 @@ def _side_by_side(layout: list[Rect]) -> tuple[int, int] | None: return None -def run(platform: Platform, checks: Checks, clients: list[Client], dx: int = 60) -> None: - """Drags the edge between a tile and the one to its right by `dx` pixels, and checks that the +def run(platform: Platform, checks: Checks, clients: list[Client], dx: int | None = None) -> None: + """Drags the edge between a tile and the one to its right by `dx` pixels (a thirty-second of + the work area's width, and at least `MIN_DRAG`, when it is not given), and checks that the two tiles moved the edge by what the pointer moved, that every other edge stayed, and that the windows still tile on the work area, as the operating system has them. @@ -30,6 +33,8 @@ def run(platform: Platform, checks: Checks, clients: list[Client], dx: int = 60) if not platform.has("pointer"): print(" skipped: this platform has no pointer") return + if dx is None: + dx = max(MIN_DRAG, platform.work_area().w // 32) state = platform.state() workspace = state.workspace() layout = workspace.latest_layout @@ -88,3 +93,217 @@ def run(platform: Platform, checks: Checks, clients: list[Client], dx: int = 60) "and do not overlap", not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]), ) + + +GRABS = { + "left": "L", + "right": "R", + "top": "T", + "bottom": "B", + "topleft": "LT", + "topright": "RT", + "bottomleft": "LB", + "bottomright": "RB", +} +# how far apart two windows may be for one to be the neighbour of the other: twice the gap +NEIGHBOUR = 80 + + +def _edges(r: Rect) -> dict[str, int]: + return {"L": r.x, "T": r.y, "R": r.x + r.w, "B": r.y + r.h} + + +def _tiles(platform: Platform) -> dict[str, Rect]: + """The daemon's layout: the tile it gave each container, by the title of its window in view.""" + workspace = platform.state().workspace() + return { + c[min(workspace.focused_windows[i], len(c) - 1)].title: workspace.latest_layout[i] + for i, c in enumerate(workspace.containers) + if i < len(workspace.latest_layout) and c + } + + +def _frames(platform: Platform, clients: list[Client]) -> dict[str, Rect]: + return {c.title: w.frame for c in clients if (w := platform.os_window(c)) is not None} + + +def _settled(platform: Platform, clients: list[Client]) -> dict[str, Rect]: + """The frames once they have stopped changing.""" + last = _frames(platform, clients) + for _ in range(20): + platform.wait_for(lambda: False, timeout=0.5) + now = _frames(platform, clients) + if now == last: + return now + last = now + return last + + +def _press_point(grab: str, r: Rect) -> tuple[int, int]: + """Where the pointer is pressed for a grab: in the gap outside the frame.""" + left, right, top, bottom = r.x - OFFSET, r.x + r.w + OFFSET, r.y - OFFSET, r.y + r.h + OFFSET + cx, cy = r.x + r.w // 2, r.y + r.h // 2 + return { + "left": (left, cy), + "right": (right, cy), + "top": (cx, top), + "bottom": (cx, bottom), + "topleft": (left, top), + "topright": (right, top), + "bottomleft": (left, bottom), + "bottomright": (right, bottom), + }[grab] + + +def _has_neighbour(edge: str, name: str, frames: dict[str, Rect]) -> bool: + """Is there another window within a gap's reach on that side of this one, overlapping it.""" + me = frames[name] + for other, o in frames.items(): + if other == name: + continue + vertical = o.y < me.y + me.h and me.y < o.y + o.h + horizontal = o.x < me.x + me.w and me.x < o.x + o.w + if edge == "L" and vertical and 0 <= me.x - (o.x + o.w) <= NEIGHBOUR: + return True + if edge == "R" and vertical and 0 <= o.x - (me.x + me.w) <= NEIGHBOUR: + return True + if edge == "T" and horizontal and 0 <= me.y - (o.y + o.h) <= NEIGHBOUR: + return True + if edge == "B" and horizontal and 0 <= o.y - (me.y + me.h) <= NEIGHBOUR: + return True + return False + + +def _stacked(layout: list[Rect]) -> tuple[int, int] | None: + """The first pair of tiles of which the second is below the first and overlaps it sideways.""" + for i, a in enumerate(layout): + for j, b in enumerate(layout): + if i != j and b.y >= a.y + a.h and a.x < b.x + b.w and b.x < a.x + a.w: + return i, j + return None + + +def _cases(layout: list[Rect], titles: list[str], area: Rect) -> list[tuple[str, str, int, int]]: + """Drags to make, as (window, grab, dx, dy), from the layout: both sides of an edge that two + tiles share, a horizontal one, a corner next to two neighbours, and an edge of the screen.""" + cases: list[tuple[str, str, int, int]] = [] + if (pair := _side_by_side(layout)) is not None: + a, b = pair + cases += [ + (titles[a], "right", 72, 0), + (titles[a], "right", -72, 0), + (titles[b], "left", -72, 0), + (titles[b], "left", -240, 0), + ] + if (stack := _stacked(layout)) is not None: + a, b = stack + cases += [(titles[a], "bottom", 0, 72), (titles[b], "top", 0, -72)] + for k, tile in enumerate(layout): + right_of = any( + i != k and tile.x >= t.x + t.w and t.y < tile.y + tile.h and tile.y < t.y + t.h + for i, t in enumerate(layout) + ) + above = any( + i != k and t.y >= tile.y + tile.h and tile.x < t.x + t.w and t.x < tile.x + tile.w + for i, t in enumerate(layout) + ) + if right_of and above: + cases.append((titles[k], "bottomleft", -72, 72)) + break + first = min(range(len(layout)), key=lambda i: layout[i].x) + if _press_point("left", layout[first])[0] >= area.x: + cases.append((titles[first], "left", -72, 0)) + return cases + + +def _problems( + platform: Platform, + clients: list[Client], + case: tuple[str, str, int, int], +) -> list[str]: + """Makes a drag and says what is wrong with the outcome: the frame the user sees, the layout, + the edges that were not dragged and the windows.""" + name, grab, dx, dy = case + area = platform.work_area() + platform.komorebic("retile") + before = _settled(platform, clients) + tiles_before = _tiles(platform) + + px, py = _press_point(grab, before[name]) + end = (max(area.x, px + dx), max(area.y, py + dy)) + platform.pointer.drag((px, py), end) + platform.wait_for(lambda: _tiles(platform) != tiles_before, timeout=3) + after = _settled(platform, clients) + tiles_after = _tiles(platform) + + held = GRABS[grab] + want = {"L": dx, "R": dx, "T": dy, "B": dy} + problems = [] + moved = {e: _edges(after[name])[e] - _edges(before[name])[e] for e in "LTRB"} + for e in "LTRB": + if e in held and _has_neighbour(e, name, before): + if abs(moved[e] - want[e]) > platform.tolerance: + problems.append(f"frame {e} moved {moved[e]}, the pointer moved {want[e]}") + elif abs(moved[e]) > platform.tolerance: + why = "was not dragged" if e not in held else "has no neighbour" + problems.append(f"frame {e} moved {moved[e]} but {why}") + + tile_moved = {e: _edges(tiles_after[name])[e] - _edges(tiles_before[name])[e] for e in "LTRB"} + for e in "LTRB": + if e in held and _has_neighbour(e, name, before): + if abs(tile_moved[e] - want[e]) > 2: + problems.append(f"tile {e} moved {tile_moved[e]}, the pointer moved {want[e]}") + elif abs(tile_moved[e]) > 1: + why = "was not dragged" if e not in held else "has no neighbour" + problems.append(f"tile {e} moved {tile_moved[e]} but {why}") + + # nothing else moves, but with a dragged edge: they share it + follows = [m for m in tile_moved.values() if abs(m) > 1] + for other in tiles_after: + if other == name: + continue + for e in "LTRB": + m = _edges(tiles_after[other])[e] - _edges(tiles_before[other])[e] + if abs(m) > 1 and not any(abs(m - f) <= 2 for f in follows): + problems.append(f"{other} tile {e} moved {m}: not with the dragged edge") + + names = list(after) + for i, a in enumerate(names): + if not after[a].inside(area): + problems.append(f"{a} {after[a]} is outside the work area") + problems += [f"{a} and {b} overlap" for b in names[i + 1 :] if after[a].overlaps(after[b])] + print(f" {case}: frame {before[name]} -> {after[name]}, tile edges {tile_moved}") + return problems + + +def edge_cases(platform: Platform, checks: Checks, clients: list[Client]) -> None: + """Drags both sides of an edge two tiles share, a horizontal edge, a corner and an edge of the + screen, and checks, against the layout the daemon computed (`latest_layout`) and the frames the + operating system has: + + - a dragged edge that has a neighbour moves by what the pointer moved, and the neighbour's + edge moves with it + - a dragged edge with no neighbour does not move, and the window is put back + - edges that were not dragged do not move, and every edge of another tile stays or moves with + a dragged one + - the windows still tile: inside the work area, not on each other + + `clients` are the tiled windows of the first workspace, each in a container of its own, in a + layout that has them side by side or stacked. The cases are made from the layout, so that + a layout with no stacked tiles has no horizontal case. The layout is retiled before each one. + """ + if not platform.has("pointer"): + print(" skipped: this platform has no pointer") + return + platform.komorebic("retile") + platform.wait_for(lambda: len(_tiles(platform)) == len(clients), timeout=20) + tiles = _tiles(platform) + titles = list(tiles) + layout = [tiles[t] for t in titles] + for case in _cases(layout, titles, platform.work_area()): + problems = _problems(platform, clients, case) + name, grab, dx, dy = case + checks.check( + f"{name}:{grab}:{dx},{dy}: " + ("as expected" if not problems else "; ".join(problems)), + not problems, + ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/resize_commands.py b/e2e/lib/komorebi_vm/core/scenarios/resize_commands.py index ed1318d0..af4d117f 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/resize_commands.py +++ b/e2e/lib/komorebi_vm/core/scenarios/resize_commands.py @@ -2,7 +2,8 @@ from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Client, Platform -from komorebi_vm.core.scenarios.support import focus_agrees +from komorebi_vm.core.scenarios.layouts import tiled +from komorebi_vm.core.scenarios.support import focus_agrees, layout_rect # how much wider the window must get for the command to have done something MIN_STEP = 10 @@ -26,18 +27,35 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :] ) - before = width() + def asked() -> int: + """The width the daemon's layout gives the window, which no client rounds.""" + rect = layout_rect(platform, target) + return rect.w if rect is not None else 0 + + before, asked_before = width(), asked() platform.komorebic("resize-axis", "horizontal", "increase") checks.check( - f"after 'resize-axis horizontal increase' {target.title} is wider", + f"after 'resize-axis horizontal increase' the layout gives {target.title} more width", + platform.wait_for(lambda: asked() >= asked_before + MIN_STEP, timeout=20), + ) + checks.check( + "... and the window is wider", platform.wait_for(lambda: width() >= before + MIN_STEP, timeout=20), ) - print(f" width {before} -> {width()}") + print(f" width {before} -> {width()}, asked {asked_before} -> {asked()}") + checks.check( + "... where the layout says, whatever the client rounds its size to", + platform.wait_for(lambda: tiled(platform, clients), timeout=20), + ) checks.check("... and every window is inside the work area, none over another", clear()) platform.komorebic("resize-axis", "horizontal", "decrease") checks.check( - "after 'decrease' it has the width it had", + "after 'decrease' the layout gives it the width it had", + platform.wait_for(lambda: asked() == asked_before, timeout=20), + ) + checks.check( + "... and the window has the width it had, to what the client rounds to", platform.wait_for(lambda: abs(width() - before) <= platform.tolerance, timeout=20), ) checks.check("... and every window is inside the work area, none over another", clear()) diff --git a/e2e/lib/komorebi_vm/core/scenarios/rules.py b/e2e/lib/komorebi_vm/core/scenarios/rules.py index 24b7ca83..a2bb17c0 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/rules.py +++ b/e2e/lib/komorebi_vm/core/scenarios/rules.py @@ -1,7 +1,10 @@ """Rules that match a window by its title decide where it goes, or that it is left alone.""" +import json + from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Platform +from komorebi_vm.core.scenarios.support import QUIET def _on(platform: Platform, title: str) -> int | None: @@ -9,12 +12,13 @@ def _on(platform: Platform, title: str) -> int | None: def run(platform: Platform, checks: Checks) -> None: - """Gives the daemon three rules, opens a window that each matches, and checks where it went. + """Gives the daemon four 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. + that is not initial sends it again whenever the rules are enforced, and at the next event (a + window that opens); the same by the name of a workspace. An ignore rule leaves it alone. Once + the rules are cleared the daemon's global state has none. The daemon must be running, on the + first workspace, which is the one in view, with no window. """ platform.komorebic("ensure-workspaces", "0", "3") @@ -45,7 +49,7 @@ def run(platform: Platform, checks: Checks) -> None: # 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), + not platform.wait_for(lambda: _on(platform, "sent-once") != 0, timeout=QUIET), ) always = platform.spawn("sent-always") @@ -71,7 +75,34 @@ def run(platform: Platform, checks: Checks) -> None: and _on(platform, "left-alone") is None, ) + platform.komorebic("workspace-name", "0", "2", "chat") + platform.komorebic("named-workspace-rule", "title", "sent-named", "chat") + named = platform.spawn("sent-named") + checks.check( + "a window a rule by the name of a workspace matches goes to that workspace", + platform.wait_for(lambda: _on(platform, "sent-named") == 2, timeout=20), + ) + platform.komorebic("focus-workspace", "2") + # the always rule's window is on that workspace too: the focus is on the one to move + platform.activate(named) + platform.komorebic("move-to-workspace", "0") + platform.wait_for(lambda: _on(platform, "sent-named") == 0, timeout=20) + # a window that opens is an event, and a rule that is not initial is applied at every event + poke = platform.spawn("sent-poke") + checks.check( + "a rule that is not initial sends the window back at the next event, a window that opens", + platform.wait_for(lambda: _on(platform, "sent-named") == 2, timeout=30), + ) + platform.komorebic("clear-all-workspace-rules") + state = json.loads(platform.komorebic("global-state")) + if "workspace_rules" in state: + checks.check( + "once the rules are cleared the daemon's global state has none", + not state["workspace_rules"], + ) + else: + checks.skip("the global state has no rule", "the port's global state has no such field") platform.komorebic("focus-workspace", "0") # the title is the window's name here, so the first window of it goes before the next opens platform.close(once) @@ -80,7 +111,7 @@ def run(platform: Platform, checks: Checks) -> None: checks.check( "once the rules are cleared, a window they matched stays on the workspace in view", platform.wait_for(lambda: _on(platform, "sent-once") == 0, timeout=20) - and not platform.wait_for(lambda: _on(platform, "sent-once") != 0, timeout=3), + and not platform.wait_for(lambda: _on(platform, "sent-once") != 0, timeout=QUIET), ) - for client in (always, ignored, later): + for client in (always, ignored, later, named, poke): platform.close(client) diff --git a/e2e/lib/komorebi_vm/core/scenarios/rules_class.py b/e2e/lib/komorebi_vm/core/scenarios/rules_class.py index bf3fb8c4..ab2bd8fe 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/rules_class.py +++ b/e2e/lib/komorebi_vm/core/scenarios/rules_class.py @@ -3,6 +3,7 @@ is left alone.""" from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Platform +from komorebi_vm.core.scenarios.support import QUIET def run(platform: Platform, checks: Checks) -> None: @@ -30,7 +31,7 @@ def run(platform: Platform, checks: Checks) -> None: checks.check( "a window an ignore rule by class matches is not managed", not platform.wait_for( - lambda: platform.state().workspace_of(left.title) is not None, timeout=3 + lambda: platform.state().workspace_of(left.title) is not None, timeout=QUIET ), ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/rules_exe.py b/e2e/lib/komorebi_vm/core/scenarios/rules_exe.py index decf25b1..53df4299 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/rules_exe.py +++ b/e2e/lib/komorebi_vm/core/scenarios/rules_exe.py @@ -7,6 +7,7 @@ rule has, whatever its kind.""" from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Platform +from komorebi_vm.core.scenarios.support import QUIET def run(platform: Platform, checks: Checks) -> None: @@ -34,7 +35,7 @@ def run(platform: Platform, checks: Checks) -> None: checks.check( "a window an ignore rule by exe matches is not managed", not platform.wait_for( - lambda: platform.state().workspace_of(left.title) is not None, timeout=3 + lambda: platform.state().workspace_of(left.title) is not None, timeout=QUIET ), ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/support.py b/e2e/lib/komorebi_vm/core/scenarios/support.py index fe0c0e19..c9f294a1 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/support.py +++ b/e2e/lib/komorebi_vm/core/scenarios/support.py @@ -1,7 +1,13 @@ """What more than one scenario needs of a platform.""" +from komorebi_vm.core.geometry import Rect from komorebi_vm.core.platform import Client, Platform +# how long something that must not happen is waited for, in seconds (scaled for the host): a window +# a rule leaves alone, a window that stays where it is. It is more than the daemon takes to act on +# an event on either port, and the price of every such check +QUIET = 3 + def os_focused(platform: Platform, clients: list[Client]) -> str: """The title of the window the operating system says has the focus, among `clients`. @@ -15,6 +21,18 @@ def os_focused(platform: Platform, clients: list[Client]) -> str: return "" +def in_view(platform: Platform, clients: list[Client]) -> list[str]: + """The titles of the windows of `clients` that are on the screen: the operating system has + them, and the daemon has not put them away. Sorted. + + A window the system does not have is not in view, though `Platform.hidden` says no for it + too: a window that is gone must not count as one that is shown. + """ + return sorted( + c.title for c in clients if platform.os_window(c) is not None and not platform.hidden(c) + ) + + def positions(platform: Platform, clients: list[Client]) -> dict[str, tuple[int, int]]: """Where the operating system has each window, by title. @@ -32,3 +50,17 @@ def positions(platform: Platform, clients: list[Client]) -> dict[str, tuple[int, 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 + + +def layout_rect(platform: Platform, client: Client) -> Rect | None: + """The rectangle the daemon's layout gives the container of `client`, or `None` if the + first workspace has no such container. + + It is what the daemon asked for: the frame the operating system gives the window may be short + of it by `platform.tolerance`, and is what the scenario then compares it with. + """ + workspace = platform.state().workspace() + for i, stack in enumerate(workspace.containers): + if any(w.title == client.title for w in stack) and i < len(workspace.latest_layout): + return workspace.latest_layout[i] + return None diff --git a/e2e/lib/komorebi_vm/core/scenarios/tiling_off.py b/e2e/lib/komorebi_vm/core/scenarios/tiling_off.py index 7517fc73..79f3651c 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/tiling_off.py +++ b/e2e/lib/komorebi_vm/core/scenarios/tiling_off.py @@ -3,7 +3,7 @@ from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Client, Platform from komorebi_vm.core.scenarios.layouts import tiled -from komorebi_vm.core.scenarios.support import positions +from komorebi_vm.core.scenarios.support import QUIET, positions def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: @@ -20,7 +20,7 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: platform.komorebic("change-layout", "columns") checks.check( "... a layout change does not move them either", - not platform.wait_for(lambda: positions(platform, clients) != before, timeout=3), + not platform.wait_for(lambda: positions(platform, clients) != before, timeout=QUIET), ) platform.komorebic("toggle-tiling") diff --git a/e2e/lib/komorebi_vm/core/scenarios/title_rule.py b/e2e/lib/komorebi_vm/core/scenarios/title_rule.py new file mode 100644 index 00000000..37b47d26 --- /dev/null +++ b/e2e/lib/komorebi_vm/core/scenarios/title_rule.py @@ -0,0 +1,48 @@ +"""A rule that matches a title decides when the window has its title.""" + +from komorebi_vm.core.checks import Checks +from komorebi_vm.core.platform import Client, Platform + +PENDING = "pending-rule" +RENAMED = "renamed-rule" + + +def run(platform: Platform, checks: Checks) -> None: + """A window that opens with a title the ignore rule matches is left alone, and tiled once it + gives itself another title. + + The daemon runs with its windows tiled; the window is closed at the end, and the rule stays. + """ + platform.komorebic("ignore-rule", "title", PENDING) + before = platform.state().managed() + + # the window renames itself after the daemon has had time to decide about the first title + platform.spawn(PENDING, rename_to=RENAMED, after=6) + renamed = Client(RENAMED) + checks.check( + "a window the ignore rule matches by its title is left alone", + not platform.wait_for(lambda: platform.state().managed() != before, timeout=2) + and platform.os_window(Client(PENDING)) is not None, + ) + checks.check( + "once it has a title the rule does not match, it is tiled", + platform.wait_for( + lambda: ( + platform.os_window(renamed) is not None and platform.state().managed() == before + 1 + ), + timeout=30, + ), + ) + window = platform.os_window(renamed) + checks.check( + "... and inside the work area", + window is not None and window.frame.inside(platform.work_area(), 2), + ) + platform.close(renamed) + checks.check( + "closed, it leaves the daemon", + platform.wait_for( + lambda: platform.os_window(renamed) is None and platform.state().managed() == before, + timeout=10, + ), + ) diff --git a/e2e/lib/komorebi_vm/core/scenarios/workspace_moves.py b/e2e/lib/komorebi_vm/core/scenarios/workspace_moves.py index f63f95b2..c45db175 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/workspace_moves.py +++ b/e2e/lib/komorebi_vm/core/scenarios/workspace_moves.py @@ -4,11 +4,7 @@ away.""" from komorebi_vm.core.checks import Checks from komorebi_vm.core.platform import Client, Platform from komorebi_vm.core.scenarios.layouts import tiled -from komorebi_vm.core.scenarios.support import focus_agrees - - -def _in_view(platform: Platform, clients: list[Client]) -> list[str]: - return sorted(c.title for c in clients if not platform.hidden(c)) +from komorebi_vm.core.scenarios.support import focus_agrees, in_view def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: @@ -24,7 +20,7 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: platform.komorebic("move-to-workspace", "1") checks.check( "after 'move-to-workspace 1' the window is there, in view, and the others are put away", - platform.wait_for(lambda: _in_view(platform, clients) == [target.title], timeout=20), + platform.wait_for(lambda: in_view(platform, clients) == [target.title], timeout=20), ) checks.check( "... the daemon has it on workspace 1", @@ -38,18 +34,18 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: platform.komorebic("focus-last-workspace") checks.check( "'focus-last-workspace' brings the others back and puts the window away", - platform.wait_for(lambda: _in_view(platform, clients) == rest, timeout=20), + platform.wait_for(lambda: in_view(platform, clients) == rest, timeout=20), ) platform.komorebic("focus-last-workspace") checks.check( "... and again, it goes back to the window", - platform.wait_for(lambda: _in_view(platform, clients) == [target.title], timeout=20), + platform.wait_for(lambda: in_view(platform, clients) == [target.title], timeout=20), ) platform.komorebic("move-to-workspace", "0") checks.check( "'move-to-workspace 0' has every window in view again", - platform.wait_for(lambda: _in_view(platform, clients) == everyone, timeout=20), + platform.wait_for(lambda: in_view(platform, clients) == everyone, timeout=20), ) checks.check( "... tiled where the layout says", diff --git a/e2e/lib/komorebi_vm/core/scenarios/workspaces.py b/e2e/lib/komorebi_vm/core/scenarios/workspaces.py index 57c963c4..b2dc9991 100644 --- a/e2e/lib/komorebi_vm/core/scenarios/workspaces.py +++ b/e2e/lib/komorebi_vm/core/scenarios/workspaces.py @@ -3,11 +3,7 @@ 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)) +from komorebi_vm.core.scenarios.support import focus_agrees, in_view, os_focused def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: @@ -21,7 +17,7 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: 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) + "every window is in view", in_view(platform, clients) == sorted(c.title for c in clients) ) platform.komorebic("send-to-workspace", "1") @@ -35,15 +31,15 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: ) checks.check( "... and the others are still in view", - platform.wait_for(lambda: _in_view(platform, clients) == rest), + platform.wait_for(lambda: in_view(platform, clients) == rest), ) platform.komorebic("focus-workspace", "1") - platform.wait_for(lambda: _in_view(platform, clients) == [last.title]) - print(f" in view after the switch: {_in_view(platform, clients)}") + platform.wait_for(lambda: in_view(platform, clients) == [last.title]) + print(f" in view after the switch: {in_view(platform, clients)}") checks.check( "after 'focus-workspace 1' only the window sent there is in view", - platform.wait_for(lambda: _in_view(platform, clients) == [last.title]), + platform.wait_for(lambda: in_view(platform, clients) == [last.title]), ) checks.check( "... it has the focus, and the daemon agrees", @@ -53,7 +49,7 @@ def run(platform: Platform, checks: Checks, clients: list[Client]) -> None: 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), + platform.wait_for(lambda: in_view(platform, clients) == rest), ) checks.check( "... and one of them has the focus", diff --git a/e2e/lib/tests/fake_platform.py b/e2e/lib/tests/fake_platform.py index 98e26c5f..f50ded50 100644 --- a/e2e/lib/tests/fake_platform.py +++ b/e2e/lib/tests/fake_platform.py @@ -5,6 +5,7 @@ real daemon does with windows laid out left to right, so that a scenario can be that is right, and against ones that are wrong in one way. """ +import json from typing import Any from PIL import Image @@ -14,7 +15,21 @@ 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)] +SCREEN = Rect(0, 0, 1920, 1080) +# what a maximized window is not in, so that asking it does nothing +ASKED_OF_THE_LAYOUT = ( + "move", + "stack", + "unstack", + "cycle-move", + "promote", + "toggle-float", + "toggle-monocle", + "resize-edge", + "send-to-workspace", + "move-to-workspace", + "toggle-lock", +) def _place_index(place: str, count: int) -> int: @@ -60,8 +75,68 @@ class FakePlatform: follows_pointer: bool = True, reloads: bool = True, retiles_on_unlock: bool = True, + panel: int = 0, + ignores_panel: bool = False, + second: Rect | None = None, + follows_renames: bool = True, + honours_ignore: bool = True, + unmanages: bool = True, + manages: bool = True, + loads_resize: bool = True, + answers_queries: bool = True, + matches_class: bool = True, + applies_rules_on_event: bool = True, + clears_rules: bool = True, + cycles_in_monocle: bool = True, + no_op_in_monocle: bool = True, + follows_user_moves: bool = True, + resizable: bool = True, + follows_modes: bool = True, + keeps_fullscreen: bool = True, + leaves_hidden_on_crash: bool = False, + ignores_commands_when_maximized: bool = True, ) -> None: - self.tiles = list(TILES) + self.panel = panel + """The height of a panel along the bottom of the first display, which the work area leaves + out.""" + self.ignores_panel = ignores_panel + """A daemon that tiles on the whole display, under the panel.""" + self.second = second + """The rectangle of the second display, when it is not one of the first's size.""" + self.keeps_fullscreen = keeps_fullscreen + self.leaves_hidden_on_crash = leaves_hidden_on_crash + self.stuck: set[str] = set() + """The windows a daemon that crashed left out of sight, which no daemon found again.""" + self.ignores_commands_when_maximized = ignores_commands_when_maximized + self.fullscreened: str | None = None + self.max_home: tuple[int, int] | None = None + """Where the window the user maximized was, to put it back.""" + self.resizable = resizable + self.follows_modes = follows_modes + self.mode: dict[int, tuple[int, int]] = {} + """The mode of the displays that are not 1920 by 1080.""" + self.follows_user_moves = follows_user_moves + self.cycles_in_monocle = cycles_in_monocle + self.no_op_in_monocle = no_op_in_monocle + self.monocle_cycles = False + """The behaviour `monocle-focus-behaviour` set: focusing in a monocle cycles it.""" + self.applies_rules_on_event = applies_rules_on_event + self.clears_rules = clears_rules + self.matches_class = matches_class + self.loads_resize = loads_resize + self.answers_queries = answers_queries + self.saved: dict[str, list[Rect]] = {} + """The tiles of each resize that `save-resize` saved, by its path.""" + self.unmanages = unmanages + self.manages = manages + self.let_go: list[str] = [] + """The windows `unmanage` let go of, the last one at the end.""" + self.follows_renames = follows_renames + self.honours_ignore = honours_ignore + self.clock = 0.0 + self.renames: list[tuple[float, str, str]] = [] + """The windows that will give themselves a title: when, the old one, the new one.""" + self.tiles = self._base() self.has_pointer = pointer self.follows_pointer = follows_pointer self.spaces: list[list[list[str]]] = [[], [], []] @@ -108,6 +183,26 @@ class FakePlatform: self.moves = moves self.focus_follows_move = focus_follows_move + @property + def area(self) -> Rect: + """What windows may take of the first display.""" + return Rect(0, 0, SCREEN.w, SCREEN.h - self.panel) + + @property + def tiled_area(self) -> Rect: + """What the daemon tiles on: the work area, or the display for a daemon that ignores the + panel.""" + return SCREEN if self.ignores_panel else self.area + + def _base(self) -> list[Rect]: + a = self.tiled_area + return [Rect(i * a.w // 3, 0, a.w // 3, a.h) for i in range(3)] + + def crash(self) -> None: + if self.leaves_hidden_on_crash: + self.stuck = {t for stack in self.containers for t in stack if self.hidden(Client(t))} + self.running = False + def has(self, feature: str) -> bool: return feature == "lock" or (feature == "pointer" and self.has_pointer) @@ -122,6 +217,10 @@ class FakePlatform: def move_window(self, client: Client, x: int, y: int) -> None: here = self.os_window(client) assert here is not None + target = min(max(x, 0) // 1920, self.display_count - 1) + if self.follows_user_moves and target != self.display_of.get(client.title, 0): + self.display_of[client.title] = target + return self.moved[client.title] = Rect(x, y, here.frame.w, here.frame.h) @property @@ -134,15 +233,35 @@ class FakePlatform: if not self.follows_pointer: return for i, tile in enumerate(self.tiles[:-1]): - if abs(start[0] - (tile.x + tile.w + 4)) <= 1: + right_of_it = abs(start[0] - (tile.x + tile.w + 4)) <= 1 + left_of_next = abs(start[0] - (self.tiles[i + 1].x - 4)) <= 1 + if right_of_it or left_of_next: a, b = tile, self.tiles[i + 1] self.tiles[i] = Rect(a.x, a.y, a.w + dx, a.h) self.tiles[i + 1] = Rect(b.x + dx, b.y, b.w - dx, b.h) return def wait_for(self, predicate: Any, timeout: float = 10) -> bool: + """Time passes by `timeout`, and the windows that were to rename themselves have.""" + self.clock += timeout + for entry in [r for r in self.renames if r[0] <= self.clock]: + self.renames.remove(entry) + self._rename(entry[1], entry[2]) return bool(predicate()) + def _rename(self, old: str, new: str) -> None: + for table in (self.exes, self.classes): + if old in table: + table[new] = table.pop(old) + if old not in self.unmanaged or not self.follows_renames: + for stack in [s for cs in self.spaces for s in cs]: + stack[:] = [new if t == old else t for t in stack] + self.unmanaged[:] = [new if t == old else t for t in self.unmanaged] + return + self.unmanaged.remove(old) + self.containers.append([new]) + self._relayout() + def start_komorebi(self) -> None: """A new daemon knows nothing: every window is tiled on the first workspace.""" everyone = [t for containers in self.spaces for stack in containers for t in stack] @@ -172,7 +291,16 @@ class FakePlatform: """The titles in view, in the order of the tiles.""" return [stack[0] for stack in self.containers] - def spawn(self, title: str, app_id: str | None = None, exe: str | None = None) -> Client: + def spawn( + self, + title: str, + app_id: str | None = None, + exe: str | None = None, + rename_to: str | None = None, + after: float = 0, + ) -> Client: + if rename_to is not None: + self.renames.append((self.clock + after, title, rename_to)) self.exes[title] = exe or "foot" self.classes[title] = app_id or "" forced = ( @@ -199,7 +327,7 @@ class FakePlatform: if self.paused: self.unmanaged.append(title) return Client(title) - if any(title.startswith(i) for i in self.ignored): + if self.honours_ignore and any(title.startswith(i) for i in self.ignored): self.unmanaged.append(title) elif title in self.initial_rules: self.spaces[self.initial_rules.pop(title)].append([title]) @@ -211,8 +339,11 @@ class FakePlatform: self._place(title) else: self.containers.append([title]) - if len(self.containers) > len(self.tiles): - self._relayout() + self._relayout() + if not self.keeps_fullscreen: + self.fullscreened = None + if self.applies_rules_on_event: + self.komorebic("enforce-workspace-rules") return Client(title) def _place(self, title: str) -> None: @@ -224,8 +355,11 @@ class FakePlatform: if isinstance(rules, dict): for place, matches in rules.items(): for match in matches if isinstance(matches, list) else [matches]: + if match["kind"] == "Class" and not self.matches_class: + continue equals = match["matching_strategy"] == "Equals" - if (title == match["id"]) if equals else (match["id"] in title): + value = self.classes.get(title, "") if match["kind"] == "Class" else title + if (value == match["id"]) if equals else (match["id"] in value): index = _place_index(place, n) elif rules is not None: index = 0 if rules == "Primary" else int(rules) - 1 @@ -279,7 +413,26 @@ class FakePlatform: raise KeyError(title) def displays(self) -> list[Rect]: - return [Rect(i * 1920, 0, 1920, 1080) for i in range(self.display_count)] + return [SCREEN, *self._others()][: self.display_count] + + def resizable_display(self) -> int | None: + return self.display_count - 1 if self.resizable and self.display_count > 1 else None + + def resize_display(self, index: int, width: int, height: int) -> None: + self.mode[index] = (width, height) + + def _others(self) -> list[Rect]: + """The displays after the first, side by side to its right.""" + found = [] + x = SCREEN.w + for n in range(1, max(self.display_count, 1)): + size = self.second if self.second is not None and n == 1 else SCREEN + width, height = (size.w, size.h) + if self.follows_modes: + width, height = self.mode.get(n, (width, height)) + found.append(Rect(x, 0, width, height)) + x += width + return found def add_display(self) -> None: self.display_count += 1 @@ -312,24 +465,28 @@ class FakePlatform: def _relayout(self) -> None: """The tiles of each workspace share the work area in equal columns.""" - self.tiles = list(TILES) + base = self._base() + self.tiles = list(base) n = len(self.containers) if n: + area = self.tiled_area w, c = self.workspace_padding, self.container_padding - width = (1920 - 2 * w) // n + width = (area.w - 2 * w) // n self.tiles = [ - Rect(w + i * width + c, w + c, width - 2 * c, 1080 - 2 * w - 2 * c) + Rect(w + i * width + c, w + c, width - 2 * c, area.h - 2 * w - 2 * c) for i in range(n) - ] + list(TILES[n:]) + ] + list(base[n:]) if self.flipped: - self.tiles = [Rect(1920 - t.x - t.w, t.y, t.w, t.h) for t in self.tiles[:n]] + list( - TILES[n:] - ) + self.tiles = [ + Rect(area.w - t.x - t.w, t.y, t.w, t.h) for t in self.tiles[:n] + ] + list(base[n:]) def _container(self, title: str) -> int: return self._find(title)[1] def hidden(self, client: Client) -> bool: + if client.title in self.stuck: + return True if client.title in self.floats or client.title in self.minimized: return False if client.title in self.unmanaged: @@ -339,7 +496,27 @@ class FakePlatform: return s != self.current or self.spaces[s][i][0] != client.title or away def work_area(self) -> Rect: - return Rect(0, 0, 1920, 1080) + return self.area + + def fullscreen(self, client: Client, on: bool = True) -> None: + self.fullscreened = client.title if on else None + + def user_maximize(self, client: Client, on: bool = True) -> None: + if on: + self.max_home = self._find(client.title) + self._find_remove(client.title) + self.maximized = client.title + self.focus = max(0, min(self.focus, len(self.containers) - 1)) + elif self.maximized == client.title: + self._restore_maximized() + self._relayout() + + def _restore_maximized(self) -> None: + if self.max_home is not None and self.maximized is not None: + space, index = self.max_home + self.spaces[space].insert(min(index, len(self.spaces[space])), [self.maximized]) + self.max_home = None + self.maximized = None def minimize(self, client: Client) -> None: self._find_remove(client.title) @@ -362,9 +539,14 @@ class FakePlatform: def exe_id(self, program: str) -> str: return program + def temp_path(self, name: str) -> str: + return f"/tmp/{name}" + def os_window(self, client: Client) -> OsWindow | None: - if client.title == self.maximized: + if client.title == self.fullscreened: return OsWindow(client.title, Rect(0, 0, 1920, 1080), focused=True) + if client.title == self.maximized: + return OsWindow(client.title, self.tiled_area, focused=True) if client.title in self.minimized: return OsWindow(client.title, Rect(0, 0, 0, 0), focused=False) if client.title in self.floats: @@ -376,15 +558,24 @@ class FakePlatform: except KeyError: return None if self.monocle == client.title: - return OsWindow(client.title, Rect(0, 0, 1920, 1080), focused=True) + return OsWindow(client.title, self.tiled_area, focused=True) focused = ( s == self.current and i == self.focuses[s] and self.spaces[s][i][0] == client.title ) - tile = self.tiles[i] - shift = 1920 * self.display_of.get(client.title, 0) + elsewhere = self.display_of.get(client.title, 0) + rank = sum( + 1 + for stack in self.spaces[s][:i] + if stack and self.display_of.get(stack[0], 0) == elsewhere + ) + tile = self.tiles[rank] if client.title in self.moved: return OsWindow(client.title, self.moved[client.title], focused=focused) - return OsWindow(client.title, Rect(tile.x + shift, tile.y, tile.w, tile.h), focused=focused) + if elsewhere: + d = self.displays()[elsewhere] + frame = Rect(d.x + tile.x, d.y + tile.y, min(tile.w, d.w), min(tile.h, d.h)) + return OsWindow(client.title, frame, focused=focused) + return OsWindow(client.title, tile, 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.""" @@ -399,6 +590,10 @@ class FakePlatform: def komorebic(self, *args: str) -> str: n = len(self.containers) + # a daemon that is wrong obeys one of them, to be told by the windows that moved + obeyed = not self.ignores_commands_when_maximized and args[0] == "promote" + if self.maximized is not None and args[0] in ASKED_OF_THE_LAYOUT and not obeyed: + return "" match args: case ("stop",): self.running = False @@ -406,6 +601,13 @@ class FakePlatform: self.follows_mouse = state == "enable" and not self.mouse_ignored case ("toggle-focus-follows-mouse", *_): self.follows_mouse = not self.follows_mouse and not self.mouse_ignored + case ("monocle-focus-behaviour", way): + self.monocle_cycles = way == "cycle" + case ("focus", "right") if self.monocle is not None: + cycles = self.monocle_cycles if self.no_op_in_monocle else True + if cycles and self.cycles_in_monocle: + self.focus = (self.focus + 1) % n + self.monocle = self.containers[self.focus][0] case ("focus", "right"): self.focus = min(self.focus + 1, n - 1) case ("focus", "left"): @@ -433,8 +635,8 @@ 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 ("change-layout", name): + self.layout_name = "BSP" if name == "bsp" else name.title() case ("send-to-monitor", _): pass case ("move-to-monitor", number): @@ -444,11 +646,18 @@ class FakePlatform: 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": + if args[0] == "clear-all-workspace-rules" and self.clears_rules: self.class_rules.clear() self.exe_rules.clear() self.rules.clear() self.initial_rules.clear() + case ("global-state",): + rules = [*self.rules, *self.initial_rules, *self.class_rules, *self.exe_rules] + return json.dumps({"workspace_rules": rules}) + case ("workspace-name", _, index, name): + self.names[int(index)] = name + case ("named-workspace-rule", "title", title, name): + self.rules[title] = self.names.index(name) case ("initial-workspace-rule", "title", title, _, number): self.initial_rules[title] = int(number) case ("workspace-rule", "title", title, _, number): @@ -490,7 +699,11 @@ class FakePlatform: self.container_padding = int(size) self._relayout() case ("toggle-maximize",): - self.maximized = None if self.maximized else self.containers[self.focus][0] + if self.maximized is not None: + self._restore_maximized() + self._relayout() + else: + self.maximized = self.containers[self.focus][0] case ("resize-axis", "horizontal", way): d = 50 if way == "increase" else -50 i = self.focus @@ -504,6 +717,35 @@ class FakePlatform: case ("flip-layout", "horizontal"): self.flipped = not self.flipped self._relayout() + case ("query", name): + return self._answer(name) + case ("quick-save-resize",): + self.saved["quick"] = list(self.tiles) + case ("quick-load-resize",): + self._load_resize("quick") + case ("save-resize", path): + self.saved[path] = list(self.tiles) + case ("load-resize", path): + self._load_resize(path) + case ("retile",): + self._relayout() + case ("minimize",): + self.minimize(Client(self.containers[self.focus][0])) + case ("unmanage",): + title = self.containers[self.focus][0] + if self.unmanages: + self._find_remove(title) + self.unmanaged.append(title) + self.let_go.append(title) + self.focus = max(0, min(self.focus, len(self.containers) - 1)) + self._relayout() + case ("manage",): + if self.let_go and self.manages: + title = self.let_go.pop() + self.unmanaged.remove(title) + self.containers.append([title]) + self.focus = len(self.containers) - 1 + self._relayout() case ("toggle-pause",): self.paused = not self.paused case ("toggle-tiling",): @@ -524,6 +766,25 @@ class FakePlatform: raise AssertionError(f"the fake does not know komorebic {args}") return "" + def _load_resize(self, key: str) -> None: + if self.loads_resize and key in self.saved: + self.tiles = list(self.saved[key]) + + def _answer(self, name: str) -> str: + if not self.answers_queries: + return "0" + stack = self.containers[self.focus] if self.containers else [] + return { + "focused-monitor-index": "0", + "focused-workspace-index": str(self.current), + "focused-container-index": str(self.focus), + "focused-window-index": "0", + "focused-workspace-name": self.names[self.current] or str(self.current), + "focused-workspace-layout": self.layout_name, + "focused-container-kind": "Stack" if len(stack) > 1 else "Single", + "version": "0.1.0", + }[name] + def _swap(self, other: int) -> None: if not self.moves: return @@ -556,7 +817,7 @@ class FakePlatform: floats = self.floats if current else [] monocle = None if current and self.monocle is not None: - whole = Rect(0, 0, 1920, 1080) + whole = self.tiled_area windows = {"elements": [window(self.monocle, whole)], "focused": 0} monocle = {"id": "m", "locked": False, "windows": windows} return { @@ -577,9 +838,7 @@ class FakePlatform: }, "monocle_container": monocle, "maximized_window": ( - window(self.maximized, Rect(0, 0, 1920, 1080)) - if current and self.maximized - else None + window(self.maximized, self.tiled_area) if current and self.maximized else None ), "floating_windows": { "elements": [window(t, Rect(300, 300, 600, 400)) for t in floats], @@ -592,12 +851,23 @@ class FakePlatform: "latest_layout": [rect(r) for r in self.tiles[: len(containers)]], } + def on_display(stacks: list[list[str]], display: int) -> list[list[str]]: + # a stack with no window is the first display's + return [ + stack + for stack in stacks + if (self.display_of.get(stack[0], 0) if stack else 0) == display + ] + monitor = { "id": 1, - "size": rect(Rect(0, 0, 1920, 1080)), + "size": rect(SCREEN), + "work_area_size": rect(self.area), "workspaces": { "elements": [ - workspace(i, c, f, i == self.current) + workspace( + i, on_display(c, 0), min(f, len(on_display(c, 0)) - 1), i == self.current + ) for i, (c, f) in enumerate(zip(self.spaces, self.focuses, strict=True)) ], "focused": self.current, @@ -606,8 +876,11 @@ class FakePlatform: extra = [ { "id": n + 1, - "size": rect(Rect(n * 1920, 0, 1920, 1080)), - "workspaces": {"elements": [workspace(0, [], 0, False)], "focused": 0}, + "size": rect(self._others()[n - 1]), + "workspaces": { + "elements": [workspace(0, on_display(self.containers, n), 0, False)], + "focused": 0, + }, } for n in range(1, 1 if self.forgets_displays else self.display_count) ] diff --git a/e2e/lib/tests/test_focus_moving.py b/e2e/lib/tests/test_focus_moving.py index f14fc691..466cd75a 100644 --- a/e2e/lib/tests/test_focus_moving.py +++ b/e2e/lib/tests/test_focus_moving.py @@ -2,7 +2,7 @@ from komorebi_vm.core.checks import Checks from komorebi_vm.core.geometry import Rect -from komorebi_vm.core.platform import OsWindow +from komorebi_vm.core.platform import Client, OsWindow from komorebi_vm.core.scenarios import ( closing, commands, @@ -72,6 +72,23 @@ def test_a_move_that_loses_the_focus_fails() -> None: assert any("keeps the focus" in f for f in checks.failures) +def test_a_window_that_is_gone_is_not_in_view_for_workspaces() -> None: + """`hidden` is false for a window the system does not have, which is not one that is shown.""" + + class Vanishes(FakePlatform): + def os_window(self, client: Client) -> OsWindow | None: + return None if client.title == "win1" else super().os_window(client) + + def hidden(self, client: Client) -> bool: + return False if client.title == "win1" else super().hidden(client) + + platform = Vanishes() + checks = Checks() + clients = opened(platform, checks) + workspaces.run(platform, checks, clients) + assert any("in view" in f for f in checks.failures) + + def test_a_daemon_that_is_right_passes_stacks() -> None: platform = FakePlatform() checks = Checks() @@ -308,6 +325,26 @@ def test_a_daemon_that_does_not_resize_fails_resize_commands() -> None: assert checks.failed > 0 +def test_a_decrease_that_gives_back_less_than_the_increase_fails_resize_commands() -> None: + """Within what a terminal rounds to (24 px), so the window alone cannot tell.""" + + class Short(FakePlatform): + def komorebic(self, *args: str) -> str: + if args == ("resize-axis", "horizontal", "decrease"): + i = self.focus + a, b = self.tiles[i], self.tiles[i + 1] + self.tiles[i] = Rect(a.x, a.y, a.w - 30, a.h) + self.tiles[i + 1] = Rect(b.x - 30, b.y, b.w + 30, b.h) + return "" + return super().komorebic(*args) + + platform = Short() + checks = Checks() + clients = opened(platform, checks) + resize_commands.run(platform, checks, clients) + assert any("the layout gives it the width it had" in f for f in checks.failures) + + def test_a_daemon_that_is_right_passes_promoting() -> None: platform = FakePlatform() checks = Checks() @@ -538,7 +575,7 @@ def test_a_daemon_that_shows_what_a_window_was_given_passes_state_fidelity() -> def test_a_daemon_that_loses_the_class_fails_state_fidelity() -> None: class Forgetful(FakePlatform): - def spawn(self, title, app_id=None, exe=None): # noqa: ANN001, ANN202 + def spawn(self, title, app_id=None, exe=None, rename_to=None, after=0): # noqa: ANN001, ANN202 client = super().spawn(title, app_id=None, exe=exe) return client @@ -781,3 +818,103 @@ def test_focus_follows_mouse_is_skipped_without_a_pointer() -> None: base = checks.passed focus_follows_mouse.run(platform, checks, clients[0], clients[1]) assert checks.failed == 0 and checks.passed == base + + +def test_a_daemon_that_tiles_inside_the_work_area_passes_with_a_panel() -> None: + platform = FakePlatform(panel=40) + checks = Checks() + clients = opened(platform, checks) + for scenario in (monocle, maximizing, layouts, floating, flipping, closing): + if scenario is closing: + closing.run(platform, checks, clients, clients[0]) + else: + scenario.run(platform, checks, clients) + assert platform.work_area().h == 1040 + assert checks.failed == 0, checks.failures + assert checks.passed > 20 + + +def test_a_daemon_that_tiles_under_the_panel_fails_tiling() -> None: + platform = FakePlatform(panel=40, ignores_panel=True) + checks = Checks() + opened(platform, checks) + assert any("inside the work area" in f for f in checks.failures) + + +def test_a_window_that_is_maximized_past_the_work_area_fails_maximizing() -> None: + platform = FakePlatform(panel=40, ignores_panel=True) + checks = Checks() + clients = [platform.spawn(t) for t in ("a", "b", "c")] + maximizing.run(platform, checks, clients) + assert any("without going past the work area" in f for f in checks.failures) + + +def test_a_window_in_monocle_past_the_work_area_fails_monocle() -> None: + platform = FakePlatform(panel=40, ignores_panel=True) + checks = Checks() + clients = [platform.spawn(t) for t in ("a", "b", "c")] + monocle.run(platform, checks, clients) + assert any("without going past the work area" in f for f in checks.failures) + + +def test_a_second_display_of_another_size_passes_hotplug() -> None: + platform = FakePlatform(second=Rect(0, 0, 1280, 800)) + checks = Checks() + clients = opened(platform, checks) + hotplug.run(platform, checks, clients) + assert platform.displays()[1] == Rect(1920, 0, 1280, 800) + assert checks.failed == 0, checks.failures + + +def test_focus_follows_mouse_is_driven_without_naming_an_implementation() -> None: + """The implementation is a port's own: the scenario leaves it to the command's default.""" + + class Records(FakePlatform): + def __init__(self) -> None: + super().__init__() + self.said: list[tuple[str, ...]] = [] + + def komorebic(self, *args: str) -> str: + self.said.append(args) + return super().komorebic(*args) + + platform = Records() + checks = Checks() + clients = opened(platform, checks) + focus_follows_mouse.run(platform, checks, clients[0], clients[2]) + assert checks.failed == 0, checks.failures + assert not [a for a in platform.said if "--implementation" in a] + + +def test_the_window_is_moved_inside_the_work_area_of_the_platform_while_locked() -> None: + class Records(FakePlatform): + def __init__(self) -> None: + super().__init__(panel=40) + self.targets: list[tuple[int, int]] = [] + + def move_window(self, client: Client, x: int, y: int) -> None: + self.targets.append((x, y)) + super().move_window(client, x, y) + + platform = Records() + checks = Checks() + clients = opened(platform, checks) + locking.run(platform, checks, clients) + assert checks.failed == 0, checks.failures + (x, y) = platform.targets[0] + assert platform.work_area().x <= x < platform.work_area().w + assert platform.work_area().y <= y < platform.work_area().h + + +def test_a_platform_that_cannot_move_a_window_while_locked_fails_locking() -> None: + """Else the check that the window is back in its tile after the unlock is a vacuous one.""" + + class Cannot(FakePlatform): + def move_window(self, client: Client, x: int, y: int) -> None: + pass + + platform = Cannot() + checks = Checks() + clients = opened(platform, checks) + locking.run(platform, checks, clients) + assert any("was moved while the screen was locked" in f for f in checks.failures) diff --git a/e2e/lib/tests/test_tiling.py b/e2e/lib/tests/test_tiling.py index 283f705f..5badece6 100644 --- a/e2e/lib/tests/test_tiling.py +++ b/e2e/lib/tests/test_tiling.py @@ -21,7 +21,14 @@ class FakePlatform: def wait_for(self, predicate, timeout: float = 10) -> bool: # noqa: ANN001 return predicate() - def spawn(self, title: str, app_id: str | None = None, exe: str | None = None) -> Client: + def spawn( + self, + title: str, + app_id: str | None = None, + exe: str | None = None, + rename_to: str | None = None, + after: float = 0, + ) -> Client: self.opened.append(title) return Client(title) @@ -47,6 +54,12 @@ class FakePlatform: def remove_display(self) -> None: pass + def resizable_display(self) -> int | None: + return None + + def resize_display(self, index: int, width: int, height: int) -> None: + pass + def komorebic_status(self, *args: str) -> tuple[int, str]: return 0, "" @@ -66,12 +79,18 @@ class FakePlatform: def restart_with(self, config: dict) -> None: pass + def crash(self) -> None: + pass + def komorebic(self, *args: str) -> str: return "" def exe_id(self, program: str) -> str: return program + def temp_path(self, name: str) -> str: + return f"/tmp/{name}" + def minimize(self, client: Client) -> None: pass @@ -90,6 +109,12 @@ class FakePlatform: def activate(self, client: Client) -> None: pass + def fullscreen(self, client: Client, on: bool = True) -> None: + pass + + def user_maximize(self, client: Client, on: bool = True) -> None: + pass + def screenshot(self, name: str) -> Image.Image: return Image.new("RGB", (4, 4))