diff --git a/nix/tests/vm/keys-corpus.py b/nix/tests/vm/keys-corpus.py index af216a76..88c07afe 100644 --- a/nix/tests/vm/keys-corpus.py +++ b/nix/tests/vm/keys-corpus.py @@ -4,37 +4,15 @@ # from the system profile; Alt+, cannot, so the module's daemon registers it and runs it. The Rust # tests and `keybindings-fixtures` check the plan; only a real session can say that what the # module builds and starts runs on a key, from each of the three formats. -from komorebi_vm import Checks, Kde, Keys + +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import keys_corpus as kde_keys_corpus start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) -keys = Keys(machine) - - -def ran(marker: str) -> bool: - return machine.execute(f"test -e /tmp/{marker}")[0] == 0 - - -def press(combo: str, marker: str) -> bool: - keys.send(combo) - return kde.wait_for(lambda: ran(marker), timeout=10) - - -shortcuts = machine.succeed("ls /run/current-system/sw/share/kglobalaccel") -checks.check( - "the module installed the static shortcut in the system profile", - "komorebi-touch-tmp-keys-corpus-alt-j.desktop" in shortcuts.split(), -) -checks.check( - "the module's daemon registered the key of the engine, and only that one", - kde.wait_for(lambda: kde.shortcut_actions() == ["Alt+,"], timeout=60), -) -checks.check("Alt+J runs its command, as a static shortcut", press("alt-j", "keys-corpus-alt-j")) -checks.check( - "Alt+, runs its command, through the engine", press("alt-comma", "keys-corpus-alt-comma") -) +run_suite(checks, platform_only("kde", kde_keys_corpus.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/check.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/check.py new file mode 100644 index 00000000..cdacabea --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/check.py @@ -0,0 +1,225 @@ +r"""`komorebic check` against a real (headless) KWin: what it finds of the desktop, and what it says +when something is missing: no Plasma shell for the wallpapers, a stock effect shadowing komorebi's +own, komorebi without its script in KWin, komorebi not running, no KWin on the bus. What only a +real KWin can tell: that its version is read from what KWin says of itself, that the effects are +komorebi's builds because of what they contain, that a daemon is told from its script by KWin's +own answer, that a bus with no KWin on it is an error with an exit status that says so, and that +the shortcut files the check compares with are in the directory `komorebic hotkeys compile` +writes to in a session. The configuration and the exit status are covered by +`komorebi/src/check.rs` and `komorebic/tests/check.rs`, against no desktop. +""" + +import base64 +import json +import re +import shlex +import struct +import zlib +from typing import Any + +from komorebi_vm import Checks, Kde + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `check`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.headless(machine, "main", size=(1920, 1080), scale=SCALE) + + CONFIG = "/tmp/check-config.json" + EMPTY_BUS = "/tmp/check-empty.bus" + FLAT = "/tmp/check-flat.png" + + def flat_png() -> bytes: + """A picture of one color all over: a wallpaper no theme can be made from.""" + raw = b"".join(b"\x00" + bytes([200, 40, 40]) * 8 for _ in range(8)) + + def chunk(kind: bytes, data: bytes) -> bytes: + body = kind + data + return ( + struct.pack(">I", len(data)) + + body + + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF) + ) + + header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0) + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(raw)) + + chunk(b"IEND", b"") + ) + + kde.sh(f"echo {base64.b64encode(flat_png()).decode()} | base64 -d > {FLAT}") + # borders and animation, which want their effects; a wallpaper, which wants the Plasma shell and + # cannot make a theme; one workspace that is a layout and one that is only a name, which komorebi + # does not tile + kde.sh( + "printf %s " + + shlex.quote( + json.dumps( + { + "border": True, + "animation": {"enabled": True, "style": "Linear"}, + "monitors": [ + { + "wallpaper": {"path": FLAT}, + "workspaces": [{"name": "a", "layout": "BSP"}, {"name": "b"}], + } + ], + } + ) + ) + + f" > {CONFIG}" + ) + + def check(bus: str | None = None, data_home: str | None = None) -> tuple[int, str]: + """Runs `komorebic check` on the session's bus, or on the bus at `bus`, with `data_home` as the + user's data directory when KWin's environment does not name one.""" + prefix = f"DBUS_SESSION_BUS_ADDRESS=unix:path={bus} " if bus else "" + prefix += f"XDG_DATA_HOME={data_home} " if data_home else "" + status, out = kde.run(f"{prefix}komorebic check --komorebi-config {CONFIG}") + print(out) + return status, out + + print("== 1. a desktop that is as it should be, with komorebi running") + kde.start_komorebi("--config", CONFIG) + checks.check( + "the daemon answers komorebic", + kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=30), + ) + checks.check("its script is in KWin", kde.wait_for(kde.script_loaded, timeout=30)) + status, out = check() + checks.check("it passes: no errors", status == 0 and "\n0 error(s)" in out) + checks.check( + "it knows this is a KDE Plasma session on Wayland", + "this is a KDE Plasma session" in out and "it is a Wayland session" in out, + ) + checks.check("it knows KWin 6", re.search(r"ok +KWin 6\.", out) is not None) + checks.check( + "it sees komorebi, and its script in KWin", + "komorebi is running, and its script is in KWin" in out, + ) + checks.check( + "it says what starts komorebi at login", + re.search(r"ok +komorebi is started at login by ", out) is not None, + ) + checks.check( + "the border effect is komorebi's build", + "the border effect is komorebi's build" in out, + ) + checks.check( + "the animation effect is komorebi's build", + "the animation effect is komorebi's build" in out, + ) + checks.check( + "the configuration is read, and the workspace that is only a name is found", + 'workspace 1 of monitor 0 ("b") has no `layout`' in out, + ) + checks.check( + "wallpapers need the Plasma shell, which a headless KWin does not have", + "the Plasma shell is not on the bus" in out, + ) + checks.check( + "a picture of one color cannot make a theme", + f"no theme can be made from {FLAT}" in out, + ) + + print("== 2. the stock animation effect in the user's own directory hides komorebi's") + DATA = "/tmp/check-data" + STOCK = f"{DATA}/kwin/effects/kwin4_effect_geometry_change/contents/code" + kde.sh(f"mkdir -p {STOCK} && echo 'curve: QEasingCurve.OutExpo' > {STOCK}/main.js") + status, out = check(data_home=DATA) + checks.check( + "the effect is the stock one, and the style is ignored", + 'the animation effect is the stock one: `animation.style` "Linear" is ignored' in out, + ) + checks.check("and it says which copy hides which", "shadows" in out) + kde.sh(f"rm -rf {DATA}") + + print("== 3. komorebi is running and its script is not in KWin") + kde.sh( + "busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting unloadScript s komorebi-bridge" + ) + checks.check("KWin has let the script go", kde.wait_for(lambda: not kde.script_loaded())) + status, out = check() + checks.check( + "it is an error, and the exit status says so", + status == 1 + and re.search(r"error +komorebi is running but its script is not in KWin", out) is not None, + ) + + print("== 4. komorebi is not running") + kde.stop_komorebi() + checks.check("the daemon is gone", kde.wait_for(lambda: not kde.komorebi_running(), timeout=30)) + status, out = check() + checks.check( + "a note, not an error", + status == 0 and re.search(r"note +komorebi is not running", out) is not None, + ) + + print("== 5. there is no KWin on the bus") + pid = kde.sh( + f"dbus-daemon --session --address=unix:path={EMPTY_BUS} --fork --print-pid" + ).strip() + status, out = check(EMPTY_BUS) + kde.run(f"kill {pid}") + checks.check( + "KWin missing is an error, and the desktop is looked at no further", + status == 1 + and "KWin is not on the session bus" in out + and "komorebi is running" not in out + and "komorebi is not running" not in out, + ) + + print("== 6. the key bindings") + KEYS_HOME = "/tmp/check-keys-home" + SHORTCUTS = "~/.local/share/kglobalaccel" + STALE = "[Desktop Entry]\nX-Komorebi-Generated=true\n" + + def check_keys() -> tuple[int, str]: + """Runs `komorebic check` on the key bindings alone, in a config home of their own.""" + status, out = kde.run( + f"KOMOREBI_CONFIG_HOME={KEYS_HOME} komorebic check --configuration-only" + ) + print(out) + return status, out + + kde.sh(f"mkdir -p {KEYS_HOME}") + status, out = check_keys() + checks.check( + "without a key binding file it is a note, not an error", + status == 0 + and re.search(r"note +there is no skhdrc, whkdrc or sxhkdrc in ", out) is not None, + ) + + kde.sh( + "printf %s " + + shlex.quote("alt - h : komorebic focus left\nalt - nosuchkey : komorebic focus up\n") + + f" > {KEYS_HOME}/skhdrc" + ) + status, out = check_keys() + checks.check( + "the file is read, and the line it cannot read is a warning that does not fail the check", + status == 0 + and "skhdrc has 1 key binding" in out + and re.search(r"warning +1 line of it cannot be read and left out", out) is not None, + ) + + # a shortcut file komorebi wrote that the file does not call for, in the directory of the session + kde.sh( + f"mkdir -p {SHORTCUTS} && printf %s {shlex.quote(STALE)} > {SHORTCUTS}/komorebi-stale.desktop" + ) + status, out = check_keys() + checks.check( + "it says the shortcut files are not the ones `hotkeys compile` would write", + status == 0 + and "the shortcut files are not the ones `komorebic hotkeys compile` would write" in out, + ) + kde.sh(f"KOMOREBI_CONFIG_HOME={KEYS_HOME} komorebic hotkeys compile") + status, out = check_keys() + checks.check( + "after `hotkeys compile` it does not: both use the directory of the session", + status == 0 and "are not the ones" not in out, + ) + + kde.stop() diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/client_geometry.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/client_geometry.py new file mode 100644 index 00000000..dc1ffa2c --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/client_geometry.py @@ -0,0 +1,98 @@ +r"""How real clients answer the frame komorebi asks for. KWin carries out a request at once; the +client then decides the size it draws at, and that is the frame KWin reports. What only real +clients can tell, and what the fake desktop of the Rust tests cannot know: Qt and KDE programs +and X11 programs on XWayland take the frame exactly, also below the minimum size they report; +foot sizes itself down to whole cells of its font; GTK 4 programs and Firefox never go below +their minimum size. Every client keeps the position komorebi asked for. The output is large +enough that some tiles are bigger and some smaller than the clients' minimums. +""" + +from typing import Any + +from komorebi_vm import Checks, Kde, Rect, daemon + +W, H = 3840, 2160 +CELL = 24 + +EXACT = ["org.kde.konsole", "org.kde.kate", "org.kde.dolphin", "XTerm"] +WHOLE_CELLS = ["foot"] +NOT_BELOW_MINIMUM = ["org.gnome.TextEditor", "org.gnome.Calculator", "firefox"] + +CLIENTS = { + "foot": "foot -T foot-term sleep 3000", + "org.kde.konsole": "konsole --separate", + "org.kde.dolphin": "dolphin --new-window /tmp", + "org.kde.kate": "kate --new", + "org.gnome.TextEditor": "gnome-text-editor --new-window", + "org.gnome.Calculator": "gnome-calculator", + "XTerm": "xterm -T xterm-x11", + "firefox": "firefox --no-remote --profile /tmp/firefox-profile about:blank", +} + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `client-geometry`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.headless(machine, "main", size=(W, H), xwayland=True, scale=SCALE) + kde.as_user("mkdir -p /tmp/firefox-profile") + kde.start_komorebi() + checks.check( + "the daemon loaded its script into KWin", + kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30), + ) + + for app, command in CLIENTS.items(): + kde.spawn(command, log=f"/tmp/{app}.log") + up = kde.wait_for(lambda app=app: kde.wid_by_class(app) != "", timeout=120) + if not checks.check(f"{app} has a window", up): + print(machine.execute(f"cat /tmp/{app}.log")[1]) + + def shown() -> int: + return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show") + + checks.check("the daemon tiles all eight", kde.wait_for(lambda: shown() >= 8, timeout=60)) + + def show(r: Rect | None) -> str: + return "-" if r is None else f"{r.x},{r.y} {r.w}x{r.h}" + + def snapshot() -> dict[str, Rect]: + return {app: kde.rect(kde.wid_by_class(app)) for app in CLIENTS} + + # the clients answer in their own time; the frames are final once they stop changing + before: dict[str, Rect] = {} + + def still() -> bool: + nonlocal before + now = snapshot() + unchanged = now == before + before = now + return unchanged + + kde.wait_for(still, timeout=60, interval=3) + requests = list(daemon.requests(kde.komorebi_log()).values()) + + print(f" {'client':<22} {'asked':<22} {'has':<22}") + for app, have in snapshot().items(): + asked = [r for r in requests if (r.x, r.y) == (have.x, have.y)] + want = asked[0] if asked else None + print(f" {app:<22} {show(want):<22} {show(have):<22}") + if not checks.check(f"{app} is where komorebi put it", want is not None): + continue + assert want is not None + if app in EXACT: + checks.check( + f"{app} takes the size it is asked for", (have.w, have.h) == (want.w, want.h) + ) + elif app in WHOLE_CELLS: + checks.check( + f"{app} sizes itself down to whole cells", + 0 <= want.w - have.w < CELL and 0 <= want.h - have.h < CELL, + ) + elif app in NOT_BELOW_MINIMUM: + checks.check( + f"{app} is never smaller than it is asked to be", + have.w >= want.w and have.h >= want.h, + ) + + kde.stop_komorebi() + kde.stop() diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/features.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/features.py new file mode 100644 index 00000000..b7ffb027 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/features.py @@ -0,0 +1,359 @@ +r"""What komorebi on Windows does itself and komorebi on KDE has the compositor do, in a real Plasma +session whose machine has the effects installed (the module does that): what is on the screen, +read from screenshots, not what komorebi wrote. Each feature is a section, and a run of the +daemon: + + A toggle-maximize: the window fills the work area, is the one on top, and goes back to its + tile. It runs on the daemon the session started with the module's unit, as on a user's + machine; the sections after it stop that daemon and start their own runs + B transparency: unfocused windows are see-through, the focused one is not + C border colors: every kind of window has its own: the focused window, the others, a locked + container that does not have the focus, a stack and a monocled window that have it, and a + floating window that has it + D animation curves: two curves put a window in different places at the same moment + E fullscreen: a fullscreen window covers the monitor, is not moved, and goes back to its tile + +Every window is a `foot` of one color all over (`Kde.colored_window`), and a color is read at the +pixels just outside the frame of the window (`pixels.ring`); section E reads the frames KWin +reports for the windows, not a screenshot. `komorebi/tests/maximize.rs`, `maximize_commands.rs` +and `fullscreen.rs` check what the window manager does with a maximize and a fullscreen against +the fake; section A checks that KWin's own maximize does it, and section E that a window KWin has +taken fullscreen is left alone. +""" + +import time +from typing import Any + +from komorebi_vm import Checks, Kde, Rect, pixels + +UNIT = "komorebi.service" +# the daemon's log of the day, without colors, which every run of the unit adds to +LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" +ROUNDED_CORNERS = "kwin4_effect_shapecorners" + +BLUE = (0, 0, 255) +SINGLE = (66, 165, 245) +UNFOCUSED = (128, 128, 128) +LOCKED = (158, 8, 8) +STACK = (0, 165, 66) +MONOCLE = (255, 51, 153) +FLOATING = (245, 245, 165) +RED = (255, 0, 0) + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `features`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + + def answering() -> bool: + return kde.run("komorebic monitor-information")[0] == 0 + + def start_komorebi() -> None: + kde.systemctl("start", UNIT) + kde.wait_for(answering, timeout=60) + # The shell's panel takes room from the windows a while after the shell has made it, and the + # daemon learns that up to a second later. The windows are opened after that: before it they + # are tiled under the panel and then again, and the ring is read in between. + kde.wait_for_panel_room() + # the effects are written, loaded and told to read their settings as the daemon starts + time.sleep(2) + + def stop_komorebi() -> None: + kde.systemctl("stop", UNIT) + kde.close_colored_windows() + + def windows() -> None: + """Opens a red, a green and a blue window, in that order, and waits for them to be tiled.""" + for title, color in (("red", "ff0000"), ("green", "00ff00"), ("blue", "0000ff")): + kde.colored_window(title, color) + time.sleep(1) + kde.wait_for(lambda: kde.managed() == 3, timeout=30) + time.sleep(2) + + def ring_wrong(title: str, color: tuple[int, int, int]) -> list[str]: + """What is wrong with the ring of `color` just outside the frame of the window with this title, + in a screenshot taken now: a line for each side that has none.""" + wid = kde.wid(title) + if wid == "": + return [f"there is no window titled {title}"] + return pixels.ring(kde.shot(f"ring-{title}"), kde.rect(wid), color) + + def check_ring(description: str, title: str, color: tuple[int, int, int]) -> None: + """Waits for the window to have the ring, and says what is wrong when it does not.""" + ok = kde.wait_for(lambda: ring_wrong(title, color) == [], timeout=15) + detail = "" + if not ok: + detail = ( + f"\n active: {active_title()!r}, komorebi's focus: {kde.focused_title()!r}" + ) + detail += "".join(f"\n {w}" for w in ring_wrong(title, color)) + said = machine.execute(f"grep -h -i 'border effect\\|colour\\|effect' {LOG}")[1] + detail += "".join(f"\n daemon: {line}" for line in said.splitlines()[-8:]) + checks.check(description + detail, ok) + + def active_title() -> str: + wid = kde.active() + return kde.title(wid) if wid else "" + + def focus(title: str) -> None: + """Gives the window the focus, and waits until komorebi has it focused too.""" + kde.activate(kde.wid(title)) + kde.wait_for(lambda: kde.focused_title() == title, timeout=10) + + def near(pixel: object, want: tuple[int, int, int], tolerance: int = 14) -> bool: + """True if every channel of the pixel is within `tolerance` of `want`.""" + assert isinstance(pixel, tuple) + return all(abs(got - wanted) <= tolerance for got, wanted in zip(pixel, want, strict=True)) + + def open_window(title: str, background: str) -> None: + """Opens a terminal with a plain background, so that a screenshot says which window is on top.""" + kde.spawn( + f"foot -T {title} -o colors-dark.background={background} -o colors-dark.alpha=1.0" + " sleep 3000" + ) + kde.wait_for(lambda: kde.wid(title) != "", timeout=60) + + print("== A. toggle-maximize") + checks.check("the session started komorebi", kde.wait_for(answering, timeout=120)) + for count, (title, background) in enumerate( + [("red", "ff0000"), ("green", "00ff00"), ("blue", "0000ff")], start=1 + ): + open_window(title, background) + checks.check( + f"komorebi manages {title}", kde.wait_for(lambda count=count: kde.managed() == count) + ) + # komorebi tiles the windows, and the last one to open has the focus. The bridge asks again for the + # position of a window that is not where komorebi put it for a second after it did (PLATFORM.md, + # "How clients answer a frame"), which would put a window that is maximized in that second back + # where its tile was: the test waits that second out, as a person would. + kde.wait_for(lambda: kde.focused_title() == "blue", timeout=20) + time.sleep(3 * SCALE) + + area = kde.state()["monitors"]["elements"][0]["work_area_size"] + blue = kde.wid("blue") + tile = kde.rect(blue) + print(f" the work area is {area['right']}x{area['bottom']}, blue's tile is {tile}") + checks.check( + "blue is a tile, not the whole work area", + tile.w < area["right"] - 20 or tile.h < area["bottom"] - 20, + ) + + kde.komorebic("toggle-maximize") + + def fills_the_work_area() -> bool: + """KWin's maximize leaves the panel alone, which is at most 100 pixels of the screen.""" + r = kde.rect(blue) + return ( + r.x <= area["left"] + 2 + and r.y <= area["top"] + 2 + and r.w >= area["right"] - 30 + and r.h >= area["bottom"] - 100 + ) + + filled = kde.wait_for(fills_the_work_area, timeout=20) + maximized = kde.rect(blue) + checks.check( + f"the focused window fills the work area (blue is {maximized}, the area is {area})", filled + ) + + # a pixel that is not the middle of the window: komorebi puts the pointer there (mouse follows + # focus), and a screenshot has the white arrow on it + image = kde.shot("maximized") + print(f" the screenshot is {image.size[0]}x{image.size[1]}") + inside = image.getpixel( + ( + min(maximized.x + maximized.w // 4, image.width - 1), + min(maximized.y + maximized.h // 4, image.height - 1), + ) + ) + checks.check(f"and is the one on top ({inside})", near(inside, BLUE)) + workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] + checks.check( + "komorebi's state has it as the maximized window, out of its containers", + workspace["maximized_window"] is not None and len(workspace["containers"]["elements"]) == 2, + ) + checks.check("komorebi still has all three", kde.managed_all() == 3) + + kde.komorebic("toggle-maximize") + checks.check( + "toggled back, it is in its tile again", + kde.wait_for(lambda: kde.rect(blue) == tile, timeout=20), + ) + workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] + checks.check( + "... and in a container of its own", + workspace["maximized_window"] is None and len(workspace["containers"]["elements"]) == 3, + ) + + # the session started the module's unit when it logged in: section A used its daemon, and the + # sections after it start their own runs + stop_komorebi() + + print("== B. transparency") + start_komorebi() + kde.komorebic("transparency-alpha", "100") + kde.komorebic("transparency", "enable") + windows() + + def center_of(title: str) -> tuple[int, int]: + frame = kde.rect(kde.wid(title)) + return frame.x + frame.w // 2, frame.y + frame.h // 2 + + def middle_of(title: str, color: tuple[int, int, int]) -> bool: + """Returns true if and only if the middle of the window is `color` in a screenshot now.""" + return pixels.near(pixels.pixel(kde.shot(f"middle-{title}"), *center_of(title)), color) + + checks.check( + "the focused window is its own color", + kde.wait_for(lambda: middle_of("blue", BLUE), timeout=15), + ) + checks.check( + "an unfocused window is not: it lets the desktop through", + kde.wait_for(lambda: not middle_of("red", RED), timeout=15), + ) + kde.komorebic("transparency", "disable") + checks.check( + "with transparency off the unfocused window is opaque again", + kde.wait_for(lambda: middle_of("red", RED), timeout=15), + ) + kde.komorebic("toggle-transparency") + checks.check( + "toggled on, see-through again", + kde.wait_for(lambda: not middle_of("red", RED), timeout=15), + ) + stop_komorebi() + + print("== C. border colors") + start_komorebi() + windows() + checks.check( + "komorebi's build of the border effect is on the bus (it takes a color for each window)", + kde.run( + "busctl --user introspect org.kde.KWin /org/komorebi/BorderColours | grep -q SetColours" + )[0] + == 0, + ) + check_ring("the focused window has the focus color", "blue", SINGLE) + check_ring("the others have the unfocused one", "green", UNFOCUSED) + + # a locked container that does not have the focus + focus("red") + kde.komorebic("toggle-lock") + focus("blue") + check_ring("a locked container that does not have the focus is marked", "red", LOCKED) + focus("red") + kde.komorebic("toggle-lock") + focus("blue") + + # a stack that has the focus: blue goes into the container on its left + kde.komorebic("stack", "left") + check_ring("a stack with the focus has the stack color", "blue", STACK) + kde.komorebic("unstack") + + # a monocled window + kde.komorebic("toggle-monocle") + check_ring("a monocled window has the monocle color", "blue", MONOCLE) + kde.komorebic("toggle-monocle") + + # a floating window that has the focus + kde.komorebic("toggle-float") + check_ring("a floating window with the focus has the floating color", "blue", FLOATING) + stop_komorebi() + + print("== D. animation curves") + # A 30 s animation, looked at a few seconds in: how far along the move is red, as seen on the + # screen (the frames are already where they are going; only the picture is on its way). An ease out + # is far along by then and a linear one has hardly started. Red is given the focus first so that + # nothing hides its left edge, and the answer is a percentage of the way, so it does not depend on + # how long the screenshot took. + + def progress(style: str) -> int: + """How far along, in percent, red is a few seconds into a flip of the layout with `style`.""" + start_komorebi() + kde.komorebic("animation-duration", "30000") + kde.komorebic("animation-style", "--style", style) + kde.komorebic("animation", "enable") + kde.colored_window("red", "ff0000") + time.sleep(1) + kde.colored_window("blue", "0000ff") + time.sleep(20 * SCALE) + focus("red") + time.sleep(2) + here = kde.rect(kde.wid("red")) + row = here.y + here.h // 2 + from_x = pixels.leftmost(kde.shot(f"curve-before-{style}"), row, RED) + kde.komorebic("flip-layout", "horizontal") + kde.wait_for(lambda: kde.rect(kde.wid("red")) != here, timeout=10) + to = kde.rect(kde.wid("red")) + time.sleep(5 * SCALE) + now_x = pixels.leftmost(kde.shot(f"curve-{style}"), row, RED) + print( + f" {style}: red's left edge on the screen went from {from_x} to {now_x}; its frame" + ) + print(f" goes from {here.x} to {to.x}") + stop_komorebi() + if from_x is None or now_x is None or to.x == here.x: + return -1 + return (now_x - from_x) * 100 // (to.x - here.x) + + linear = progress("linear") + expo = progress("ease-out-expo") + print(f" a few seconds into a 30 s move, red is this far along: {linear}% with Linear,") + print(f" {expo}% with EaseOutExpo") + checks.check("Linear is less than 60% of the way", 0 <= linear < 60) + checks.check("EaseOutExpo is at least 20 points further along than Linear", expo >= linear + 20) + + print("== E. fullscreen") + # This section needs the daemon running and a red, a green and a blue window open and tiled, and + # does not depend on which section came before it: when one has stopped the daemon or closed the + # windows, they are started and opened again. + if not answering(): + kde.systemctl("start", UNIT) + kde.wait_for(answering, timeout=60) + for title, background in [("red", "ff0000"), ("green", "00ff00"), ("blue", "0000ff")]: + if kde.wid(title) == "": + open_window(title, background) + kde.wait_for(lambda: kde.managed() == 3, timeout=30) + kde.wait_for(lambda: kde.focused_title() == "blue", timeout=20) + blue = kde.wid("blue") + monitor = kde.state()["monitors"]["elements"][0]["size"] + whole = Rect(monitor["left"], monitor["top"], monitor["right"], monitor["bottom"]) + # the bridge asks again for the position of a window that is not where komorebi put it for a second + # after it did, which is not the thing tested here + time.sleep(3 * SCALE) + kde.fullscreen(blue) + checks.check( + f"the window covers the monitor, panels included ({kde.rect(blue)}, the monitor is {whole})", + kde.wait_for(lambda: kde.rect(blue) == whole, timeout=20), + ) + open_window("yellow", "ffff00") + checks.check("komorebi manages the fourth window", kde.wait_for(lambda: kde.managed() == 4)) + time.sleep(3 * SCALE) + checks.check( + f"a window opening meanwhile does not take it out of fullscreen ({kde.rect(blue)})", + kde.rect(blue) == whole, + ) + kde.fullscreen(blue, on=False) + + def in_a_tile(r: Rect) -> bool: + """Smaller than the monitor, and inside it.""" + return ( + r.w < whole.w - 100 + and r.x >= whole.x + and r.y >= whole.y + and r.x + r.w <= whole.x + whole.w + and r.y + r.h <= whole.y + whole.h + ) + + checks.check( + "back from fullscreen it is in a tile", + kde.wait_for(lambda: in_a_tile(kde.rect(blue)), timeout=20), + ) + back = kde.rect(blue) + print(f" blue is back at {back}") + checks.check( + "and it does not sit on any other window", + not any(back.overlaps(kde.rect(kde.wid(other))) for other in ("red", "green", "yellow")), + ) + checks.check("komorebi still has all four", kde.managed_all() == 4) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/focus_follows_mouse.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/focus_follows_mouse.py new file mode 100644 index 00000000..a023ec63 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/focus_follows_mouse.py @@ -0,0 +1,130 @@ +r"""Focus follows mouse against a real KWin session, with a real pointer. + +komorebi's focus follows mouse is KWin's own focus policy: the window under the pointer is the one +that has the focus, and komorebi follows. Checked by moving the pointer over each window in turn, +then turning it off (the focus stays where it was), and on exit (the user's policy is back in +`kwinrc`). The pointer is a device made inside the guest (`Pointer`, the program +`komorebi-pointer`), moved to the middle of a window by pixel. +""" + +import time +from typing import Any + +from komorebi_vm import Checks, Kde, Pointer + +UNIT = "komorebi.service" +# the session node's display, which the pointer's two axes span +SCREEN = (1280, 800) + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `focus-follows-mouse`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + + def answering() -> bool: + return kde.run("komorebic monitor-information")[0] == 0 + + def running() -> bool: + return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 + + def active_title() -> str: + wid = kde.active() + return kde.title(wid) if wid else "" + + def focus_policy() -> str | None: + return kde.kwinrc("Windows", "FocusPolicy") + + def kwin_has_read_it() -> None: + """Waits for KWin to have read the focus policy komorebi wrote. + + The key is in the file at once, and KWin reads it about 200 ms after it is asked to (it waits + for more changes): a pointer moved before that is moved under the old policy, and a pointer that + then rests over a window moves nothing. + """ + time.sleep(1) + + def middle(title: str) -> tuple[int, int]: + frame = kde.rect(kde.wid(title)) + return frame.x + frame.w // 2, frame.y + frame.h // 2 + + # the session started the module's unit when it logged in: this test starts its own run + kde.systemctl("stop", UNIT) + kde.close_colored_windows() + before = focus_policy() + before_delay = kde.kwinrc("Windows", "DelayFocusInterval") + print(f" the user's focus policy before: {before or '(not set: click to focus)'}") + + print("== focus follows mouse, turned on by command") + kde.systemctl("start", UNIT) + kde.wait_for(answering, timeout=60) + time.sleep(2) + kde.colored_window("win1", "222233") + time.sleep(1) + kde.colored_window("win2", "223322") + kde.wait_for(lambda: kde.managed() == 2, timeout=30) + time.sleep(2) + pointer = Pointer.start(machine, SCREEN, scale=SCALE) + kde.komorebic("focus-follows-mouse", "enable") + checks.check( + "KWin's focus policy is focus follows mouse, with no delay", + kde.wait_for( + lambda: focus_policy() == "1" and kde.kwinrc("Windows", "DelayFocusInterval") == "0", + timeout=10, + ), + ) + + kwin_has_read_it() + first, second = middle("win1"), middle("win2") + print(f" win1's middle is at {first}, win2's at {second}") + pointer.move(*first) + checks.check( + "the pointer over win1 gives it the focus", + kde.wait_for(lambda: active_title() == "win1", timeout=10), + ) + pointer.move(*second) + checks.check("over win2, win2", kde.wait_for(lambda: active_title() == "win2", timeout=10)) + pointer.move(*first) + checks.check("and back", kde.wait_for(lambda: active_title() == "win1", timeout=10)) + checks.check( + "komorebi followed the compositor", + kde.wait_for(lambda: kde.focused_title() == "win1", timeout=10), + ) + + print("== turned off") + kde.komorebic("toggle-focus-follows-mouse") + checks.check( + "the policy is back to what it was", + kde.wait_for(lambda: focus_policy() == before, timeout=10), + ) + kwin_has_read_it() + pointer.move(*second) + time.sleep(2) + checks.check("the pointer over win2 no longer moves the focus", active_title() == "win1") + + print("== turned on again, and put back when komorebi exits") + kde.komorebic("focus-follows-mouse", "enable") + checks.check( + "the policy is focus follows mouse again", + kde.wait_for(lambda: focus_policy() == "1", timeout=10), + ) + kwin_has_read_it() + # the pointer is resting over win2: it has to go into a window to be followed + pointer.move(*first) + kde.wait_for(lambda: active_title() == "win1", timeout=10) + pointer.move(*second) + checks.check( + "on again: the pointer over win2 gives it the focus", + kde.wait_for(lambda: active_title() == "win2", timeout=10), + ) + kde.komorebic("stop") + kde.wait_for(lambda: not running(), timeout=30) + kde.close_colored_windows() + checks.check( + "when komorebi exits the user's focus policy is back", + kde.wait_for(lambda: focus_policy() == before, timeout=10), + ) + checks.check( + "and so is the delay it had", + kde.kwinrc("Windows", "DelayFocusInterval") == before_delay, + ) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/keys_corpus.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/keys_corpus.py new file mode 100644 index 00000000..851cad1a --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/keys_corpus.py @@ -0,0 +1,41 @@ +r"""vm-keys-skhd, vm-keys-whkd and vm-keys-sxhkd: the case `vm` of the key binding corpus +(komorebi-hotkeys/tests/fixtures/vm.*), in the format of the suite, installed by the NixOS module +(`services.komorebi.keybindings`, mode auto). Alt+J can be a static shortcut, which KWin runs +from the system profile; Alt+, cannot, so the module's daemon registers it and runs it. The Rust +tests and `keybindings-fixtures` check the plan; only a real session can say that what the +module builds and starts runs on a key, from each of the three formats. +""" + +from typing import Any + +from komorebi_vm import Checks, Kde, Keys + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `keys-corpus`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + keys = Keys(machine) + + def ran(marker: str) -> bool: + return machine.execute(f"test -e /tmp/{marker}")[0] == 0 + + def press(combo: str, marker: str) -> bool: + keys.send(combo) + return kde.wait_for(lambda: ran(marker), timeout=10) + + shortcuts = machine.succeed("ls /run/current-system/sw/share/kglobalaccel") + checks.check( + "the module installed the static shortcut in the system profile", + "komorebi-touch-tmp-keys-corpus-alt-j.desktop" in shortcuts.split(), + ) + checks.check( + "the module's daemon registered the key of the engine, and only that one", + kde.wait_for(lambda: kde.shortcut_actions() == ["Alt+,"], timeout=60), + ) + checks.check( + "Alt+J runs its command, as a static shortcut", press("alt-j", "keys-corpus-alt-j") + ) + checks.check( + "Alt+, runs its command, through the engine", press("alt-comma", "keys-corpus-alt-comma") + ) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/keys_engine.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/keys_engine.py new file mode 100644 index 00000000..a0ea916d --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/keys_engine.py @@ -0,0 +1,291 @@ +r"""The engine in a real Plasma session: the daemon registers the keys of a key binding file with +KWin's global shortcut daemon and runs their commands. The Rust tests check the calls the +engine's effects become; only KWin can say that a grabbed key reports its presses to the daemon, +that the keys of a killed daemon stay registered until the next start takes them over, and that +a stop gives them back. +""" + +import json +import shlex +from typing import Any + +from komorebi_vm import Checks, Kde, Keys + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `keys-engine`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + keys = Keys(machine) + + def ran(marker: str) -> bool: + return machine.execute(f"test -e /tmp/{marker}")[0] == 0 + + def press(combo: str, marker: str) -> bool: + keys.send(combo) + return kde.wait_for(lambda: ran(marker), timeout=10) + + def engine() -> dict[str, Any]: + """What the engine is doing: its `mode`, the keys it holds (`active`) and whether a chord + `chain` is being typed. It is empty when no engine answers. + + The engine answers once it has told kglobalaccel everything its last event needed, so what it + says it holds is what KWin has grabbed. A key pressed before that is not the engine's yet and + goes to the window, and how long the grab takes is how slow the machine is: the engine is + asked, and no fixed time is waited. + """ + status, out = kde.run("komorebic hotkeys state") + return (json.loads(out).get("engine") or {}) if status == 0 else {} + + def in_mode(mode: str) -> bool: + """Waits for the engine to be in `mode`, with the keys of the mode grabbed.""" + return kde.wait_for(lambda: engine().get("mode") == mode, timeout=10) + + def chain_is(on: bool, within: float = 10) -> bool: + """Waits for the engine to be in a chord chain (or, with `on` false, to be done with it, and to + hold the keys of the mode again), for up to `within` seconds.""" + return kde.wait_for(lambda: engine().get("chain") is on, timeout=within) + + def write(skhdrc: str) -> None: + kde.sh( + f"mkdir -p ~/.config/komorebi && printf '%s' {shlex.quote(skhdrc)} > ~/.config/komorebi/skhdrc" + ) + + def start(skhdrc: str, *args: str) -> None: + write(skhdrc) + # no --keybindings: the daemon finds the skhdrc in the config directory + kde.spawn_komorebi("--log-level", "debug", *args) + if not kde.wait_for(lambda: "keys in kglobalaccel" in kde.komorebi_log(), timeout=60): + raise AssertionError(f"the keys were not registered:\n{kde.komorebi_log()}") + + def stop() -> None: + """Stops the daemon, and waits until it is gone: it takes its KWin script and its keys with + it when it exits, and a daemon started before that would find them taken from it.""" + kde.komorebic("stop") + if not kde.wait_for(lambda: machine.execute("pgrep -x komorebi")[0] != 0, timeout=10): + raise AssertionError("the daemon did not stop") + + start( + "alt - h : touch /tmp/keys-engine-alt-h\n" + "alt - r : komorebic retile\n" + 'alt - q : echo "$HOME" > /tmp/keys-engine-alt-q\n' + ) + actions = kde.shortcut_actions() + checks.check( + f"the daemon registered its three keys ({actions})", actions == ["Alt+H", "Alt+Q", "Alt+R"] + ) + checks.check("Alt+H runs its command", press("alt-h", "keys-engine-alt-h")) + checks.check("Alt+Q runs its command through a shell", press("alt-q", "keys-engine-alt-q")) + home = machine.succeed("cat /tmp/keys-engine-alt-q").strip() + checks.check(f"the shell expanded $HOME ({home!r})", home == "/home/komorebi") + keys.send("alt-r") + checks.check( + "Alt+R runs komorebic, which sends its message to the daemon", + kde.wait_for(lambda: "processing command: Retile" in kde.komorebi_log(), timeout=10), + ) + + # kglobalaccel keeps the keys of a daemon that was killed + kde.kill_spawned_komorebi() + checks.check("a killed daemon leaves its keys registered", kde.shortcut_actions() == actions) + + # the next start takes over the keys it binds, and unregisters the others + start("alt - j : touch /tmp/keys-engine-alt-j\nalt - h : touch /tmp/keys-engine-alt-h-again\n") + actions = kde.shortcut_actions() + checks.check( + f"the next start leaves only its own keys ({actions})", actions == ["Alt+H", "Alt+J"] + ) + checks.check("Alt+J runs its command", press("alt-j", "keys-engine-alt-j")) + checks.check("Alt+H runs its new command", press("alt-h", "keys-engine-alt-h-again")) + + # a stop gives every key back + kde.komorebic("stop") + checks.check( + "komorebic stop stops the daemon", + kde.wait_for(lambda: machine.execute("pgrep -x komorebi")[0] != 0, timeout=10), + ) + checks.check("a stop unregisters every key", kde.shortcut_actions() == []) + machine.succeed("rm /tmp/keys-engine-alt-j") + keys.send("alt-j") + checks.check( + "Alt+J runs nothing once the daemon stopped", + not kde.wait_for(lambda: ran("keys-engine-alt-j"), timeout=3), + ) + + # modes: entering one grabs its keys, a bare H among them, and lets the others go to the window + kde.spawn("stdbuf -oL wev", log="/tmp/wev.log") + if not kde.wait_for(lambda: kde.wid_by_class("wev") != "", timeout=30): + raise AssertionError("wev did not open") + + def activate(wid: str) -> None: + """Gives the window the focus, asking again until KWin has: it lists a window before it + can have the focus, and refuses to activate it until then.""" + if not kde.wait_for( + lambda: ( + kde.run(f"kdotool windowactivate {shlex.quote(wid)}")[0] == 0 + and kde.active() == wid + ), + timeout=30, + ): + raise AssertionError(f"{wid} did not take the focus") + + activate(kde.wid_by_class("wev")) + + def typed(key: str) -> int: + """How many presses of `key` reached wev.""" + # wev prints a sym line after the press and after the release of a key + presses = f"grep -A1 'state: 1 (pressed)' /tmp/wev.log | grep -cE 'sym: {key} +\\('" + out = machine.execute(presses)[1].strip() + return int(out or "0") + + def reaches_wev(key: str, presses: int) -> bool: + return kde.wait_for(lambda: typed(key) >= presses, timeout=5) + + start( + ":: resize : touch /tmp/keys-modes-entered\n" + "alt - r ; resize\n" + "resize < h : touch /tmp/keys-modes-h\n" + "resize < escape ; default\n" + ) + keys.send("h") + checks.check("in the default mode H reaches the focused window", reaches_wev("h", 1)) + checks.check("Alt+R enters the mode and runs its command", press("alt-r", "keys-modes-entered")) + checks.check( + "the daemon logs the mode it is in, and holds the keys of the mode", + kde.wait_for(lambda: "the mode is now resize" in kde.komorebi_log()) and in_mode("resize"), + ) + checks.check("in the mode H runs its binding", press("h", "keys-modes-h")) + checks.check("and does not reach the window", typed("h") == 1) + keys.send("esc") + checks.check( + "Escape goes back to the default mode, and gives the keys of the mode back", + kde.wait_for(lambda: "the mode is now default" in kde.komorebi_log()) + and in_mode("default"), + ) + keys.send("h") + checks.check("back in the default mode H reaches the window again", reaches_wev("h", 2)) + stop() + + # chord chains: the prefix grabs the keys that can come next, until a key, Escape or the timeout + sxhkdrc = "/home/komorebi/.config/komorebi/sxhkdrc" + chain = "alt + w ; {h,l}\n touch /tmp/keys-chords-{h,l}\n" + kde.sh(f"printf '%s' {shlex.quote(chain)} > {sxhkdrc}") + # The timeout is long, and is scaled like every wait, so that the keys of a chain are sent well + # inside it however slowly the machine grabs them, and that Escape can be told from the timeout. + CHORD_TIMEOUT = 3 + kde.spawn_komorebi( + "--log-level", + "debug", + "--keybindings", + sxhkdrc, + "--chord-timeout", + str(int(CHORD_TIMEOUT * 1000 * SCALE)), + ) + if not kde.wait_for(lambda: "keys in kglobalaccel" in kde.komorebi_log(), timeout=60): + raise AssertionError(f"the keys were not registered:\n{kde.komorebi_log()}") + + def chain_begins() -> None: + """Presses Alt+W and waits until the engine has grabbed the keys that can come next. + + A key pressed before that goes to the window, not to the chain. + """ + keys.send("alt-w") + if not chain_is(True): + raise AssertionError( + f"Alt+W did not begin the chain ({engine()}):\n{kde.komorebi_log()}" + ) + + def chain_ends() -> None: + """Waits until the chain is over and the engine holds Alt+W again, which a key pressed + before that would not find.""" + if not chain_is(False): + raise AssertionError(f"the chain did not end ({engine()}):\n{kde.komorebi_log()}") + + h_before = typed("h") + chain_begins() + checks.check("Alt+W, H runs the binding of the chain", press("h", "keys-chords-h")) + checks.check("the H of the chain does not reach the window", typed("h") == h_before) + chain_ends() + chain_begins() + keys.send("esc") + checks.check( + "Escape ends the chain, which the timeout has not yet done", + chain_is(False, within=CHORD_TIMEOUT / 2), + ) + keys.send("h") + checks.check("after Alt+W, Escape, H reaches the window", reaches_wev("h", h_before + 1)) + chain_begins() + checks.check("the chain ends at its timeout", chain_is(False, within=CHORD_TIMEOUT + 1)) + keys.send("l") + checks.check("after Alt+W and the timeout, L reaches the window", reaches_wev("l", 1)) + checks.check("and runs nothing", not ran("keys-chords-l")) + stop() + + # per-application bindings: a key is grabbed only while the focused application has an action + start( + 'alt - g [\n "terminal" : touch /tmp/keys-scopes-terminal\n]\n' + 'alt - n [\n "wev" ~\n * : touch /tmp/keys-scopes-other\n]\n', + "--app-alias", + "terminal=foot", + ) + kde.spawn("foot") + if not kde.wait_for(lambda: kde.wid_by_class("foot") != "", timeout=30): + raise AssertionError("foot did not open") + wev, foot = kde.wid_by_class("wev"), kde.wid_by_class("foot") + + def sees_focus(wid: str, app_id: str) -> bool: + """Activates the window and waits for the engine to log that its application has the focus.""" + activate(wid) + + def seen() -> bool: + lines = [x for x in kde.komorebi_log().splitlines() if "the focus is now" in x] + return bool(lines) and f"({app_id}, " in lines[-1] + + return kde.wait_for(seen, timeout=10) + + def focus(wid: str, app_id: str) -> None: + """Activates the window, and returns once the engine has grabbed the keys that its + application has an action for, and given the others back.""" + if not sees_focus(wid, app_id): + raise AssertionError(f"the engine did not see {app_id} take the focus") + # the engine logs the focus before it grabs and gives back the keys of the application, and + # answers once it has: a key pressed before that would find the keys of the other window + if not engine(): + raise AssertionError("the engine does not answer") + + focus(wev, "wev") + g_before, n_before = typed("g"), typed("n") + keys.send("alt-g") + checks.check( + "in wev, Alt+G (for the terminal only) reaches wev", reaches_wev("g", g_before + 1) + ) + keys.send("alt-n") + checks.check("in wev, Alt+N (which wev ignores) reaches wev", reaches_wev("n", n_before + 1)) + checks.check("and runs nothing", not ran("keys-scopes-other")) + focus(foot, "foot") + checks.check( + "in foot, Alt+G runs the terminal's binding, by the alias", + press("alt-g", "keys-scopes-terminal"), + ) + checks.check( + "in foot, Alt+N runs the binding for every other application", + press("alt-n", "keys-scopes-other"), + ) + focus(wev, "wev") + keys.send("alt-g") + checks.check("back in wev, Alt+G reaches wev again", reaches_wev("g", g_before + 2)) + + # An engine that starts while the focused application has nothing to grab starts all the same: + # the key bindings are read again with wev focused, and every binding is for the terminal. + write('alt - j [\n "terminal" : touch /tmp/keys-scopes-reload\n]\n') + reads = kde.komorebi_log().count("bindings for the engine") + kde.komorebic("hotkeys", "reload") + kde.wait_for(lambda: kde.komorebi_log().count("bindings for the engine") > reads, timeout=10) + checks.check( + "an engine that starts with nothing to grab goes on to see foot take the focus", + sees_focus(foot, "foot") and bool(engine()), + ) + checks.check( + "and in foot, Alt+J runs the terminal's binding", + press("alt-j", "keys-scopes-reload"), + ) + stop() diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/keys_static.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/keys_static.py new file mode 100644 index 00000000..3bf99ed7 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/keys_static.py @@ -0,0 +1,50 @@ +r"""Static shortcuts in a real Plasma session: what `komorebic hotkeys compile` and +`komorebic export-kde-shortcuts` write is run by KWin itself, with no komorebi +process. The Rust tests check the files; only a KWin can say that it reads them +and runs their commands on a key: the files in the system profile when the +session starts, and a file written later once `--reload` has handed it over. +""" + +from typing import Any + +from komorebi_vm import Checks, Kde, Keys + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `keys-static`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + keys = Keys(machine) + + def ran(marker: str) -> bool: + return machine.execute(f"test -e /tmp/{marker}")[0] == 0 + + def press(combo: str, marker: str) -> bool: + keys.send(combo) + return kde.wait_for(lambda: ran(marker), timeout=10) + + print(kde.sh("ls /run/current-system/sw/share/kglobalaccel")) + checks.check("Alt+J runs its command", press("alt-j", "keys-static-alt-j")) + checks.check( + "Alt+Shift+K runs a command that needs a shell", + press("alt-shift-k", "keys-static-alt-shift-k"), + ) + checks.check("Alt+P runs a command with a %", press("alt-p", "keys-static-alt-p")) + date = machine.succeed("cat /tmp/keys-static-alt-p").strip() + checks.check(f"the % reached the command as one % ({date!r})", date.isdigit()) + + # a binding written in the middle of the session, into the user's directory + kde.sh("mkdir -p ~/.config/komorebi") + kde.sh("echo 'alt - u : touch /tmp/keys-static-alt-u' > ~/.config/komorebi/skhdrc") + print(kde.sh("komorebic export-kde-shortcuts --reload")) + written = ( + "/home/komorebi/.local/share/kglobalaccel/komorebi-touch-tmp-keys-static-alt-u.desktop" + ) + checks.check( + "the file is in the user's kglobalaccel directory", + machine.execute(f"test -e {written}")[0] == 0, + ) + checks.check( + "Alt+U runs its command once --reload has handed it over", + press("alt-u", "keys-static-alt-u"), + ) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/kwin.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/kwin.py new file mode 100644 index 00000000..6f134f41 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/kwin.py @@ -0,0 +1,31 @@ +r"""What the harness itself promises: a headless KWin comes up with the outputs asked for, a client +gets a window on it, and the library sees both. +""" + +from typing import Any + +from komorebi_vm import Checks, Kde + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `kwin`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.headless(machine, "main", size=(1280, 720), outputs=2, scale=SCALE) + checks.check("KWin owns its name on the private bus", kde.has_name("org.kde.KWin")) + checks.check("KWin has the two outputs that were asked for", lambda: kde.outputs() == 2) + + kde.spawn("foot -T alpha sleep 3000") + checks.check("a window appears", kde.wait_for(lambda: kde.wid("alpha") != "", timeout=30)) + wid = kde.wid("alpha") + checks.check("the library reads its title back", lambda: kde.title(wid) == "alpha") + rect = kde.rect(wid) + print(f"alpha is at {rect}") + checks.check("it has a size", rect.w > 0 and rect.h > 0) + + other = Kde.headless(machine, "other", size=(800, 600), scale=SCALE) + checks.check("a second session is its own KWin", lambda: other.outputs() == 1) + checks.check("it does not see the first session's window", other.wid("alpha") == "") + other.stop() + + kde.stop() + checks.check("stopping the session releases its name", not kde.has_name("org.kde.KWin")) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/kwin_contract.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/kwin_contract.py new file mode 100644 index 00000000..ba3cf784 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/kwin_contract.py @@ -0,0 +1,172 @@ +r"""The contract of KWin's per-output virtual desktops that komorebi's workspaces rely on, checked +against a headless KWin with two outputs and no komorebi: workspace `i` is desktop `i`, and each +output shows a desktop of its own. What has to hold, and what breaks if it does not: + +- with `[Windows] PerOutputVirtualDesktops=true` in kwinrc, a script can show a desktop on one + output and the other output keeps its own (otherwise a workspace switch switches every monitor); +- KWin says so with `workspace.currentDesktopChanged`, which the bridge listens to; +- KWin focuses a window of the desktop it switched an output to, by itself (komorebi asks for no + focus after a switch it did not make); +- activating a window on another desktop of its output (an app raising itself) makes KWin switch + that output to the window's desktop (which komorebi then follows); +- a window moved by a script so that its middle is on the other output keeps its desktops: KWin + moves a window to the new output's desktop only during an interactive move; +- a window put on another desktop from outside raises `desktopsChanged` on the window, which the + bridge listens to. + +docs/dev/PLATFORM.md records these as the facts of KWin that komorebi depends on. +""" + +from itertools import count +from typing import Any + +from komorebi_vm import Checks, Kde + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `kwin-contract`, which the suite script calls.""" + SCALE = scale # noqa: N806 + # per-output desktops are read when KWin starts, as komorebi's users have them after their first run + machine.succeed( + "runuser -u komorebi -- sh -c 'mkdir -p ~/.config" + ' && printf "[Windows]\\nPerOutputVirtualDesktops=true\\n" > ~/.config/kwinrc\'' + ) + kde = Kde.headless(machine, "main", size=(1920, 1080), outputs=2, scale=SCALE) + + # what every script is given: the desktop each output shows, and a window by its title + HELPERS = """ + function cur() { + return workspace.screens.map(function (o) { + return workspace.currentDesktopForScreen(o).name; + }).join("/"); + } + function win(title) { + return workspace.windowList().filter(function (w) { return w.caption === title; })[0]; + } + function names(ds) { + return ds.map(function (d) { return d.name; }).join(","); + } + """ + + def script(name: str, body: str, keep: bool = False) -> list[str]: + return kde.kwin_script(name, HELPERS + body + '\nreport("done");\n', keep=keep) + + def shows() -> str: + """What each output shows, as `first/second`.""" + lines = script(f"shows-{next(counter)}", "report(cur());") + return lines[0] if lines else "" + + counter = count(1) + + print("== 1. two outputs, one desktop, and per-output desktops on") + outputs = script( + "outputs", 'report(workspace.screens.map(function (o) { return o.name; }).join(" "));' + ) + print(f" outputs: {outputs}") + names_of = outputs[0].split() if outputs else [] + checks.check("KWin has two outputs", len(names_of) == 2) + checks.check("and one desktop", kde.desktops() == 1) + checks.check( + "kwinrc has per-output desktops on", + kde.kwinrc("Windows", "PerOutputVirtualDesktops") == "true", + ) + + print("== 2. a desktop created over D-Bus is a desktop of every output") + kde.sh( + "busctl --user call org.kde.KWin /VirtualDesktopManager" + " org.kde.KWin.VirtualDesktopManager createDesktop us 1 two > /dev/null" + ) + checks.check("KWin has two desktops", kde.wait_for(lambda: kde.desktops() == 2)) + desktops = script("desktops", "report(names(workspace.desktops));") + checks.check(f"the script sees them in order: {desktops}", desktops[-1:] == ["Desktop 1,two"]) + checks.check("both outputs show the first", shows() == "Desktop 1/Desktop 1") + + print("== 3. one output shows another desktop, and the other keeps its own") + script( + "listen", + 'workspace.currentDesktopChanged.connect(function () { report("changed", cur()); });', + keep=True, + ) + script( + "switch", + "workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);", + ) + checks.check( + "the first output shows the second desktop, and the second output the first", + kde.wait_for(lambda: shows() == "two/Desktop 1"), + ) + checks.check( + "KWin said so with currentDesktopChanged", + kde.wait_for(lambda: "changed two/Desktop 1" in kde.kwin_reports("listen")), + ) + script( + "back", "workspace.setCurrentDesktopForScreen(workspace.desktops[0], workspace.screens[0]);" + ) + checks.check("and back", kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1")) + + print("== 4. KWin focuses a window of the desktop it switched an output to") + for title in ["w1", "w2"]: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30) + script( + "place", + """ + var d = workspace.desktops; + var w1 = win("w1"), w2 = win("w2"); + w1.desktops = [d[0]]; + w1.frameGeometry = { x: 100, y: 100, width: 600, height: 400 }; + w2.desktops = [d[1]]; + w2.frameGeometry = { x: 800, y: 100, width: 600, height: 400 }; + workspace.activeWindow = w1; + """, + ) + checks.check( + "w1 has the focus, on the first desktop", + kde.wait_for(lambda: kde.title(kde.active()) == "w1"), + ) + script( + "to-two", + "workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);", + ) + checks.check( + "after the first output shows the second desktop, w2, which is on it, has the focus", + kde.wait_for(lambda: kde.active() != "" and kde.title(kde.active()) == "w2"), + ) + + print("== 5. activating a window on another desktop of its output switches that output to it") + script("raise", 'workspace.activeWindow = win("w1");') + checks.check( + "the first output shows the first desktop again", + kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1"), + ) + checks.check("and w1 has the focus", kde.wait_for(lambda: kde.title(kde.active()) == "w1")) + + print("== 6. a window a script moves onto the other output keeps its desktops") + script("cross", 'win("w1").frameGeometry = { x: 2300, y: 100, width: 600, height: 400 };') + + def where_w1() -> str: + lines = script( + f"where-{next(counter)}", + 'var w = win("w1"); report(w.output.name + " " + names(w.desktops));', + ) + return lines[0] if lines else "" + + second = names_of[1] if len(names_of) == 2 else "?" + checks.check( + f"w1 is on {second} now, and still on the first desktop only", + kde.wait_for(lambda: where_w1() == f"{second} Desktop 1"), + ) + + print("== 7. a window put on another desktop from outside says so") + script( + "watch", + 'var w = win("w1"); w.desktopsChanged.connect(function () { report("moved", names(w.desktops)); });', + keep=True, + ) + kde.sh(f"kdotool set_desktop_for_window {kde.wid('w1')} 2") + checks.check( + "w1's desktopsChanged was raised, with the second desktop", + kde.wait_for(lambda: "moved two" in kde.kwin_reports("watch")), + ) + + kde.stop() diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/kwin_events.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/kwin_events.py new file mode 100644 index 00000000..9be79973 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/kwin_events.py @@ -0,0 +1,128 @@ +r"""The daemon reads a real KWin through its script. What only a real KWin can tell: that the script +loads and reports the desktop, that KWin's signals reach the window manager as the events +`komorebi/src/kwin/state.rs` and `komorebi/tests/wm_events.rs` feed it by hand, in the order KWin +raised them (KWin activates a new window before it announces it), that a window giving itself +another title is reported, and that it takes its script out of KWin when it stops. +""" + +import shlex +from typing import Any + +from komorebi_vm import Checks, Kde, daemon +from komorebi_vm.daemon import Event + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `kwin-events`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.headless(machine, "main", size=(1280, 720), scale=SCALE) + + def daemon_log() -> str: + return kde.komorebi_log() + + def handled(event: Event) -> bool: + return event in daemon.events(daemon_log()) + + kde.spawn("foot -T before sleep 3000") + checks.check( + "a window is open before komorebi starts", + kde.wait_for(lambda: kde.wid("before") != "", timeout=30), + ) + before = kde.wid("before") + + kde.start_komorebi() + checks.check( + "the daemon loaded its script into KWin", + kde.wait_for(lambda: "loaded the KWin bridge script" in daemon_log(), timeout=30), + ) + checks.check("KWin runs the script", kde.script_loaded()) + checks.check( + "the script reported the window that was already open", + kde.wait_for(lambda: "1 valid windows identified" in daemon_log(), timeout=10), + ) + checks.check("the daemon is still running", kde.komorebi_running()) + + print("== a window opens") + kde.spawn("foot -T alpha sleep 3000") + checks.check("KWin has it", kde.wait_for(lambda: kde.wid("alpha") != "", timeout=30)) + alpha = kde.wid("alpha") + checks.check( + "KWin's focus on it reached the daemon, by title", + kde.wait_for(lambda: "alpha" in daemon.window_ids(daemon_log()), timeout=10), + ) + ids = daemon.window_ids(daemon_log()) + n = ids.get("alpha", -1) + shown = Event("Show", n, "WindowAdded") + focused = Event("FocusChange", n, "WindowActivated") + checks.check( + "the daemon handled a Show for it", kde.wait_for(lambda: handled(shown), timeout=10) + ) + checks.check("... and a FocusChange", kde.wait_for(lambda: handled(focused), timeout=10)) + seen = daemon.events(daemon_log()) + checks.check( + "the Show came first, although KWin activates a window before it announces it", + shown in seen and focused in seen and seen.index(shown) < seen.index(focused), + ) + + print("== the focus moves") + kde.activate(before) + checks.check( + "the window that was open before is focused, and the daemon knows it", + kde.wait_for(lambda: "before" in daemon.window_ids(daemon_log()), timeout=10), + ) + m = daemon.window_ids(daemon_log()).get("before", -1) + checks.check( + "a FocusChange for it", + kde.wait_for(lambda: handled(Event("FocusChange", m, "WindowActivated")), timeout=10), + ) + + print("== minimize, restore, close") + kde.minimize(alpha) + checks.check( + "minimizing is a Minimize", + kde.wait_for(lambda: handled(Event("Minimize", n, "WindowMinimized")), timeout=10), + ) + kde.activate(alpha) + checks.check( + "activating a minimized window brings it back: a Restore", + kde.wait_for(lambda: handled(Event("Restore", n, "WindowRestored")), timeout=10), + ) + kde.close(alpha) + checks.check( + "closing is a Destroy", + kde.wait_for(lambda: handled(Event("Destroy", n, "WindowRemoved")), timeout=10), + ) + mine = [e.kind for e in daemon.events(daemon_log()) if e.window == n] + print(f" the events of alpha, in order: {mine}") + in_order = [kind for kind in mine if kind in ("Show", "Minimize", "Restore", "Destroy")] + checks.check( + "alpha's events came in the order they happened", + in_order == ["Show", "Minimize", "Restore", "Destroy"], + ) + + print("== a window gives itself another title") + rename = 'sleep 4; printf "\\033]0;beta-renamed\\007"; sleep 3000' + kde.spawn(f"foot -T beta sh -c {shlex.quote(rename)}") + checks.check( + "KWin's focus on it reached the daemon, by title", + kde.wait_for(lambda: "beta" in daemon.window_ids(daemon_log()), timeout=30), + ) + b = daemon.window_ids(daemon_log()).get("beta", -1) + checks.check( + "KWin has it under its new title", + kde.wait_for(lambda: kde.wid("beta-renamed") != "", timeout=20), + ) + checks.check( + "the title change is a TitleUpdate", + kde.wait_for(lambda: handled(Event("TitleUpdate", b, "CaptionChanged")), timeout=10), + ) + + print("== stop") + kde.stop_komorebi() + checks.check("the daemon exited", not kde.komorebi_running()) + checks.check( + "the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded(), timeout=10) + ) + checks.check("the windows are still there", kde.wid("before") != "") + + kde.stop() diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/latency.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/latency.py new file mode 100644 index 00000000..1399762e --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/latency.py @@ -0,0 +1,82 @@ +r"""How long a retile takes to reach the windows of a real KWin, measured on the session bus: from +the moment the daemon answers the bridge's held call with a batch of new frames, to the last +frame KWin reports for one of the windows it moved, the client's answer included. Every number +here comes from KWin and real clients; the Rust tests cannot measure it. The output is large, so +that ten windows in komorebi's default layout all have room. +""" + +from typing import Any + +from komorebi_vm import Checks, Kde, daemon, latency + +W, H = 3840, 2160 +WINDOWS = 10 +ROUNDS = 10 +BUS_LOG = "/tmp/komorebi-bus.log" + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `latency`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) + kde.start_komorebi() + checks.check( + "the daemon loaded its script into KWin", + kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30), + ) + kde.monitor_bridge(BUS_LOG) + + titles = [f"w{n}" for n in range(1, WINDOWS + 1)] + for title in titles: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30) + + def shown() -> int: + return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show") + + checks.check(f"the daemon tiles all {WINDOWS}", kde.wait_for(lambda: shown() >= WINDOWS)) + + def measured() -> list[latency.Round]: + return latency.rounds(machine.succeed(f"cat {BUS_LOG}")) + + def settled_after(count: int) -> bool: + """A round after the first `count` is over: its windows all reported, and then 0.3 s passed.""" + done = measured() + if len(done) <= count or done[-1].seconds is None: + return False + now = float(machine.succeed("date +%s.%N")) + return now - (done[-1].sent + done[-1].seconds) > 0.3 + + kde.wait_for(lambda: settled_after(0), timeout=10) + start = len(measured()) + + # each round takes one window out of the layout and puts it back: two retiles + for title in titles[:ROUNDS]: + wid = kde.wid(title) + count = len(measured()) + kde.minimize(wid) + kde.wait_for(lambda count=count: settled_after(count), timeout=10) + count = len(measured()) + kde.activate(wid) + kde.wait_for(lambda count=count: settled_after(count), timeout=10) + + # the rounds before `start` tiled the windows as they opened + rounds = measured()[start:] + settled = [r.seconds * 1000 for r in rounds if r.seconds is not None] + moved = sum(r.windows for r in rounds) / max(1, len(rounds)) + print( + f" {len(rounds)} retiles, {moved:.1f} windows moved by each on average, scale {SCALE}" + ) + if settled: + p50, p95 = latency.percentile(settled, 0.5), latency.percentile(settled, 0.95) + print(f" from the batch to the last frame: p50 {p50:.1f} ms, p95 {p95:.1f} ms,") + print(f" max {max(settled):.1f} ms, min {min(settled):.1f} ms") + checks.check(f"{2 * ROUNDS} retiles were measured", len(rounds) == 2 * ROUNDS) + checks.check("every window of every retile reported its frame", len(settled) == len(rounds)) + checks.check( + "a retile reaches the windows within 100 ms (times the machine's scale), at p95", + bool(settled) and latency.percentile(settled, 0.95) <= 100 * SCALE, + ) + + kde.stop_komorebi() + kde.stop() diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/live_resize.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/live_resize.py new file mode 100644 index 00000000..661f9884 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/live_resize.py @@ -0,0 +1,215 @@ +r"""The tiles next to an edge follow it while it is dragged, not only when it is let go, in a Plasma +session with a pointer device the test drives from inside the guest (`komorebi_vm.Pointer`). For +each case the button is pressed on an edge of a window, the pointer is taken part of the way and +held there, and the frames of every window are read while the button is still down; then the +rest of the way, read again, and let go (`komorebi/tests/live_resize.rs` checks the window +manager's side against the fake). What only a real KWin can tell is that the bridge sends the +steps of a drag and that the neighbors are moved while KWin has the dragged window: + +* part way and all the way, the neighbor's facing edge has moved with the pointer, give or take + a cell of the terminal's font +* the windows that are not next to the dragged edge have not moved +* when the button is let go nothing jumps: the neighbors stay where they followed to +* the windows still tile +""" + +import re +import time +from typing import Any + +from komorebi_vm import Checks, Kde, Pointer, daemon + +# the module's unit, which the session starts when it logs in: the daemon the suite drags against +UNIT = "komorebi.service" + +# what an edge of a terminal's frame may be off by: up to a cell of its font +CELL = 24 +# how far from its frame a window's resize border is pressed: in the gap between two tiles +OFFSET = 4 +WINDOWS = 3 + +OPPOSITE = {"L": "R", "R": "L", "T": "B", "B": "T"} +HELD = {"left": "L", "right": "R", "top": "T", "bottom": "B"} + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `live-resize`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + + # KWin snaps an edge the user drags to an edge of another window within its snap zone, 10 pixels + # by default, and the neighbors that follow a drag are about that far from the edge: it would end + # up a few pixels past the pointer. The test measures komorebi, so KWin snaps nothing. + for zone in ("BorderSnapZone", "WindowSnapZone", "CenterSnapZone"): + kde.sh(f"kwriteconfig6 --file kwinrc --group Windows --key {zone} 0") + kde.sh("busctl --user call org.kde.KWin /KWin org.kde.KWin reconfigure") + + # the session started the module's unit when it logged in + checks.check( + "komorebi answers", kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=120) + ) + + # The shell makes its panel, and KWin takes room for it a while later, which the daemon learns of + # up to a second after that and tiles the windows again. A case that begins then ends with every + # tile moved by the panel, so the windows are opened after it (`Kde.wait_for_panel_room`). + kde.wait_for_panel_room() + + size = kde.state()["monitors"]["elements"][0]["size"] + W, H = size["right"], size["bottom"] + pointer = Pointer.start(machine, (W, H), scale=SCALE) + + for n in range(1, WINDOWS + 1): + kde.spawn(f"foot -T win{n} sleep 3000") + kde.wait_for(lambda n=n: kde.managed() == n, timeout=30) + checks.check(f"the {WINDOWS} windows are tiled", kde.managed() == WINDOWS) + + Box = tuple[int, int, int, int] + + def frames() -> dict[str, Box]: + out = {} + for n in range(1, WINDOWS + 1): + r = kde.rect(kde.wid(f"win{n}")) + out[f"win{n}"] = (r.x, r.y, r.w, r.h) + return out + + def edges(r: Box) -> dict[str, int]: + x, y, w, h = r + return {"L": x, "T": y, "R": x + w, "B": y + h} + + def settled() -> dict[str, Box]: + """The frames once they have stopped changing""" + last = frames() + deadline = time.monotonic() + 10 * SCALE + while time.monotonic() < deadline: + time.sleep(0.5) + now = frames() + if now == last: + return now + last = now + return last + + def resize_ends() -> int: + """How many drags of an edge the daemon has handled the end of, by the unit's log""" + log = kde.run(f"journalctl --user -u {UNIT} --no-pager -o cat")[1] + return sum(1 for e in daemon.events(log) if e.kind == "ResizeEnd") + + def press_point(grab: str, r: Box) -> tuple[int, int]: + x, y, w, h = r + cx, cy = x + w // 2, y + h // 2 + return { + "left": (x - OFFSET, cy), + "right": (x + w + OFFSET, cy), + "top": (cx, y - OFFSET), + "bottom": (cx, y + h + OFFSET), + }[grab] + + def neighbors(edge: str, name: str, before: dict[str, Box]) -> list[str]: + """The windows within a gap's reach on that side of this one, overlapping it""" + mx, my, mw, mh = before[name] + found = [] + for other, (ox, oy, ow, oh) in before.items(): + if other == name: + continue + v = oy < my + mh and my < oy + oh + h = ox < mx + mw and mx < ox + ow + if ( + (edge == "L" and v and 0 <= mx - (ox + ow) <= 80) + or (edge == "R" and v and 0 <= ox - (mx + mw) <= 80) + or (edge == "T" and h and 0 <= my - (oy + oh) <= 80) + or (edge == "B" and h and 0 <= oy - (my + mh) <= 80) + ): + found.append(other) + return found + + def where() -> tuple[int, int]: + found = re.search(r"x:(-?\d+) y:(-?\d+)", kde.sh("kdotool getmouselocation")) + assert found, "kdotool says nowhere" + return int(found.group(1)), int(found.group(2)) + + def run_case(case: str) -> list[str]: + name, grab, d = case.split(":") + dx, dy = (int(v) for v in d.split(",")) + held = HELD[grab] + want = dx if held in "LR" else dy + + kde.komorebic("retile") + before = settled() + near = neighbors(held, name, before) + if not near: + return [f"{name} has nothing next to its {grab} edge"] + ends = resize_ends() + + px, py = press_point(grab, before[name]) + pointer.move(px, py) + pointer.down() + + problems = [] + held_at: dict[str, dict[str, Box]] = {} + for label, fraction in (("part way", 0.5), ("all the way", 1.0)): + pointer.glide(px + round(dx * fraction), py + round(dy * fraction), steps=12, ms=30) + expect = want * fraction + + def moved(now: dict[str, Box], n: str) -> int: + return edges(now[n])[OPPOSITE[held]] - edges(before[n])[OPPOSITE[held]] + + # the pointer is held there; the neighbors follow + kde.wait_for( + lambda expect=expect: all(abs(moved(frames(), n) - expect) <= CELL for n in near), + timeout=5, + ) + now = frames() + held_at[label] = now + print(f"{case} {label}: the pointer is at {where()}, the frames {now}") + + for n in near: + if abs(moved(now, n) - expect) > CELL: + problems.append( + f"{label}: {n}'s {OPPOSITE[held]} edge is {moved(now, n)} from where it was," + f" the pointer {expect:.0f}" + ) + for other, r in before.items(): + if other == name or other in near: + continue + if any(abs(edges(now[other])[e] - edges(r)[e]) > CELL for e in "LTRB"): + # a tile that shares the dragged edge's line may move with it; nothing else may + shared = any(abs(edges(r)[e] - edges(before[name])[held]) <= 80 for e in "LTRB") + if not shared: + problems.append(f"{label}: {other} moved, and it is not next to the edge") + + pointer.up() + kde.wait_for(lambda: resize_ends() > ends, timeout=10) + after = settled() + + for n in near: + jump = ( + edges(after[n])[OPPOSITE[held]] - edges(held_at["all the way"][n])[OPPOSITE[held]] + ) + if abs(jump) > CELL: + problems.append(f"{n} jumped {jump} when the button was let go") + + names = list(after) + for i, n1 in enumerate(names): + x, y, w, h = after[n1] + if x < 0 or y < 0 or x + w > W or y + h > H: + problems.append(f"{n1} {after[n1]} is off the screen") + for n2 in names[i + 1 :]: + ox, oy, ow, oh = after[n2] + if x < ox + ow and ox < x + w and y < oy + oh and oy < y + h: + problems.append(f"{n1} and {n2} overlap") + + print(f"{case}: neighbors {near}, before {before}, let go {after}") + return problems + + # BSP: win1 is the left half, win2 the top right and win3 the bottom right + cases = [ + "win2:left:-120,0", + "win2:left:90,0", + "win2:bottom:0,100", + "win3:top:0,-80", + "win1:right:100,0", + ] + for case in cases: + problems = run_case(case) + checks.check( + f"{case}: " + ("as expected" if not problems else "; ".join(problems)), not problems + ) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/lock_sleep.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/lock_sleep.py new file mode 100644 index 00000000..9e6ceb86 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/lock_sleep.py @@ -0,0 +1,143 @@ +r"""The screen being locked and unlocked in a real Plasma session, with komorebi running as the +module's user unit. What only a real session can tell: that the lock screen is not tiled (it is a +window of KWin's, on every desktop and in no task list), that nothing komorebi does while the +screen is locked changes the layout, and that when the screen is unlocked komorebi looks at the +desktop again and puts every window where its tile is, with its idea of the focus KWin's. + +A real suspend and resume is not tested: the QEMU guest has no way to wake from one. The signals +komorebi waits for, logind's `PrepareForSleep` and the lock screen's `ActiveChanged`, are +tested on private buses by `komorebi/tests/power.rs`, and the desktop it finds on waking against +the fake by `komorebi/tests/wake.rs`. +""" + +import time +from typing import Any + +from komorebi_vm import Checks, Kde, Rect + +UNIT = "komorebi.service" +TITLES = ["sl-a", "sl-b", "sl-c"] +# what a terminal's frame may be off its tile by: up to a cell of its font +CELL = 24 +# the daemon's log of the day, without colors, which the unit writes +LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `lock-sleep`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + + def daemon_log() -> str: + return machine.execute(f"cat {LOG}")[1] + + def frames() -> list[Rect]: + return [kde.rect(kde.wid(title)) for title in TITLES] + + def settled_frames() -> list[Rect]: + """The frames the windows have once they have stopped moving: the same a second apart. + + A window that opens makes komorebi tile the others again, so the frames are not the tiles + until the last window has had its turn. + """ + seen: list[list[Rect]] = [] + + def still() -> bool: + seen.append(frames()) + time.sleep(1 * SCALE) + return len(seen) >= 2 and seen[-1] == seen[-2] + + kde.wait_for(still, timeout=60) + return seen[-1] + + def tile_of(title: str) -> Rect: + """The tile the daemon has for the window now, from its layout.""" + workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] + for i, container in enumerate(workspace["containers"]["elements"]): + windows = container["windows"] + if windows["elements"][windows["focused"]]["details"]["title"] == title: + tile = workspace["latest_layout"][i] + return Rect(tile["left"], tile["top"], tile["right"], tile["bottom"]) + raise AssertionError(f"the daemon has no container for {title}") + + def near(a: Rect, b: Rect) -> bool: + """Whether the frame is the tile, give or take the cell of the terminal's font.""" + return max(abs(a.x - b.x), abs(a.y - b.y), abs(a.w - b.w), abs(a.h - b.h)) <= CELL + + def session_id() -> str: + """The id of the user's graphical session, which is the one that gets locked.""" + for line in kde.sh("loginctl list-sessions --no-legend").splitlines(): + words = line.split() + if len(words) > 2 and words[2] == "komorebi": + shown = kde.sh(f"loginctl show-session {words[0]} -p Type --value") + if shown.strip() == "wayland": + return words[0] + raise AssertionError("the user has no Wayland session") + + print("== 1. komorebi runs in the session, and has three windows") + checks.check( + "the module's unit runs the daemon, which answers komorebic", + kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=60), + ) + # The daemon tiles the windows again when it learns of the panel's room. They are opened after that, + # so that they are tiled once. The wait is not a check: a session may never take the room, and it + # ends after a while. + kde.wait_for_panel_room() + for title in TITLES: + kde.spawn(f"foot -T {title} sleep 3010") + kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=60) + checks.check( + "komorebi manages the three", kde.wait_for(lambda: kde.managed(0) == 3, timeout=30) + ) + checks.check( + "they are tiled: none is on another", + kde.wait_for( + lambda: ( + not any(a.overlaps(b) for i, a in enumerate(frames()) for b in frames()[i + 1 :]) + ) + ), + ) + tiles = settled_frames() + sid = session_id() + print(f" session {sid}; tiles: {tiles}") + + print("== 2. the screen is locked, and a window is moved while nothing can be drawn") + kde.sh(f"loginctl lock-session {sid}") + checks.check( + "komorebi noticed the lock screen coming up", + kde.wait_for(lambda: "the screen was locked" in daemon_log(), timeout=30), + ) + kde.sh(f"kdotool windowmove {kde.wid('sl-b')} 400 300") + checks.check( + "while it is locked komorebi has the same three windows: the lock screen is not one", + kde.managed(0) == 3, + ) + checks.check( + "the other two did not move for it", + kde.rect(kde.wid("sl-a")) == tiles[0] and kde.rect(kde.wid("sl-c")) == tiles[2], + ) + + print("== 3. the screen is unlocked") + kde.sh(f"loginctl unlock-session {sid}") + checks.check( + "komorebi noticed the screen being unlocked", + kde.wait_for(lambda: "the screen was unlocked" in daemon_log(), timeout=30), + ) + # the tile it has now, not the one it had: the shell's panel can take room from the windows after + # the windows were tiled, and the daemon puts every window in the room that is left + checks.check( + "the window that was moved is in its tile again", + kde.wait_for(lambda: near(kde.rect(kde.wid("sl-b")), tile_of("sl-b")), timeout=30), + ) + checks.check("it still has three windows", kde.managed(0) == 3) + checks.check( + "its idea of the focus is KWin's", + kde.wait_for( + lambda: kde.active() != "" and kde.title(kde.active()) == kde.focused_title(0), + timeout=30, + ), + ) + checks.check( + "and it is still running", + kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0, + ) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/look.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/look.py new file mode 100644 index 00000000..d2689e1e --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/look.py @@ -0,0 +1,232 @@ +r"""The border and the animation, in a real Plasma session whose machine has the effects installed +(the module does that): komorebi writes the effects' settings, loads them, and on exit puts +everything back. + +What is checked is what is on the screen, not what komorebi wrote: a screenshot is read at the +pixels just outside each window's frame (the border) and at the place a window is going to (the +animation). The runs of komorebi: + + A the borders, as they are by default: the ring is outside the frame on all four sides + B the commands that change them: the effect follows, and takes the border away and back + C a 30 s animation: a window flipped to the other side is not there yet moments later + D no animation, the control: the same flip is there at once + +Every window is a `foot` of one color all over (`Kde.colored_window`). +""" + +import time +from typing import Any + +from komorebi_vm import Checks, Kde, Rect, daemon, pixels + +UNIT = "komorebi.service" +# the daemon's log of the day, without colors, which every run of the unit adds to +LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" +ROUNDED_CORNERS = "kwin4_effect_shapecorners" +GROUP = "Round-Corners" +GEOMETRY_CHANGE = "kwin4_effect_geometry_change" +ANIMATION_GROUP = "Effect-kwin4_effect_geometry_change" +FOCUSED = (66, 165, 245) +UNFOCUSED = (128, 128, 128) +RED = (255, 0, 0) + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `look`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + + def running() -> bool: + return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 + + def answering() -> bool: + return kde.run("komorebic monitor-information")[0] == 0 + + def asked(title: str) -> Rect | None: + """The frame the daemon last asked KWin for, for the window with this title.""" + return daemon.asked(machine.execute(f"cat {LOG}")[1], title) + + def start_komorebi() -> None: + kde.systemctl("start", UNIT) + kde.wait_for(answering, timeout=60) + # The shell's panel takes room from the windows a while after the shell has made it, and the + # daemon learns that up to a second later. The windows are opened after that: before it they + # are tiled under the panel and then again, and the ring is read in between. + kde.wait_for_panel_room() + # the border effect is written, loaded and told to read its settings as the daemon starts + time.sleep(2) + + def stop_komorebi() -> None: + kde.systemctl("stop", UNIT) + kde.close_colored_windows() + + print("== the effect is installed, and not loaded by anyone") + # the session started the module's unit when it logged in: this test starts its own runs + stop_komorebi() + checks.check("KDE Rounded Corners is installed", kde.effect_supported(ROUNDED_CORNERS)) + checks.check("Geometry Change is installed", kde.effect_supported(GEOMETRY_CHANGE)) + checks.check( + "and KWin does not load either by itself (they are built disabled by default)", + not kde.effect_loaded(ROUNDED_CORNERS) and not kde.effect_loaded(GEOMETRY_CHANGE), + ) + before = kde.kwinrc_group(GROUP) + before_animation = kde.kwinrc_group(ANIMATION_GROUP) + + def put_back() -> None: + checks.check("komorebi exited", not running()) + checks.check("the border effect is unloaded again", not kde.effect_loaded(ROUNDED_CORNERS)) + checks.check( + "the animation effect is unloaded again", not kde.effect_loaded(GEOMETRY_CHANGE) + ) + checks.check(f"kwinrc [{GROUP}] is as it was", kde.kwinrc_group(GROUP) == before) + checks.check( + f"kwinrc [{ANIMATION_GROUP}] is as it was", + kde.kwinrc_group(ANIMATION_GROUP) == before_animation, + ) + + print("== A. komorebi starts, with the borders it has by default") + start_komorebi() + checks.check("the border effect is loaded", kde.effect_loaded(ROUNDED_CORNERS)) + rc = kde.kwinrc_group(GROUP) + checks.check( + "the border is the outer outline: 10 px, colored like the focused window", + rc.get("OuterOutlineThickness") == "10" and rc.get("OuterOutlineColor") == "66,165,245", + ) + checks.check( + "nothing is drawn inside the window, over its title bar (the effect's default does)", + rc.get("OutlineThickness") == "0" and rc.get("SecondOutlineThickness") == "0", + ) + checks.check( + "the unfocused window gets the other color", + rc.get("InactiveOuterOutlineColor") == "128,128,128", + ) + checks.check("the corner radius is the border radius", rc.get("Size") == "10") + + print("== A. two windows, side by side") + kde.colored_window("red", "ff0000") + time.sleep(1) + kde.colored_window("blue", "0000ff") + checks.check("komorebi tiles both", kde.wait_for(lambda: kde.managed() == 2, timeout=30)) + time.sleep(3) + red, blue = kde.wid("red"), kde.wid("blue") + red_frame, blue_frame = kde.rect(red), kde.rect(blue) + print(f" red: {red_frame} blue: {blue_frame}") + checks.check("they are next to each other", not red_frame.overlaps(blue_frame)) + image = kde.shot("tiled") + + print("== A. the border is just outside the frame, on all four sides") + wrong = pixels.ring(image, blue_frame, FOCUSED) + checks.check( + "the focused window (blue) has the focus color around it" + + "".join(f"\n {w}" for w in wrong), + wrong == [], + ) + wrong = pixels.ring(image, red_frame, UNFOCUSED) + checks.check( + "the other window (red) has the unfocused color around it" + + "".join(f"\n {w}" for w in wrong), + wrong == [], + ) + inside = pixels.pixel(image, blue_frame.x + 40, blue_frame.y + 5) + checks.check( + f"the border does not cover the title bar (inside the frame, near its top: {inside})", + not pixels.near(inside, FOCUSED), + ) + + print("== B. the commands that set the border reach the effect") + kde.komorebic("border-width", "6") + checks.check( + "a narrower border is a thinner outline", + kde.wait_for( + lambda: kde.kwinrc_group(GROUP).get("OuterOutlineThickness") == "6", timeout=10 + ), + ) + kde.komorebic("border", "disable") + checks.check( + "no border unloads the effect", kde.wait_for(lambda: not kde.effect_loaded(ROUNDED_CORNERS)) + ) + checks.check(f"and puts kwinrc [{GROUP}] back as it was", kde.kwinrc_group(GROUP) == before) + kde.komorebic("border", "enable") + checks.check( + "a border again loads the effect, with the width that was set", + kde.wait_for(lambda: kde.effect_loaded(ROUNDED_CORNERS), timeout=10) + and kde.kwinrc_group(GROUP).get("OuterOutlineThickness") == "6", + ) + + print("== B. the layout leaves the room the border takes") + room = asked("blue") + kde.komorebic("border-width", "0") + kde.komorebic("retile") + + def grew() -> bool: + now = asked("blue") + return room is not None and now is not None and (now.w - room.w, now.h - room.h) == (20, 20) + + checks.check( + f"without the 10 px of border on each side the tile is 20 px wider and higher ({room})", + kde.wait_for(grew, timeout=10), + ) + + stop_komorebi() + put_back() + + def flip_of_red() -> tuple[Rect, Rect]: + """Flips the layout, and returns the frame red had and the one komorebi gave it.""" + kde.colored_window("red", "ff0000") + time.sleep(1) + kde.colored_window("blue", "0000ff") + kde.wait_for(lambda: kde.managed() == 2, timeout=30) + # well past the half of it, where an ease out is at 97 %: the windows have got where they go + time.sleep(16 * SCALE) + before_flip = kde.rect(kde.wid("red")) + kde.komorebic("flip-layout", "horizontal") + kde.wait_for(lambda: kde.rect(kde.wid("red")) != before_flip, timeout=10) + return before_flip, kde.rect(kde.wid("red")) + + def point_in(frame: Rect) -> tuple[int, int]: + """A point inside the frame, far from where red came from, which is on its left.""" + return frame.x + frame.w - 60, frame.y + frame.h // 2 + + print("== C. komorebi runs a 30 s animation") + start_komorebi() + kde.komorebic("animation-duration", "30000") + # an ease out is at 97 % after half of its time, which the waits below rely on (the default style + # is linear, which is at half) + kde.komorebic("animation-style", "--style", "ease-out-expo") + kde.komorebic("animation", "enable") + checks.check( + "the animation effect is loaded", + kde.wait_for(lambda: kde.effect_loaded(GEOMETRY_CHANGE), timeout=10), + ) + animation = kde.kwinrc_group(ANIMATION_GROUP) + checks.check( + "it lasts what it was asked to, without cross-fading", + animation.get("Duration") == "30000" and animation.get("CrossFade") == "false", + ) + was, now = flip_of_red() + print(f" red: {was} -> {now}") + checks.check("komorebi moved the window", was != now) + x, y = point_in(now) + soon = pixels.pixel(kde.shot("soon"), x, y) + checks.check( + f"a moment after the flip red has not got to its new place ({soon})", + not pixels.near(soon, RED), + ) + time.sleep(16 * SCALE) + later = pixels.pixel(kde.shot("later"), x, y) + checks.check(f"and 16 s later it has ({later})", pixels.near(later, RED)) + stop_komorebi() + put_back() + + print("== D. without an animation, the control, the same flip is there at once") + start_komorebi() + checks.check("the animation effect is not loaded", not kde.effect_loaded(GEOMETRY_CHANGE)) + was, now = flip_of_red() + x, y = point_in(now) + at_once = pixels.pixel(kde.shot("control"), x, y) + checks.check( + f"red is at its new place when the screenshot is taken ({at_once})", + pixels.near(at_once, RED), + ) + stop_komorebi() + put_back() diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/module.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/module.py new file mode 100644 index 00000000..d5b64a03 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/module.py @@ -0,0 +1,211 @@ +r"""The NixOS module runs komorebi in a real Plasma session: nothing in this test starts the daemon. +What only a real session can tell: that logging in starts the module's user unit through +`plasma-workspace.target`, that the daemon it runs reaches KWin from there and tiles a window +opened in the session, that it runs with the module's log level, the `komorebi.json` the module +wrote from its `config`, and the PATH of the user's session, that systemd starts it again when +it is killed, and that a clean stop is not a failure. Once the unit is stopped, the daemon is +started with a `komorebi.json` of the user's, which it follows when the file changes, and +`komorebic enable-autostart` writes the entry systemd's autostart generator makes a unit of. The +options and the unit the module writes are checked without a machine by `nixos-module-eval` +(`nix/tests/nixos-module.nix`). +""" + +import json +import shlex +from typing import Any + +from komorebi_vm import Checks, Kde, Rect, daemon + +UNIT = "komorebi.service" +# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for +CELL = 24 +# the daemon's log of the day, without colors, which the unit's journal has +LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `module`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + + def active() -> bool: + return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 + + def failed() -> bool: + return kde.run(f"systemctl --user is-failed --quiet {UNIT}")[0] == 0 + + def main_pid() -> str: + return kde.sh(f"systemctl --user show --property MainPID --value {UNIT}").strip() + + def answering() -> bool: + return kde.run("komorebic monitor-information")[0] == 0 + + def managed_titles() -> list[str]: + """The titles of the windows komorebi has on the first workspace of the first monitor.""" + workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] + return [ + window["details"]["title"] + for container in workspace["containers"]["elements"] + for window in container["windows"]["elements"] + ] + + def daemon_log() -> str: + return machine.execute(f"cat {LOG}")[1] + + print("== 1. logging in starts komorebi") + checks.check("the session started the module's unit", kde.wait_for(active, timeout=60)) + checks.check("its daemon answers komorebic", kde.wait_for(answering, timeout=60)) + + pid = main_pid() + command = kde.sh(f"tr '\\0' ' ' < /proc/{pid}/cmdline").split() + print(f" the unit runs: {' '.join(command)}") + checks.check("the unit runs bin/komorebi", command[0].endswith("/bin/komorebi")) + checks.check("... at the module's log level", command[1:3] == ["--log-level", "debug"]) + checks.check( + "... with the komorebi.json the module wrote as its --config", + len(command) == 5 and command[3] == "--config" and command[4].endswith("-komorebi.json"), + ) + environment = kde.sh(f"tr '\\0' '\\n' < /proc/{pid}/environ").splitlines() + path = next((line[len("PATH=") :] for line in environment if line.startswith("PATH=")), "") + checks.check( + "... with the PATH of the user's session", + path.split(":") + == [ + "/run/wrappers/bin", + "/etc/profiles/per-user/komorebi/bin", + "/run/current-system/sw/bin", + ], + ) + + print("== 1b. the daemon is configured by the file") + workspaces = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"] + checks.check( + "its workspaces are the ones the file names", + [workspace["name"] for workspace in workspaces] == ["web", "code"], + ) + checks.check( + "KWin has a virtual desktop for each of them", + kde.wait_for(lambda: kde.desktops() >= 2, timeout=30), + ) + checks.check( + "the settings the daemon says it has are the file's", + json.loads(kde.komorebic("generate-static-config"))["default_workspace_padding"] == 40, + ) + + print("== 2. a window opened in the session is tiled") + width = json.loads(kde.komorebic("monitor-information"))[0]["size"]["right"] + + def asked() -> Rect | None: + return daemon.asked(daemon_log(), "tiled") + + def tiled() -> bool: + """KWin has the window where komorebi asked, and that is a tile across the screen.""" + want, wid = asked(), kde.wid("tiled") + if want is None or wid == "": + return False + have = kde.rect(wid) + return ( + (have.x, have.y) == (want.x, want.y) + and 0 <= want.w - have.w < CELL + and 0 <= want.h - have.h < CELL + and want.w > width // 2 + ) + + kde.spawn("foot -T tiled sleep 3000") + checks.check("the window opens", kde.wait_for(lambda: kde.wid("tiled") != "", timeout=60)) + checks.check( + "komorebi manages it", kde.wait_for(lambda: "tiled" in managed_titles(), timeout=30) + ) + checks.check("KWin has it on its tile", kde.wait_for(tiled, timeout=30)) + print(f" asked {asked()}, has {kde.rect(kde.wid('tiled'))}") + want = asked() + checks.check( + "its tile is as far from the edge as the file's workspace padding says", + want is not None and want.x == 40, + ) + + print("== 3. systemd starts a komorebi that was killed again") + kde.systemctl("kill", "--signal=SIGKILL", UNIT) + checks.check( + "the unit runs a new daemon", + kde.wait_for(lambda: active() and main_pid() not in ("0", pid), timeout=30), + ) + checks.check("... which answers komorebic", kde.wait_for(answering, timeout=60)) + checks.check( + "... and manages the window again", + kde.wait_for(lambda: "tiled" in managed_titles(), timeout=30), + ) + + print("== 4. a stop is not a failure") + kde.systemctl("stop", UNIT) + checks.check("stopped with SIGTERM, the unit is inactive", not active()) + checks.check("... and not failed", not failed()) + kde.systemctl("start", UNIT) + checks.check("started again, its daemon answers", kde.wait_for(answering, timeout=60)) + kde.komorebic("stop") + checks.check("komorebic stop stops the unit", kde.wait_for(lambda: not active(), timeout=30)) + checks.check("... which is not failed", not failed()) + checks.check("... and not started again", not kde.wait_for(active, timeout=5)) + + print("== 5. a daemon follows the file it is started with, and reloads it when it changes") + MINE = "/home/komorebi/mine.json" + + def write(text: str) -> None: + kde.sh(f"printf %s {shlex.quote(text)} > {MINE}") + + def resize_delta() -> int: + return json.loads(kde.komorebic("generate-static-config"))["resize_delta"] + + def workspace_names() -> list[str]: + elements = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"] + return [workspace["name"] for workspace in elements] + + write('{ "resize_delta": 100 }') + kde.komorebic("start", "--config", MINE) + checks.check("komorebic start --config starts a daemon that answers", kde.wait_for(answering)) + checks.check("... which has the settings of the file", resize_delta() == 100) + + write( + '{ "resize_delta": 33, "monitors": [ { "workspaces": [' + ' { "name": "one" }, { "name": "two" }, { "name": "three" } ] } ] }' + ) + checks.check( + "a change to the file is applied", + kde.wait_for( + lambda: resize_delta() == 33 and workspace_names() == ["one", "two", "three"], + timeout=30, + ), + ) + kde.komorebic("focus-workspace", "2") + checks.check( + "... and a workspace it added is one KWin shows", + kde.wait_for(lambda: kde.shown() == 3, timeout=30), + ) + kde.komorebic("stop") + checks.check("that daemon stops", kde.wait_for(lambda: not answering(), timeout=30)) + + print("== 6. an autostart entry is run by the session") + ENTRY = "/home/komorebi/.config/autostart/komorebi.desktop" + AUTOSTART = "app-komorebi@autostart.service" + kde.komorebic("enable-autostart", "--config", MINE) + checks.check( + "komorebic enable-autostart writes the entry, with the file it is given", + f'Exec=komorebi --config "{MINE}"' in machine.succeed(f"cat {ENTRY}"), + ) + kde.systemctl("daemon-reload") + status, unit_text = kde.run(f"systemctl --user cat {AUTOSTART}") + print(unit_text) + checks.check( + "systemd's autostart generator makes a unit of it, which runs komorebi", + status == 0 and "komorebi" in unit_text, + ) + kde.systemctl("start", AUTOSTART) + checks.check("... which starts a daemon that answers", kde.wait_for(answering, timeout=60)) + checks.check("... with the file the entry gave it", resize_delta() == 33) + kde.komorebic("stop") + checks.check("that daemon stops", kde.wait_for(lambda: not answering(), timeout=30)) + kde.komorebic("disable-autostart") + checks.check( + "komorebic disable-autostart takes the entry away", + machine.execute(f"test -e {ENTRY}")[0] != 0, + ) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/rdp.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/rdp.py new file mode 100644 index 00000000..9ee53852 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/rdp.py @@ -0,0 +1,60 @@ +r"""KRDP, Plasma's RDP server, runs in the Plasma session of the session node as the guest to develop +in runs it (nix/dev/krdp.nix), and a client logs in and gets a picture of the desktop. What only a +real session can tell: that the unit starts in the session once it has a password, that KWin lets +KRDP have the screen without asking, that a client with the password is let in and one without +it is not, and that the picture the client gets is what the display shows. + +The client is FreeRDP's, on an X server of its own (`komorebi_vm.RdpClient`), so its picture can be +read back and compared with a screenshot of the display. The suite `run-kde` runs the same checks +with a password that the demo guest takes from the host's directory. +""" + +import secrets +import time +from typing import Any + +from komorebi_vm import Checks, Kde, RdpClient +from komorebi_vm.rdp import colors + +PASSWORD_FILE = "/home/komorebi/.config/komorebi-vm/rdp-password" + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `rdp`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + rdp = RdpClient(machine, kde) + + def active(unit: str) -> bool: + return kde.run(f"systemctl --user is-active --quiet {unit}")[0] == 0 + + checks.check( + "komorebi runs in the session", kde.wait_for(lambda: active("komorebi"), timeout=60) + ) + checks.check("with no password, KRDP does not start", not active("krdp")) + + password = secrets.token_hex(16) + kde.as_user( + f"umask 077 && mkdir -p $(dirname {PASSWORD_FILE}) && printf %s {password} > {PASSWORD_FILE}" + ) + kde.systemctl("start", "krdp.service") + + checks.check( + "with a password, KRDP listens on port 3389", kde.wait_for(rdp.listening, timeout=60) + ) + + rdp.start_x_server() + + checks.check("a client with the password is let in", rdp.logs_in(password)) + checks.check("a client with another password is not", not rdp.logs_in("not-" + password)) + + started = time.monotonic() + rdp.connect(password) + checks.check("the client's picture is the display", rdp.shows_display()) + print(f"after {time.monotonic() - started:.1f}s") + + remote = rdp.picture() + print(f"the client's picture: {remote.size}, {colors(remote)} colors") + remote.save(machine.out_dir / "client.png") + print(machine.execute("journalctl --no-pager _SYSTEMD_USER_UNIT=krdp.service | tail -n 20")[1]) + print(machine.execute("tail -n 20 /tmp/xfreerdp.log")[1]) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/render_smoke.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/render_smoke.py new file mode 100644 index 00000000..74349f12 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/render_smoke.py @@ -0,0 +1,40 @@ +r"""A Plasma session draws a desktop in the test machine, so that every test after this one can trust +a screenshot. KSplash has thousands of colors on it too, so "not blank" is not the check: the +splash has to be gone and a window has to be painted on the desktop. +""" + +import time +from typing import Any + +from komorebi_vm import Checks, Kde + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `render-smoke`, which the suite script calls.""" + SCALE = scale # noqa: N806 + started = time.monotonic() + kde = Kde.session(machine, scale=SCALE) + print(f"the desktop is up after {time.monotonic() - started:.0f}s") + + def konsole() -> str: + return kde.run("kdotool search --class konsole | head -1")[1].strip() + + kde.spawn("konsole") + checks.check("a window appears", kde.wait_for(lambda: konsole() != "", timeout=60)) + rect = kde.rect(konsole()) + checks.check("the window has a size", rect.w > 0 and rect.h > 0) + + def painted() -> bool: + image = kde.shot("desktop") + center = image.getpixel((rect.x + rect.w // 2, rect.y + rect.h // 2)) + assert isinstance(center, tuple) + # the terminal's background is dark; the wallpaper behind it is not + return sum(center) < 3 * 90 + + checks.check("the window is painted on the screen", kde.wait_for(painted, timeout=60)) + + image = kde.shot("desktop") + colors = image.getcolors(maxcolors=image.width * image.height) + assert colors is not None + print(f"the screenshot is {image.size[0]}x{image.size[1]} with {len(colors)} colors") + checks.check("the desktop behind it is drawn", len(colors) > 5000) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/restart_survival.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/restart_survival.py new file mode 100644 index 00000000..1f1d76a8 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/restart_survival.py @@ -0,0 +1,116 @@ +r"""The keys of the engine survive the daemon and KWin going away. kglobalaccel keeps the keys of a +client that died, swallowed and running nothing, until they are unregistered; and it runs inside +KWin, so a KWin that restarts forgets them. Only a real session can say that the module's unit +releases the keys of a daemon that was killed, that a new daemon takes them over, and that the +daemon registers them again with the kglobalaccel of a new KWin. +""" + +import json +import shlex +from typing import Any + +from komorebi_vm import Checks, Kde, Keys + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `restart-survival`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + keys = Keys(machine) + + def presses() -> int: + """How many times a binding has run.""" + return len(machine.execute("cat /tmp/keys-restart")[1].split()) + + def press(combo: str) -> bool: + before = presses() + keys.send(combo) + return kde.wait_for(lambda: presses() > before, timeout=10) + + def registered(actions: list[str], timeout: float = 30) -> bool: + return kde.wait_for(lambda: kde.shortcut_actions() == actions, timeout=timeout) + + def write(skhdrc: str) -> None: + kde.sh( + f"mkdir -p ~/.config/komorebi && printf '%s' {shlex.quote(skhdrc)}" + " > ~/.config/komorebi/skhdrc" + ) + + def main_pid() -> str: + return kde.systemctl("show", "--property=MainPID", "--value", "komorebi.service").strip() + + # the module's unit runs the daemon, which reads the skhdrc of the config directory at start + write("alt - h : echo h >> /tmp/keys-restart\n") + kde.systemctl("restart", "komorebi.service") + checks.check("the daemon of the unit registers Alt+H", registered(["Alt+H"])) + checks.check("Alt+H runs its binding", press("alt-h")) + + state = json.loads(kde.komorebic("hotkeys", "state")) + checks.check( + f"hotkeys state shows the key and the engine ({state})", + state["registered"] == ["Alt+H"] + and state["engine"]["mode"] == "default" + and state["engine"]["active"] == ["Alt+H"], + ) + + # a daemon that does not answer leaves its keys dead, until they are released + machine.succeed("pkill -STOP -x komorebi") + before = presses() + keys.send("alt-h") + checks.check( + "the key of a stopped daemon runs nothing", + not kde.wait_for(lambda: presses() > before, timeout=3), + ) + released = kde.komorebic("hotkeys", "release") + checks.check(f"hotkeys release unregisters it ({released.strip()})", "Alt+H" in released) + checks.check("no key is registered after the release", kde.shortcut_actions() == []) + machine.succeed("pkill -CONT -x komorebi") + kde.systemctl("restart", "komorebi.service") + checks.check("a new daemon registers the key again", registered(["Alt+H"])) + checks.check("Alt+H runs its binding again", press("alt-h")) + + # a daemon that is killed: the unit releases its keys, and systemd starts a new one + old = main_pid() + # the main process alone, as a crash: killing the whole unit would kill ExecStopPost too + kde.systemctl("kill", "--kill-whom=main", "--signal=SIGKILL", "komorebi.service") + checks.check( + "systemd starts the daemon again", + kde.wait_for(lambda: main_pid() not in ("0", old), timeout=30), + ) + + def journal() -> str: + """The journal of the machine since it booted: the unit's lines, ExecStopPost's among them.""" + return machine.execute("journalctl --no-pager -o cat -b")[1] + + released = kde.wait_for(lambda: "released 1 keys: Alt+H" in journal(), timeout=10) + words = ("released", "had no key", "could not release", "komorebi.service") + seen = [line for line in journal().splitlines() if any(word in line for word in words)] + checks.check( + f"the unit released the keys of the killed daemon (it logged {seen[-6:]})", released + ) + checks.check("the new daemon has the key", registered(["Alt+H"])) + checks.check("Alt+H runs its binding after the kill", press("alt-h")) + + # KWin restarts, and kglobalaccel with it + kwins = machine.succeed("pgrep -a kwin_wayland || true") + print(kwins) + compositors = [ + line.split()[0] + for line in kwins.splitlines() + if line.strip() and "wrapper" not in line.split()[1] + ] + machine.succeed(f"kill -KILL {' '.join(compositors)}") + checks.check( + "a new KWin owns kglobalaccel", + kde.wait_for(lambda: kde.has_name("org.kde.kglobalaccel"), timeout=60), + ) + checks.check( + "the daemon registers the key with the new KWin", registered(["Alt+H"], timeout=60) + ) + checks.check("Alt+H runs its binding after KWin restarted", press("alt-h")) + + # a reload reads the file again + write("alt - j : echo j >> /tmp/keys-restart\n") + kde.komorebic("hotkeys", "reload") + checks.check("after a reload the daemon has the key of the new file", registered(["Alt+J"])) + checks.check("Alt+J runs its binding", press("alt-j")) diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/run_kde.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/run_kde.py new file mode 100644 index 00000000..f7f69b79 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/run_kde.py @@ -0,0 +1,163 @@ +r"""The demo guest of `run-kde` (nix/dev/run-kde.nix), as the command starts it: the module is the +session node's. What only a real session can tell: that the demo opens its windows and komorebi +tiles them clear of the panel, that the cheat sheet is a window komorebi leaves alone, that what +the cheat sheet shows of `komorebic check` has no error in it, and that the password and the key +the host shares reach the units that use them. The host's directory is made as the guest finds it +when it has mounted it (the node says how): another user owns it, so that the guest's own user +cannot read what is in it, and the guest has to take it as root. + +The RDP checks are those of the suite `rdp`, with the password from that directory. Nothing starts +KRDP by hand here: that it listens shows that the guest took the password before the login, as the +command's guest has to. The command itself, `scripts/run-kde`, is checked by `run-kde-dry-run` and +`run-kde-doctor`, which a VM cannot: it is a program of the host. +""" + +import re +from typing import Any + +from komorebi_vm import Checks, Kde, RdpClient +from komorebi_vm.rdp import colors + +SHARED = "/run/run-kde" +TAKEN = "/run/run-kde-guest" +PASSWORD = "a-password-of-the-host" +CHEAT_SHEET_TITLE = "komorebi cheat sheet" + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `run-kde`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + rdp = RdpClient(machine, kde) + + def active(unit: str) -> bool: + return kde.run(f"systemctl --user is-active --quiet {unit}")[0] == 0 + + def tiles() -> list[str]: + """The titles of the tiled windows of the first workspace, or none while the daemon is busy.""" + try: + return [title for container in kde.containers(0) for title in container] + except AssertionError: + return [] + + def demo_is_open() -> bool: + titles = tiles() + return ( + sum("Konsole" in title for title in titles) == 2 + and any("Kate" in title for title in titles) + and any("Dolphin" in title for title in titles) + ) + + checks.check( + "komorebi runs in the session", kde.wait_for(lambda: active("komorebi"), timeout=60) + ) + + print("== the windows of the demo") + checks.check( + "the demo opens two Konsole windows, Kate and Dolphin, and komorebi tiles them", + kde.wait_for(demo_is_open, timeout=240), + ) + checks.check( + "the cheat sheet is a window", + kde.wait_for(lambda: kde.wid(CHEAT_SHEET_TITLE) != "", timeout=120), + ) + titles = tiles() + print(f"the tiles: {titles}") + checks.check("the cheat sheet is not one of the tiles", len(titles) == 4) + + # a window tiled before komorebi knew the panel's room is tiled under the panel + monitor = kde.state()["monitors"]["elements"][0] + work = monitor["work_area_size"] + work_bottom = work["top"] + work["bottom"] + bottoms = {title: (lambda r: r.y + r.h)(kde.rect(kde.wid(title))) for title in titles} + print(f"the bottom of the work area: {work_bottom}; of the tiles: {bottoms}") + checks.check( + "every tile ends above the panel", + all(bottom <= work_bottom for bottom in bottoms.values()), + ) + checks.check("the screen shows a desktop", colors(kde.shot("demo")) > 1000) + + print("== the cheat sheet") + checks.check( + "the cheat sheet has the bindings of the sample file", + machine.execute("grep -q 'alt + shift - 0x21' /etc/run-kde/cheat-sheet.txt")[0] == 0 + and machine.execute("grep -q 'komorebic change-layout' /etc/run-kde/cheat-sheet.txt")[0] + == 0, + ) + checks.check( + "KWin's renderer is found, and said as the cheat sheet says it", + kde.wait_for( + lambda: machine.execute(f"test -s /run/user/{kde.uid}/run-kde-renderer")[0] == 0, + timeout=60, + ), + ) + renderer = machine.succeed(f"cat /run/user/{kde.uid}/run-kde-renderer").strip() + print(f"the renderer: {renderer}") + checks.check( + "a node with no GPU draws in software", + re.match(r"software \(llvmpipe\): ", renderer) is not None, + ) + checks.check( + "the console is told too", + machine.execute( + "journalctl -b -u run-kde-report --no-pager | grep -q 'run-kde: KWin draws with'" + )[0] + == 0, + ) + + status, out = kde.run("KOMOREBI_CONFIG_HOME=/etc/run-kde/config-home komorebic check") + print(out) + checks.check( + "komorebic check, as the cheat sheet runs it, has no error", + status == 0 and "\n0 error(s)" in out, + ) + checks.check( + "it reads the key bindings the daemon runs", + re.search(r"ok +\S*skhdrc has \d+ key bindings?", out) is not None, + ) + checks.check( + "it sees komorebi, and its script in KWin", + "komorebi is running, and its script is in KWin" in out, + ) + + print("== what the host shares") + checks.check( + "the guest's user cannot read the host's directory", + machine.execute(f"runuser -u komorebi -- cat {SHARED}/rdp-password")[0] != 0, + ) + checks.check( + "the password is taken for the user, and for no one else", + machine.succeed(f"stat -c '%U %a' {TAKEN}/rdp-password").strip() == "komorebi 400", + ) + checks.check( + "the key is taken as the user's authorized key", + machine.succeed(f"cat {TAKEN}/authorized_keys.d/komorebi").split()[:2] + == machine.succeed(f"cut -d' ' -f1,2 {SHARED}/ssh_key.pub").split(), + ) + machine.succeed("install -m 600 /etc/run-kde-test/ssh_key /tmp/ssh_key") + ssh = ( + "ssh -i /tmp/ssh_key -o IdentitiesOnly=yes -o StrictHostKeyChecking=no" + " -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o LogLevel=ERROR komorebi@127.0.0.1" + ) + machine.wait_for_unit("sshd.service") + checks.check("ssh lets in the host's key", machine.execute(f"{ssh} true")[0] == 0) + checks.check( + "and no other", + machine.execute( + "ssh-keygen -q -t ed25519 -N '' -f /tmp/other_key" + f" && {ssh.replace('/tmp/ssh_key', '/tmp/other_key')} true" + )[0] + != 0, + ) + + print("== RDP, with the host's password") + checks.check( + "KRDP started by itself and listens on port 3389", + kde.wait_for(lambda: active("krdp") and rdp.listening(), timeout=60), + ) + rdp.start_x_server() + checks.check("a client with the host's password is let in", rdp.logs_in(PASSWORD)) + checks.check("a client with another password is not", not rdp.logs_in("not-" + PASSWORD)) + rdp.connect(PASSWORD) + checks.check("the client's picture is the display", rdp.shows_display()) + rdp.picture().save(machine.out_dir / "client.png") diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/user_maximize.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/user_maximize.py new file mode 100644 index 00000000..fa02c913 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/user_maximize.py @@ -0,0 +1,162 @@ +r"""A window the user maximizes, in a real headless KWin. The user's title bar maximizes a window +without asking komorebi: KWin does it and reports it, and komorebi has to take the window out of +the layout as it does for `toggle-maximize`, leave the layout alone while the window is maximized, +and put the window back in its tile when it is restored, by the user or by komorebi. +`komorebi/tests/user_maximize.rs` checks what the window manager does against the fake; this +checks that KWin reports the user's maximize, and the restore, the way komorebi reads them. +""" + +import json +import shlex +import time +from typing import Any + +from komorebi_vm import Checks, Kde, Rect, daemon + +W, H = 1920, 1080 +# The windows are tiled with a gap of 10 pixels around the workspace and between the tiles: a tile +# has padding, and a maximized window has none. The windows are not animated. +CONFIG = "/tmp/user-maximize-config.json" + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `user-maximize`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) + + def workspace() -> dict[str, Any]: + return kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] + + def containers() -> int: + return len(workspace()["containers"]["elements"]) + + def maximized_title() -> str | None: + window = workspace()["maximized_window"] + return None if window is None else window["details"]["title"] + + def fills(r: Rect) -> bool: + """The work area is the whole output: a virtual KWin has no panel.""" + return r.w >= W - 40 and r.h >= H - 80 + + def rect_of(title: str) -> Rect: + return kde.rect(kde.wid(title)) + + def open_window(title: str) -> None: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda: kde.wid(title) != "", timeout=30) + + print("== three windows, tiled") + kde.sh( + "printf %s " + + shlex.quote( + json.dumps( + { + "default_workspace_padding": 10, + "default_container_padding": 10, + "animation": {"enabled": False}, + } + ) + ) + + f" > {CONFIG}" + ) + kde.start_komorebi("--config", CONFIG) + kde.wait_for(lambda: kde.run("komorebic monitor-information")[0] == 0, timeout=30) + for title in ("um-a", "um-b", "um-c"): + open_window(title) + checks.check("komorebi has three tiles", kde.wait_for(lambda: containers() == 3, timeout=20)) + # The bridge asks again for the position of a window that is not where komorebi put it for a second + # after it did (PLATFORM.md, "How clients answer a frame"), which would put a window that is + # maximized in that second back where its tile was: wait that second out, as a person would. + kde.wait_for(lambda: kde.focused_title() == "um-c", timeout=20) + time.sleep(3 * SCALE) + tiles = {title: rect_of(title) for title in ("um-a", "um-b", "um-c")} + print(f" the tiles are {tiles}") + + print("== 1. the user maximizes a window with its title bar") + kde.maximize(kde.wid("um-b")) + checks.check( + "komorebi has it as its maximized window", + kde.wait_for(lambda: maximized_title() == "um-b", timeout=20), + ) + checks.check( + f"it fills the work area ({rect_of('um-b')})", + kde.wait_for(lambda: fills(rect_of("um-b")), timeout=10), + ) + checks.check("and its tile is gone: two are left", containers() == 2) + checks.check( + "komorebi handled it as a change of the window's maximized state", + any( + event.kind == "MaximizeChange" and event.notification == "WindowMaximizedChanged" + for event in daemon.events(kde.komorebi_log()) + ), + ) + checks.check("it still has all three windows", kde.managed_all() == 3) + + print("== 2. what is asked of the layout does nothing") + beside = {title: rect_of(title) for title in ("um-a", "um-c")} + for command in [ + "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", + ]: + kde.komorebic(*command.split()) + time.sleep(1 * SCALE) + checks.check( + "it is still maximized, and still komorebi's maximized window", + fills(rect_of("um-b")) and maximized_title() == "um-b", + ) + checks.check( + "the others did not move, and nothing floats or is in the monocle", + {title: rect_of(title) for title in ("um-a", "um-c")} == beside + and containers() == 2 + and workspace()["floating_windows"]["elements"] == [] + and workspace()["monocle_container"] is None, + ) + checks.check( + "komorebi noted that it ignored them", + "ignoring" in kde.komorebi_log() + and "the window in front is maximized" in kde.komorebi_log(), + ) + + print("== 3. toggle-maximize restores it") + kde.komorebic("toggle-maximize") + checks.check( + f"it is back in its tile ({tiles['um-b']})", + kde.wait_for(lambda: rect_of("um-b") == tiles["um-b"], timeout=20), + ) + checks.check( + "and nothing is maximized", + maximized_title() is None and containers() == 3, + ) + + print("== 4. the user restores it with the title bar") + kde.maximize(kde.wid("um-c")) + checks.check( + "maximized again", + kde.wait_for(lambda: maximized_title() == "um-c" and containers() == 2, timeout=20), + ) + kde.unmaximize(kde.wid("um-c")) + checks.check( + f"restored by the user, it is back in its tile ({tiles['um-c']})", + kde.wait_for(lambda: rect_of("um-c") == tiles["um-c"], timeout=20), + ) + checks.check( + "and nothing is maximized", + kde.wait_for(lambda: maximized_title() is None and containers() == 3, timeout=10), + ) + + kde.komorebic("stop") + kde.wait_for(lambda: not kde.komorebi_running()) + kde.stop() diff --git a/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/wallpaper.py b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/wallpaper.py new file mode 100644 index 00000000..acfa8124 --- /dev/null +++ b/nix/tests/vm/lib/komorebi_vm/platforms/kde/extras/wallpaper.py @@ -0,0 +1,252 @@ +r"""Wallpapers, and the borders' colors that come from them, in a real Plasma session: what the shell +shows and what is on the screen, read from the shell's D-Bus API and from screenshots. + + A a monitor's wallpaper is set at start, and a workspace's own replaces it when it is shown + B a switch komorebi did not make (a pager's) sets the wallpaper too + C the borders take the colors of the wallpaper's palette, and follow it from workspace to + workspace + D a wallpaper the user changed by hand is put back when its workspace is shown again + E the palette cache, and a path with a space in it (the second picture's) + F komorebi that starts before the Plasma shell does + +The pictures are a dozen bands of color each, since a palette wants at least eight: a warm one for +the monitor, a cool one for the second workspace, and a green one the test sets by hand. +""" + +import base64 +import io +import re +import shlex +import time +from typing import Any + +from PIL import Image + +from komorebi_vm import Checks, Kde, Rect, pixels + +UNIT = "komorebi.service" +SHELL_UNIT = "plasma-plasmashell.service" +# the daemon's log of the day, without colors, which every run of the unit adds to +LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" +CONFIG = "/home/komorebi/.config/komorebi/komorebi.json" +PICTURES = "/tmp/wallpapers" +WARM = f"{PICTURES}/warm.png" +COOL = f"{PICTURES}/my pictures/cool.png" +OTHER = f"{PICTURES}/other.png" +WARM_URL = f"file://{PICTURES}/warm.png" +COOL_URL = f"file://{PICTURES}/my%20pictures/cool.png" +# `Image.PreserveAspectCrop`, which is how komorebi has the shell fill the screen +FILL = 2 + + +def run(machine: Any, checks: Checks, scale: float) -> None: + """Runs the checks of the suite `wallpaper`, which the suite script calls.""" + SCALE = scale # noqa: N806 + kde = Kde.session(machine, scale=SCALE) + + def picture(hue: tuple[int, int, int], ramp: int) -> bytes: + """A 192 by 108 PNG of diagonal bands of `hue`, going dark and light, `ramp` varying the hue.""" + data: list[tuple[int, int, int]] = [] + for y in range(108): + for x in range(192): + band = (x // 16 + y // 16) % 12 + shade = 40 + (band % 4) * 55 + red, green, blue = hue + green = min(255, green + band * ramp) + data.append( + ( + min(255, red * shade // 255), + min(255, green * shade // 255), + blue * shade // 255, + ) + ) + image = Image.new("RGB", (192, 108)) + image.putdata(data) + out = io.BytesIO() + image.save(out, "PNG") + return out.getvalue() + + def put(path: str, data: bytes) -> None: + """Writes `data` to `path` in the machine, where the test user can read it.""" + directory = shlex.quote(path.rsplit("/", 1)[0]) + encoded = base64.b64encode(data).decode() + machine.succeed(f"mkdir -p {directory} && chmod a+rx {directory}") + machine.succeed(f"echo {encoded} | base64 -d > {shlex.quote(path)}") + machine.succeed(f"chmod a+r {shlex.quote(path)}") + + def running() -> bool: + return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 + + def answering() -> bool: + return kde.run("komorebic monitor-information")[0] == 0 + + def start_komorebi() -> None: + kde.systemctl("start", UNIT) + kde.wait_for(answering, timeout=60) + time.sleep(2) + + def stop_komorebi() -> None: + kde.systemctl("stop", UNIT) + kde.close_colored_windows() + + def shell_wallpaper() -> tuple[str, int]: + """What the shell shows on its first screen: the picture's URL, and the fill mode.""" + out = kde.run( + "busctl --user call org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell wallpaper u 0" + )[1] + image = re.search(r'"Image" s "([^"]*)"', out) + fill = re.search(r'"FillMode" i (\d+)', out) + return (image.group(1) if image else "", int(fill.group(1)) if fill else -1) + + def shows(url: str) -> bool: + return shell_wallpaper()[0] == url + + def hue_of(image: Image.Image) -> str: + """Warm, cool or neither: the average color of a grid of points of the screen.""" + width, height = image.size + points = [ + pixels.pixel(image, width * i // 10, height * j // 12) + for i in range(1, 10) + for j in range(1, 9) + ] + red = sum(p[0] for p in points) / len(points) + blue = sum(p[2] for p in points) / len(points) + return "warm" if red > blue + 40 else "cool" if blue > red + 40 else "neither" + + def screen_is(hue: str, name: str) -> bool: + """Takes pictures of the screen until it is `hue`: one can catch the shell half way.""" + return kde.wait_for(lambda: hue_of(kde.shot(name)) == hue, timeout=20) + + def ring_hue(frame: Rect, image: Image.Image) -> str: + """The hue of the ring just outside the left edge of a frame.""" + red, _, blue = pixels.pixel(image, frame.x - 5, frame.y + frame.h // 2) + return "warm" if red > blue + 40 else "cool" if blue > red + 40 else "neither" + + def has_ring(title: str, hue: str, name: str) -> bool: + """Returns true if the window has a ring of `hue` in a screenshot taken until it does.""" + return kde.wait_for( + lambda: ring_hue(kde.rect(kde.wid(title)), kde.shot(name)) == hue, timeout=20 + ) + + print("== the pictures, and the wallpapers of the configuration") + put(WARM, picture((255, 0, 20), 20)) + put(COOL, picture((20, 80, 255), 14)) + put(OTHER, picture((60, 255, 60), 0)) + kde.sh(f"mkdir -p {shlex.quote(CONFIG.rsplit('/', 1)[0])}") + config = ( + '{ "monitors": [ { "wallpaper": { "path": "' + WARM + '" },' + ' "workspaces": [ { "name": "one" },' + ' { "name": "two", "wallpaper": { "path": "' + COOL + '" } } ] } ] }' + ) + kde.sh(f"echo {shlex.quote(config)} > {CONFIG}") + kde.sh("rm -rf ~/.cache/komorebi") + + # the session started the module's unit when it logged in: this test starts its own runs + stop_komorebi() + kde.sh(f"plasma-apply-wallpaperimage {shlex.quote(OTHER)}") + checks.check( + "the shell shows a picture of the user's choice to begin with", + kde.wait_for(lambda: shows(f"file://{OTHER}"), timeout=20), + ) + + print("== A. set at start, and by workspace") + start_komorebi() + checks.check( + "at start the shell shows the monitor's wallpaper", + kde.wait_for(lambda: shows(WARM_URL), timeout=20), + ) + checks.check("it fills the screen", shell_wallpaper()[1] == FILL) + checks.check("and the screen is warm", screen_is("warm", "a1")) + + began = time.monotonic() + kde.komorebic("focus-workspace", "1") + checks.check( + "workspace two's own wallpaper is shown when it is (the path has a space in it)", + kde.wait_for(lambda: shows(COOL_URL), timeout=10), + ) + took = time.monotonic() - began + checks.check(f"it took under two seconds ({took:.1f} s)", took < 2 * max(1, SCALE)) + checks.check("and the screen is cool", screen_is("cool", "a2")) + + kde.komorebic("focus-workspace", "0") + checks.check( + "back on workspace one, the monitor's wallpaper again", + kde.wait_for(lambda: shows(WARM_URL), timeout=10), + ) + + print("== B. a switch somebody else made") + kde.sh("kdotool set_desktop 2") + checks.check( + "the desktop was changed outside komorebi, and its wallpaper came with it", + kde.wait_for(lambda: shows(COOL_URL), timeout=10), + ) + kde.sh("kdotool set_desktop 1") + checks.check("and back", kde.wait_for(lambda: shows(WARM_URL), timeout=10)) + + print("== C. the borders follow the wallpaper") + kde.colored_window("left", "303030") + time.sleep(1.5) + checks.check( + "on the warm workspace the focused window's ring is warm", has_ring("left", "warm", "c1") + ) + kde.komorebic("focus-workspace", "1") + time.sleep(2) + kde.colored_window("right", "303030") + time.sleep(2) + checks.check("on the cool one it is cool", has_ring("right", "cool", "c2")) + kde.komorebic("focus-workspace", "0") + time.sleep(2.5) + checks.check("and warm again when the first is back", has_ring("left", "warm", "c3")) + + print("== D. a wallpaper changed by hand is put back") + kde.sh(f"plasma-apply-wallpaperimage {shlex.quote(OTHER)}") + checks.check( + "the user changed it", + kde.wait_for(lambda: shows(f"file://{OTHER}"), timeout=10), + ) + kde.komorebic("focus-workspace", "1") + time.sleep(1) + kde.komorebic("focus-workspace", "0") + checks.check( + "showing the workspace again set it back", + kde.wait_for(lambda: shows(WARM_URL), timeout=10), + ) + + print("== E. the palette is kept") + cache = kde.sh("ls ~/.cache/komorebi 2>/dev/null || true").split() + print(f" the cache: {cache}") + checks.check( + "a palette for each wallpaper is in the cache, named for the picture", + any(n.startswith("warm-") for n in cache) and any(n.startswith("cool-") for n in cache), + ) + daemon_log = machine.execute(f"cat {LOG}")[1] + checks.check( + "komorebi did not complain", + "failed to set wallpaper" not in daemon_log + and "gave up setting the wallpaper" not in daemon_log, + ) + stop_komorebi() + + print("== F. komorebi starts before the Plasma shell") + kde.sh(f"plasma-apply-wallpaperimage {shlex.quote(OTHER)}") + kde.systemctl("stop", SHELL_UNIT) + checks.check( + "the shell is gone", + kde.wait_for(lambda: not kde.has_name("org.kde.plasmashell"), timeout=20), + ) + start_komorebi() + time.sleep(3) + checks.check("no shell to answer: komorebi is still managing", answering()) + kde.systemctl("start", SHELL_UNIT) + checks.check( + "the shell is back", kde.wait_for(lambda: kde.has_name("org.kde.plasmashell"), timeout=60) + ) + checks.check( + "once the shell is up the wallpaper is set", + kde.wait_for(lambda: shows(WARM_URL), timeout=60), + ) + daemon_log = machine.execute(f"cat {LOG}")[1] + checks.check( + "and komorebi did not give up and say so", "gave up setting the wallpaper" not in daemon_log + ) + stop_komorebi() diff --git a/nix/tests/vm/lib/pyproject.toml b/nix/tests/vm/lib/pyproject.toml index ca8375f1..6da6cc45 100644 --- a/nix/tests/vm/lib/pyproject.toml +++ b/nix/tests/vm/lib/pyproject.toml @@ -28,5 +28,30 @@ line-length = 100 [tool.ruff.lint] select = ["E", "F", "I", "UP", "B", "SIM"] +[tool.ruff.lint.per-file-ignores] +# moved from the suite scripts, which were not linted to 100 columns: long lines of comments, +# strings and calls that were not wrapped +"komorebi_vm/platforms/kde/extras/kwin.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/kwin_events.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/kwin_contract.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/client_geometry.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/module.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/restart_survival.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/user_maximize.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/check.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/features.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/look.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/render_smoke.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/wallpaper.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/rdp.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/latency.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/run_kde.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/live_resize.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/focus_follows_mouse.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/lock_sleep.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/keys_engine.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/keys_static.py" = ["E501"] +"komorebi_vm/platforms/kde/extras/keys_corpus.py" = ["E501"] + [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/nix/tests/vm/suites/check/test.py b/nix/tests/vm/suites/check/test.py index 8386bd6a..b08f6abf 100644 --- a/nix/tests/vm/suites/check/test.py +++ b/nix/tests/vm/suites/check/test.py @@ -7,215 +7,16 @@ # the shortcut files the check compares with are in the directory `komorebic hotkeys compile` # writes to in a session. The configuration and the exit status are covered by # `komorebi/src/check.rs` and `komorebic/tests/check.rs`, against no desktop. -import base64 -import json -import re -import shlex -import struct -import zlib -from komorebi_vm import Checks, Kde +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import check as kde_check start_all() machine.wait_for_unit("multi-user.target") machine.wait_for_unit("user@1000.service") checks = Checks() -kde = Kde.headless(machine, "main", size=(1920, 1080), scale=SCALE) -CONFIG = "/tmp/check-config.json" -EMPTY_BUS = "/tmp/check-empty.bus" -FLAT = "/tmp/check-flat.png" - - -def flat_png() -> bytes: - """A picture of one color all over: a wallpaper no theme can be made from.""" - raw = b"".join(b"\x00" + bytes([200, 40, 40]) * 8 for _ in range(8)) - - def chunk(kind: bytes, data: bytes) -> bytes: - body = kind + data - return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF) - - header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0) - return ( - b"\x89PNG\r\n\x1a\n" - + chunk(b"IHDR", header) - + chunk(b"IDAT", zlib.compress(raw)) - + chunk(b"IEND", b"") - ) - - -kde.sh(f"echo {base64.b64encode(flat_png()).decode()} | base64 -d > {FLAT}") -# borders and animation, which want their effects; a wallpaper, which wants the Plasma shell and -# cannot make a theme; one workspace that is a layout and one that is only a name, which komorebi -# does not tile -kde.sh( - "printf %s " - + shlex.quote( - json.dumps( - { - "border": True, - "animation": {"enabled": True, "style": "Linear"}, - "monitors": [ - { - "wallpaper": {"path": FLAT}, - "workspaces": [{"name": "a", "layout": "BSP"}, {"name": "b"}], - } - ], - } - ) - ) - + f" > {CONFIG}" -) - - -def check(bus: str | None = None, data_home: str | None = None) -> tuple[int, str]: - """Runs `komorebic check` on the session's bus, or on the bus at `bus`, with `data_home` as the - user's data directory when KWin's environment does not name one.""" - prefix = f"DBUS_SESSION_BUS_ADDRESS=unix:path={bus} " if bus else "" - prefix += f"XDG_DATA_HOME={data_home} " if data_home else "" - status, out = kde.run(f"{prefix}komorebic check --komorebi-config {CONFIG}") - print(out) - return status, out - - -print("== 1. a desktop that is as it should be, with komorebi running") -kde.start_komorebi("--config", CONFIG) -checks.check( - "the daemon answers komorebic", - kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=30), -) -checks.check("its script is in KWin", kde.wait_for(kde.script_loaded, timeout=30)) -status, out = check() -checks.check("it passes: no errors", status == 0 and "\n0 error(s)" in out) -checks.check( - "it knows this is a KDE Plasma session on Wayland", - "this is a KDE Plasma session" in out and "it is a Wayland session" in out, -) -checks.check("it knows KWin 6", re.search(r"ok +KWin 6\.", out) is not None) -checks.check( - "it sees komorebi, and its script in KWin", - "komorebi is running, and its script is in KWin" in out, -) -checks.check( - "it says what starts komorebi at login", - re.search(r"ok +komorebi is started at login by ", out) is not None, -) -checks.check( - "the border effect is komorebi's build", - "the border effect is komorebi's build" in out, -) -checks.check( - "the animation effect is komorebi's build", - "the animation effect is komorebi's build" in out, -) -checks.check( - "the configuration is read, and the workspace that is only a name is found", - 'workspace 1 of monitor 0 ("b") has no `layout`' in out, -) -checks.check( - "wallpapers need the Plasma shell, which a headless KWin does not have", - "the Plasma shell is not on the bus" in out, -) -checks.check( - "a picture of one color cannot make a theme", - f"no theme can be made from {FLAT}" in out, -) - -print("== 2. the stock animation effect in the user's own directory hides komorebi's") -DATA = "/tmp/check-data" -STOCK = f"{DATA}/kwin/effects/kwin4_effect_geometry_change/contents/code" -kde.sh(f"mkdir -p {STOCK} && echo 'curve: QEasingCurve.OutExpo' > {STOCK}/main.js") -status, out = check(data_home=DATA) -checks.check( - "the effect is the stock one, and the style is ignored", - 'the animation effect is the stock one: `animation.style` "Linear" is ignored' in out, -) -checks.check("and it says which copy hides which", "shadows" in out) -kde.sh(f"rm -rf {DATA}") - -print("== 3. komorebi is running and its script is not in KWin") -kde.sh( - "busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting unloadScript s komorebi-bridge" -) -checks.check("KWin has let the script go", kde.wait_for(lambda: not kde.script_loaded())) -status, out = check() -checks.check( - "it is an error, and the exit status says so", - status == 1 - and re.search(r"error +komorebi is running but its script is not in KWin", out) is not None, -) - -print("== 4. komorebi is not running") -kde.stop_komorebi() -checks.check("the daemon is gone", kde.wait_for(lambda: not kde.komorebi_running(), timeout=30)) -status, out = check() -checks.check( - "a note, not an error", - status == 0 and re.search(r"note +komorebi is not running", out) is not None, -) - -print("== 5. there is no KWin on the bus") -pid = kde.sh(f"dbus-daemon --session --address=unix:path={EMPTY_BUS} --fork --print-pid").strip() -status, out = check(EMPTY_BUS) -kde.run(f"kill {pid}") -checks.check( - "KWin missing is an error, and the desktop is looked at no further", - status == 1 - and "KWin is not on the session bus" in out - and "komorebi is running" not in out - and "komorebi is not running" not in out, -) - -print("== 6. the key bindings") -KEYS_HOME = "/tmp/check-keys-home" -SHORTCUTS = "~/.local/share/kglobalaccel" -STALE = "[Desktop Entry]\nX-Komorebi-Generated=true\n" - - -def check_keys() -> tuple[int, str]: - """Runs `komorebic check` on the key bindings alone, in a config home of their own.""" - status, out = kde.run(f"KOMOREBI_CONFIG_HOME={KEYS_HOME} komorebic check --configuration-only") - print(out) - return status, out - - -kde.sh(f"mkdir -p {KEYS_HOME}") -status, out = check_keys() -checks.check( - "without a key binding file it is a note, not an error", - status == 0 and re.search(r"note +there is no skhdrc, whkdrc or sxhkdrc in ", out) is not None, -) - -kde.sh( - "printf %s " - + shlex.quote("alt - h : komorebic focus left\nalt - nosuchkey : komorebic focus up\n") - + f" > {KEYS_HOME}/skhdrc" -) -status, out = check_keys() -checks.check( - "the file is read, and the line it cannot read is a warning that does not fail the check", - status == 0 - and "skhdrc has 1 key binding" in out - and re.search(r"warning +1 line of it cannot be read and left out", out) is not None, -) - -# a shortcut file komorebi wrote that the file does not call for, in the directory of the session -kde.sh( - f"mkdir -p {SHORTCUTS} && printf %s {shlex.quote(STALE)} > {SHORTCUTS}/komorebi-stale.desktop" -) -status, out = check_keys() -checks.check( - "it says the shortcut files are not the ones `hotkeys compile` would write", - status == 0 - and "the shortcut files are not the ones `komorebic hotkeys compile` would write" in out, -) -kde.sh(f"KOMOREBI_CONFIG_HOME={KEYS_HOME} komorebic hotkeys compile") -status, out = check_keys() -checks.check( - "after `hotkeys compile` it does not: both use the directory of the session", - status == 0 and "are not the ones" not in out, -) - -kde.stop() +run_suite(checks, platform_only("kde", kde_check.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/client-geometry/test.py b/nix/tests/vm/suites/client-geometry/test.py index bb435781..1f53af0b 100644 --- a/nix/tests/vm/suites/client-geometry/test.py +++ b/nix/tests/vm/suites/client-geometry/test.py @@ -5,97 +5,16 @@ # foot sizes itself down to whole cells of its font; GTK 4 programs and Firefox never go below # their minimum size. Every client keeps the position komorebi asked for. The output is large # enough that some tiles are bigger and some smaller than the clients' minimums. -from komorebi_vm import Checks, Kde, Rect, daemon -W, H = 3840, 2160 -CELL = 24 - -EXACT = ["org.kde.konsole", "org.kde.kate", "org.kde.dolphin", "XTerm"] -WHOLE_CELLS = ["foot"] -NOT_BELOW_MINIMUM = ["org.gnome.TextEditor", "org.gnome.Calculator", "firefox"] - -CLIENTS = { - "foot": "foot -T foot-term sleep 3000", - "org.kde.konsole": "konsole --separate", - "org.kde.dolphin": "dolphin --new-window /tmp", - "org.kde.kate": "kate --new", - "org.gnome.TextEditor": "gnome-text-editor --new-window", - "org.gnome.Calculator": "gnome-calculator", - "XTerm": "xterm -T xterm-x11", - "firefox": "firefox --no-remote --profile /tmp/firefox-profile about:blank", -} +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import client_geometry as kde_client_geometry start_all() machine.wait_for_unit("multi-user.target") machine.wait_for_unit("user@1000.service") checks = Checks() -kde = Kde.headless(machine, "main", size=(W, H), xwayland=True, scale=SCALE) -kde.as_user("mkdir -p /tmp/firefox-profile") -kde.start_komorebi() -checks.check( - "the daemon loaded its script into KWin", - kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30), -) -for app, command in CLIENTS.items(): - kde.spawn(command, log=f"/tmp/{app}.log") - up = kde.wait_for(lambda app=app: kde.wid_by_class(app) != "", timeout=120) - if not checks.check(f"{app} has a window", up): - print(machine.execute(f"cat /tmp/{app}.log")[1]) - - -def shown() -> int: - return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show") - - -checks.check("the daemon tiles all eight", kde.wait_for(lambda: shown() >= 8, timeout=60)) - - -def show(r: Rect | None) -> str: - return "-" if r is None else f"{r.x},{r.y} {r.w}x{r.h}" - - -def snapshot() -> dict[str, Rect]: - return {app: kde.rect(kde.wid_by_class(app)) for app in CLIENTS} - - -# the clients answer in their own time; the frames are final once they stop changing -before: dict[str, Rect] = {} - - -def still() -> bool: - global before - now = snapshot() - unchanged = now == before - before = now - return unchanged - - -kde.wait_for(still, timeout=60, interval=3) -requests = list(daemon.requests(kde.komorebi_log()).values()) - -print(f" {'client':<22} {'asked':<22} {'has':<22}") -for app, have in snapshot().items(): - asked = [r for r in requests if (r.x, r.y) == (have.x, have.y)] - want = asked[0] if asked else None - print(f" {app:<22} {show(want):<22} {show(have):<22}") - if not checks.check(f"{app} is where komorebi put it", want is not None): - continue - assert want is not None - if app in EXACT: - checks.check(f"{app} takes the size it is asked for", (have.w, have.h) == (want.w, want.h)) - elif app in WHOLE_CELLS: - checks.check( - f"{app} sizes itself down to whole cells", - 0 <= want.w - have.w < CELL and 0 <= want.h - have.h < CELL, - ) - elif app in NOT_BELOW_MINIMUM: - checks.check( - f"{app} is never smaller than it is asked to be", - have.w >= want.w and have.h >= want.h, - ) - -kde.stop_komorebi() -kde.stop() +run_suite(checks, platform_only("kde", kde_client_geometry.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/features/test.py b/nix/tests/vm/suites/features/test.py index de250432..6d02f23d 100644 --- a/nix/tests/vm/suites/features/test.py +++ b/nix/tests/vm/suites/features/test.py @@ -19,357 +19,15 @@ # and `fullscreen.rs` check what the window manager does with a maximize and a fullscreen against # the fake; section A checks that KWin's own maximize does it, and section E that a window KWin has # taken fullscreen is left alone. -import time -from komorebi_vm import Checks, Kde, Rect, pixels - -UNIT = "komorebi.service" -# the daemon's log of the day, without colors, which every run of the unit adds to -LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" -ROUNDED_CORNERS = "kwin4_effect_shapecorners" - -BLUE = (0, 0, 255) -SINGLE = (66, 165, 245) -UNFOCUSED = (128, 128, 128) -LOCKED = (158, 8, 8) -STACK = (0, 165, 66) -MONOCLE = (255, 51, 153) -FLOATING = (245, 245, 165) -RED = (255, 0, 0) +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import features as kde_features start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) - - -def answering() -> bool: - return kde.run("komorebic monitor-information")[0] == 0 - - -def start_komorebi() -> None: - kde.systemctl("start", UNIT) - kde.wait_for(answering, timeout=60) - # The shell's panel takes room from the windows a while after the shell has made it, and the - # daemon learns that up to a second later. The windows are opened after that: before it they - # are tiled under the panel and then again, and the ring is read in between. - kde.wait_for_panel_room() - # the effects are written, loaded and told to read their settings as the daemon starts - time.sleep(2) - - -def stop_komorebi() -> None: - kde.systemctl("stop", UNIT) - kde.close_colored_windows() - - -def windows() -> None: - """Opens a red, a green and a blue window, in that order, and waits for them to be tiled.""" - for title, color in (("red", "ff0000"), ("green", "00ff00"), ("blue", "0000ff")): - kde.colored_window(title, color) - time.sleep(1) - kde.wait_for(lambda: kde.managed() == 3, timeout=30) - time.sleep(2) - - -def ring_wrong(title: str, color: tuple[int, int, int]) -> list[str]: - """What is wrong with the ring of `color` just outside the frame of the window with this title, - in a screenshot taken now: a line for each side that has none.""" - wid = kde.wid(title) - if wid == "": - return [f"there is no window titled {title}"] - return pixels.ring(kde.shot(f"ring-{title}"), kde.rect(wid), color) - - -def check_ring(description: str, title: str, color: tuple[int, int, int]) -> None: - """Waits for the window to have the ring, and says what is wrong when it does not.""" - ok = kde.wait_for(lambda: ring_wrong(title, color) == [], timeout=15) - detail = "" - if not ok: - detail = f"\n active: {active_title()!r}, komorebi's focus: {kde.focused_title()!r}" - detail += "".join(f"\n {w}" for w in ring_wrong(title, color)) - said = machine.execute(f"grep -h -i 'border effect\\|colour\\|effect' {LOG}")[1] - detail += "".join(f"\n daemon: {line}" for line in said.splitlines()[-8:]) - checks.check(description + detail, ok) - - -def active_title() -> str: - wid = kde.active() - return kde.title(wid) if wid else "" - - -def focus(title: str) -> None: - """Gives the window the focus, and waits until komorebi has it focused too.""" - kde.activate(kde.wid(title)) - kde.wait_for(lambda: kde.focused_title() == title, timeout=10) - - -def near(pixel: object, want: tuple[int, int, int], tolerance: int = 14) -> bool: - """True if every channel of the pixel is within `tolerance` of `want`.""" - assert isinstance(pixel, tuple) - return all(abs(got - wanted) <= tolerance for got, wanted in zip(pixel, want, strict=True)) - - -def open_window(title: str, background: str) -> None: - """Opens a terminal with a plain background, so that a screenshot says which window is on top.""" - kde.spawn( - f"foot -T {title} -o colors-dark.background={background} -o colors-dark.alpha=1.0" - " sleep 3000" - ) - kde.wait_for(lambda: kde.wid(title) != "", timeout=60) - - -print("== A. toggle-maximize") -checks.check("the session started komorebi", kde.wait_for(answering, timeout=120)) -for count, (title, background) in enumerate( - [("red", "ff0000"), ("green", "00ff00"), ("blue", "0000ff")], start=1 -): - open_window(title, background) - checks.check( - f"komorebi manages {title}", kde.wait_for(lambda count=count: kde.managed() == count) - ) -# komorebi tiles the windows, and the last one to open has the focus. The bridge asks again for the -# position of a window that is not where komorebi put it for a second after it did (PLATFORM.md, -# "How clients answer a frame"), which would put a window that is maximized in that second back -# where its tile was: the test waits that second out, as a person would. -kde.wait_for(lambda: kde.focused_title() == "blue", timeout=20) -time.sleep(3 * SCALE) - -area = kde.state()["monitors"]["elements"][0]["work_area_size"] -blue = kde.wid("blue") -tile = kde.rect(blue) -print(f" the work area is {area['right']}x{area['bottom']}, blue's tile is {tile}") -checks.check( - "blue is a tile, not the whole work area", - tile.w < area["right"] - 20 or tile.h < area["bottom"] - 20, -) - -kde.komorebic("toggle-maximize") - - -def fills_the_work_area() -> bool: - """KWin's maximize leaves the panel alone, which is at most 100 pixels of the screen.""" - r = kde.rect(blue) - return ( - r.x <= area["left"] + 2 - and r.y <= area["top"] + 2 - and r.w >= area["right"] - 30 - and r.h >= area["bottom"] - 100 - ) - - -filled = kde.wait_for(fills_the_work_area, timeout=20) -maximized = kde.rect(blue) -checks.check( - f"the focused window fills the work area (blue is {maximized}, the area is {area})", filled -) - -# a pixel that is not the middle of the window: komorebi puts the pointer there (mouse follows -# focus), and a screenshot has the white arrow on it -image = kde.shot("maximized") -print(f" the screenshot is {image.size[0]}x{image.size[1]}") -inside = image.getpixel( - ( - min(maximized.x + maximized.w // 4, image.width - 1), - min(maximized.y + maximized.h // 4, image.height - 1), - ) -) -checks.check(f"and is the one on top ({inside})", near(inside, BLUE)) -workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] -checks.check( - "komorebi's state has it as the maximized window, out of its containers", - workspace["maximized_window"] is not None and len(workspace["containers"]["elements"]) == 2, -) -checks.check("komorebi still has all three", kde.managed_all() == 3) - -kde.komorebic("toggle-maximize") -checks.check( - "toggled back, it is in its tile again", - kde.wait_for(lambda: kde.rect(blue) == tile, timeout=20), -) -workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] -checks.check( - "... and in a container of its own", - workspace["maximized_window"] is None and len(workspace["containers"]["elements"]) == 3, -) - - -# the session started the module's unit when it logged in: section A used its daemon, and the -# sections after it start their own runs -stop_komorebi() - -print("== B. transparency") -start_komorebi() -kde.komorebic("transparency-alpha", "100") -kde.komorebic("transparency", "enable") -windows() - - -def center_of(title: str) -> tuple[int, int]: - frame = kde.rect(kde.wid(title)) - return frame.x + frame.w // 2, frame.y + frame.h // 2 - - -def middle_of(title: str, color: tuple[int, int, int]) -> bool: - """Returns true if and only if the middle of the window is `color` in a screenshot now.""" - return pixels.near(pixels.pixel(kde.shot(f"middle-{title}"), *center_of(title)), color) - - -checks.check( - "the focused window is its own color", - kde.wait_for(lambda: middle_of("blue", BLUE), timeout=15), -) -checks.check( - "an unfocused window is not: it lets the desktop through", - kde.wait_for(lambda: not middle_of("red", RED), timeout=15), -) -kde.komorebic("transparency", "disable") -checks.check( - "with transparency off the unfocused window is opaque again", - kde.wait_for(lambda: middle_of("red", RED), timeout=15), -) -kde.komorebic("toggle-transparency") -checks.check( - "toggled on, see-through again", - kde.wait_for(lambda: not middle_of("red", RED), timeout=15), -) -stop_komorebi() - -print("== C. border colors") -start_komorebi() -windows() -checks.check( - "komorebi's build of the border effect is on the bus (it takes a color for each window)", - kde.run( - "busctl --user introspect org.kde.KWin /org/komorebi/BorderColours | grep -q SetColours" - )[0] - == 0, -) -check_ring("the focused window has the focus color", "blue", SINGLE) -check_ring("the others have the unfocused one", "green", UNFOCUSED) - -# a locked container that does not have the focus -focus("red") -kde.komorebic("toggle-lock") -focus("blue") -check_ring("a locked container that does not have the focus is marked", "red", LOCKED) -focus("red") -kde.komorebic("toggle-lock") -focus("blue") - -# a stack that has the focus: blue goes into the container on its left -kde.komorebic("stack", "left") -check_ring("a stack with the focus has the stack color", "blue", STACK) -kde.komorebic("unstack") - -# a monocled window -kde.komorebic("toggle-monocle") -check_ring("a monocled window has the monocle color", "blue", MONOCLE) -kde.komorebic("toggle-monocle") - -# a floating window that has the focus -kde.komorebic("toggle-float") -check_ring("a floating window with the focus has the floating color", "blue", FLOATING) -stop_komorebi() - -print("== D. animation curves") -# A 30 s animation, looked at a few seconds in: how far along the move is red, as seen on the -# screen (the frames are already where they are going; only the picture is on its way). An ease out -# is far along by then and a linear one has hardly started. Red is given the focus first so that -# nothing hides its left edge, and the answer is a percentage of the way, so it does not depend on -# how long the screenshot took. - - -def progress(style: str) -> int: - """How far along, in percent, red is a few seconds into a flip of the layout with `style`.""" - start_komorebi() - kde.komorebic("animation-duration", "30000") - kde.komorebic("animation-style", "--style", style) - kde.komorebic("animation", "enable") - kde.colored_window("red", "ff0000") - time.sleep(1) - kde.colored_window("blue", "0000ff") - time.sleep(20 * SCALE) - focus("red") - time.sleep(2) - here = kde.rect(kde.wid("red")) - row = here.y + here.h // 2 - from_x = pixels.leftmost(kde.shot(f"curve-before-{style}"), row, RED) - kde.komorebic("flip-layout", "horizontal") - kde.wait_for(lambda: kde.rect(kde.wid("red")) != here, timeout=10) - to = kde.rect(kde.wid("red")) - time.sleep(5 * SCALE) - now_x = pixels.leftmost(kde.shot(f"curve-{style}"), row, RED) - print(f" {style}: red's left edge on the screen went from {from_x} to {now_x}; its frame") - print(f" goes from {here.x} to {to.x}") - stop_komorebi() - if from_x is None or now_x is None or to.x == here.x: - return -1 - return (now_x - from_x) * 100 // (to.x - here.x) - - -linear = progress("linear") -expo = progress("ease-out-expo") -print(f" a few seconds into a 30 s move, red is this far along: {linear}% with Linear,") -print(f" {expo}% with EaseOutExpo") -checks.check("Linear is less than 60% of the way", 0 <= linear < 60) -checks.check("EaseOutExpo is at least 20 points further along than Linear", expo >= linear + 20) - -print("== E. fullscreen") -# This section needs the daemon running and a red, a green and a blue window open and tiled, and -# does not depend on which section came before it: when one has stopped the daemon or closed the -# windows, they are started and opened again. -if not answering(): - kde.systemctl("start", UNIT) - kde.wait_for(answering, timeout=60) -for title, background in [("red", "ff0000"), ("green", "00ff00"), ("blue", "0000ff")]: - if kde.wid(title) == "": - open_window(title, background) -kde.wait_for(lambda: kde.managed() == 3, timeout=30) -kde.wait_for(lambda: kde.focused_title() == "blue", timeout=20) -blue = kde.wid("blue") -monitor = kde.state()["monitors"]["elements"][0]["size"] -whole = Rect(monitor["left"], monitor["top"], monitor["right"], monitor["bottom"]) -# the bridge asks again for the position of a window that is not where komorebi put it for a second -# after it did, which is not the thing tested here -time.sleep(3 * SCALE) -kde.fullscreen(blue) -checks.check( - f"the window covers the monitor, panels included ({kde.rect(blue)}, the monitor is {whole})", - kde.wait_for(lambda: kde.rect(blue) == whole, timeout=20), -) -open_window("yellow", "ffff00") -checks.check("komorebi manages the fourth window", kde.wait_for(lambda: kde.managed() == 4)) -time.sleep(3 * SCALE) -checks.check( - f"a window opening meanwhile does not take it out of fullscreen ({kde.rect(blue)})", - kde.rect(blue) == whole, -) -kde.fullscreen(blue, on=False) - - -def in_a_tile(r: Rect) -> bool: - """Smaller than the monitor, and inside it.""" - return ( - r.w < whole.w - 100 - and r.x >= whole.x - and r.y >= whole.y - and r.x + r.w <= whole.x + whole.w - and r.y + r.h <= whole.y + whole.h - ) - - -checks.check( - "back from fullscreen it is in a tile", - kde.wait_for(lambda: in_a_tile(kde.rect(blue)), timeout=20), -) -back = kde.rect(blue) -print(f" blue is back at {back}") -checks.check( - "and it does not sit on any other window", - not any(back.overlaps(kde.rect(kde.wid(other))) for other in ("red", "green", "yellow")), -) -checks.check("komorebi still has all four", kde.managed_all() == 4) +run_suite(checks, platform_only("kde", kde_features.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/focus-follows-mouse/test.py b/nix/tests/vm/suites/focus-follows-mouse/test.py index 8145c1dd..f5807151 100644 --- a/nix/tests/vm/suites/focus-follows-mouse/test.py +++ b/nix/tests/vm/suites/focus-follows-mouse/test.py @@ -5,132 +5,15 @@ # then turning it off (the focus stays where it was), and on exit (the user's policy is back in # `kwinrc`). The pointer is a device made inside the guest (`Pointer`, the program # `komorebi-pointer`), moved to the middle of a window by pixel. -import time -from komorebi_vm import Checks, Kde, Pointer - -UNIT = "komorebi.service" -# the session node's display, which the pointer's two axes span -SCREEN = (1280, 800) +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import focus_follows_mouse as kde_focus_follows_mouse start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) - - -def answering() -> bool: - return kde.run("komorebic monitor-information")[0] == 0 - - -def running() -> bool: - return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 - - -def active_title() -> str: - wid = kde.active() - return kde.title(wid) if wid else "" - - -def focus_policy() -> str | None: - return kde.kwinrc("Windows", "FocusPolicy") - - -def kwin_has_read_it() -> None: - """Waits for KWin to have read the focus policy komorebi wrote. - - The key is in the file at once, and KWin reads it about 200 ms after it is asked to (it waits - for more changes): a pointer moved before that is moved under the old policy, and a pointer that - then rests over a window moves nothing. - """ - time.sleep(1) - - -def middle(title: str) -> tuple[int, int]: - frame = kde.rect(kde.wid(title)) - return frame.x + frame.w // 2, frame.y + frame.h // 2 - - -# the session started the module's unit when it logged in: this test starts its own run -kde.systemctl("stop", UNIT) -kde.close_colored_windows() -before = focus_policy() -before_delay = kde.kwinrc("Windows", "DelayFocusInterval") -print(f" the user's focus policy before: {before or '(not set: click to focus)'}") - -print("== focus follows mouse, turned on by command") -kde.systemctl("start", UNIT) -kde.wait_for(answering, timeout=60) -time.sleep(2) -kde.colored_window("win1", "222233") -time.sleep(1) -kde.colored_window("win2", "223322") -kde.wait_for(lambda: kde.managed() == 2, timeout=30) -time.sleep(2) -pointer = Pointer.start(machine, SCREEN, scale=SCALE) -kde.komorebic("focus-follows-mouse", "enable") -checks.check( - "KWin's focus policy is focus follows mouse, with no delay", - kde.wait_for( - lambda: focus_policy() == "1" and kde.kwinrc("Windows", "DelayFocusInterval") == "0", - timeout=10, - ), -) - -kwin_has_read_it() -first, second = middle("win1"), middle("win2") -print(f" win1's middle is at {first}, win2's at {second}") -pointer.move(*first) -checks.check( - "the pointer over win1 gives it the focus", - kde.wait_for(lambda: active_title() == "win1", timeout=10), -) -pointer.move(*second) -checks.check("over win2, win2", kde.wait_for(lambda: active_title() == "win2", timeout=10)) -pointer.move(*first) -checks.check("and back", kde.wait_for(lambda: active_title() == "win1", timeout=10)) -checks.check( - "komorebi followed the compositor", - kde.wait_for(lambda: kde.focused_title() == "win1", timeout=10), -) - -print("== turned off") -kde.komorebic("toggle-focus-follows-mouse") -checks.check( - "the policy is back to what it was", - kde.wait_for(lambda: focus_policy() == before, timeout=10), -) -kwin_has_read_it() -pointer.move(*second) -time.sleep(2) -checks.check("the pointer over win2 no longer moves the focus", active_title() == "win1") - -print("== turned on again, and put back when komorebi exits") -kde.komorebic("focus-follows-mouse", "enable") -checks.check( - "the policy is focus follows mouse again", - kde.wait_for(lambda: focus_policy() == "1", timeout=10), -) -kwin_has_read_it() -# the pointer is resting over win2: it has to go into a window to be followed -pointer.move(*first) -kde.wait_for(lambda: active_title() == "win1", timeout=10) -pointer.move(*second) -checks.check( - "on again: the pointer over win2 gives it the focus", - kde.wait_for(lambda: active_title() == "win2", timeout=10), -) -kde.komorebic("stop") -kde.wait_for(lambda: not running(), timeout=30) -kde.close_colored_windows() -checks.check( - "when komorebi exits the user's focus policy is back", - kde.wait_for(lambda: focus_policy() == before, timeout=10), -) -checks.check( - "and so is the delay it had", - kde.kwinrc("Windows", "DelayFocusInterval") == before_delay, -) +run_suite(checks, platform_only("kde", kde_focus_follows_mouse.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/keys-engine/test.py b/nix/tests/vm/suites/keys-engine/test.py index daaeedc5..06d60bbe 100644 --- a/nix/tests/vm/suites/keys-engine/test.py +++ b/nix/tests/vm/suites/keys-engine/test.py @@ -3,300 +3,15 @@ # engine's effects become; only KWin can say that a grabbed key reports its presses to the daemon, # that the keys of a killed daemon stay registered until the next start takes them over, and that # a stop gives them back. -import json -import shlex -from typing import Any -from komorebi_vm import Checks, Kde, Keys +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import keys_engine as kde_keys_engine start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) -keys = Keys(machine) - - -def ran(marker: str) -> bool: - return machine.execute(f"test -e /tmp/{marker}")[0] == 0 - - -def press(combo: str, marker: str) -> bool: - keys.send(combo) - return kde.wait_for(lambda: ran(marker), timeout=10) - - -def engine() -> dict[str, Any]: - """What the engine is doing: its `mode`, the keys it holds (`active`) and whether a chord - `chain` is being typed. It is empty when no engine answers. - - The engine answers once it has told kglobalaccel everything its last event needed, so what it - says it holds is what KWin has grabbed. A key pressed before that is not the engine's yet and - goes to the window, and how long the grab takes is how slow the machine is: the engine is - asked, and no fixed time is waited. - """ - status, out = kde.run("komorebic hotkeys state") - return (json.loads(out).get("engine") or {}) if status == 0 else {} - - -def in_mode(mode: str) -> bool: - """Waits for the engine to be in `mode`, with the keys of the mode grabbed.""" - return kde.wait_for(lambda: engine().get("mode") == mode, timeout=10) - - -def chain_is(on: bool, within: float = 10) -> bool: - """Waits for the engine to be in a chord chain (or, with `on` false, to be done with it, and to - hold the keys of the mode again), for up to `within` seconds.""" - return kde.wait_for(lambda: engine().get("chain") is on, timeout=within) - - -def write(skhdrc: str) -> None: - kde.sh( - f"mkdir -p ~/.config/komorebi && printf '%s' {shlex.quote(skhdrc)} > ~/.config/komorebi/skhdrc" - ) - - -def start(skhdrc: str, *args: str) -> None: - write(skhdrc) - # no --keybindings: the daemon finds the skhdrc in the config directory - kde.spawn_komorebi("--log-level", "debug", *args) - if not kde.wait_for(lambda: "keys in kglobalaccel" in kde.komorebi_log(), timeout=60): - raise AssertionError(f"the keys were not registered:\n{kde.komorebi_log()}") - - -def stop() -> None: - """Stops the daemon, and waits until it is gone: it takes its KWin script and its keys with - it when it exits, and a daemon started before that would find them taken from it.""" - kde.komorebic("stop") - if not kde.wait_for(lambda: machine.execute("pgrep -x komorebi")[0] != 0, timeout=10): - raise AssertionError("the daemon did not stop") - - -start( - "alt - h : touch /tmp/keys-engine-alt-h\n" - "alt - r : komorebic retile\n" - 'alt - q : echo "$HOME" > /tmp/keys-engine-alt-q\n' -) -actions = kde.shortcut_actions() -checks.check( - f"the daemon registered its three keys ({actions})", actions == ["Alt+H", "Alt+Q", "Alt+R"] -) -checks.check("Alt+H runs its command", press("alt-h", "keys-engine-alt-h")) -checks.check("Alt+Q runs its command through a shell", press("alt-q", "keys-engine-alt-q")) -home = machine.succeed("cat /tmp/keys-engine-alt-q").strip() -checks.check(f"the shell expanded $HOME ({home!r})", home == "/home/komorebi") -keys.send("alt-r") -checks.check( - "Alt+R runs komorebic, which sends its message to the daemon", - kde.wait_for(lambda: "processing command: Retile" in kde.komorebi_log(), timeout=10), -) - -# kglobalaccel keeps the keys of a daemon that was killed -kde.kill_spawned_komorebi() -checks.check("a killed daemon leaves its keys registered", kde.shortcut_actions() == actions) - -# the next start takes over the keys it binds, and unregisters the others -start("alt - j : touch /tmp/keys-engine-alt-j\nalt - h : touch /tmp/keys-engine-alt-h-again\n") -actions = kde.shortcut_actions() -checks.check(f"the next start leaves only its own keys ({actions})", actions == ["Alt+H", "Alt+J"]) -checks.check("Alt+J runs its command", press("alt-j", "keys-engine-alt-j")) -checks.check("Alt+H runs its new command", press("alt-h", "keys-engine-alt-h-again")) - -# a stop gives every key back -kde.komorebic("stop") -checks.check( - "komorebic stop stops the daemon", - kde.wait_for(lambda: machine.execute("pgrep -x komorebi")[0] != 0, timeout=10), -) -checks.check("a stop unregisters every key", kde.shortcut_actions() == []) -machine.succeed("rm /tmp/keys-engine-alt-j") -keys.send("alt-j") -checks.check( - "Alt+J runs nothing once the daemon stopped", - not kde.wait_for(lambda: ran("keys-engine-alt-j"), timeout=3), -) - -# modes: entering one grabs its keys, a bare H among them, and lets the others go to the window -kde.spawn("stdbuf -oL wev", log="/tmp/wev.log") -if not kde.wait_for(lambda: kde.wid_by_class("wev") != "", timeout=30): - raise AssertionError("wev did not open") - - -def activate(wid: str) -> None: - """Gives the window the focus, asking again until KWin has: it lists a window before it - can have the focus, and refuses to activate it until then.""" - if not kde.wait_for( - lambda: kde.run(f"kdotool windowactivate {shlex.quote(wid)}")[0] == 0 - and kde.active() == wid, - timeout=30, - ): - raise AssertionError(f"{wid} did not take the focus") - - -activate(kde.wid_by_class("wev")) - - -def typed(key: str) -> int: - """How many presses of `key` reached wev.""" - # wev prints a sym line after the press and after the release of a key - presses = f"grep -A1 'state: 1 (pressed)' /tmp/wev.log | grep -cE 'sym: {key} +\\('" - out = machine.execute(presses)[1].strip() - return int(out or "0") - - -def reaches_wev(key: str, presses: int) -> bool: - return kde.wait_for(lambda: typed(key) >= presses, timeout=5) - - -start( - ":: resize : touch /tmp/keys-modes-entered\n" - "alt - r ; resize\n" - "resize < h : touch /tmp/keys-modes-h\n" - "resize < escape ; default\n" -) -keys.send("h") -checks.check("in the default mode H reaches the focused window", reaches_wev("h", 1)) -checks.check("Alt+R enters the mode and runs its command", press("alt-r", "keys-modes-entered")) -checks.check( - "the daemon logs the mode it is in, and holds the keys of the mode", - kde.wait_for(lambda: "the mode is now resize" in kde.komorebi_log()) and in_mode("resize"), -) -checks.check("in the mode H runs its binding", press("h", "keys-modes-h")) -checks.check("and does not reach the window", typed("h") == 1) -keys.send("esc") -checks.check( - "Escape goes back to the default mode, and gives the keys of the mode back", - kde.wait_for(lambda: "the mode is now default" in kde.komorebi_log()) and in_mode("default"), -) -keys.send("h") -checks.check("back in the default mode H reaches the window again", reaches_wev("h", 2)) -stop() - -# chord chains: the prefix grabs the keys that can come next, until a key, Escape or the timeout -sxhkdrc = "/home/komorebi/.config/komorebi/sxhkdrc" -chain = "alt + w ; {h,l}\n touch /tmp/keys-chords-{h,l}\n" -kde.sh(f"printf '%s' {shlex.quote(chain)} > {sxhkdrc}") -# The timeout is long, and is scaled like every wait, so that the keys of a chain are sent well -# inside it however slowly the machine grabs them, and that Escape can be told from the timeout. -CHORD_TIMEOUT = 3 -kde.spawn_komorebi( - "--log-level", - "debug", - "--keybindings", - sxhkdrc, - "--chord-timeout", - str(int(CHORD_TIMEOUT * 1000 * SCALE)), -) -if not kde.wait_for(lambda: "keys in kglobalaccel" in kde.komorebi_log(), timeout=60): - raise AssertionError(f"the keys were not registered:\n{kde.komorebi_log()}") - - -def chain_begins() -> None: - """Presses Alt+W and waits until the engine has grabbed the keys that can come next. - - A key pressed before that goes to the window, not to the chain. - """ - keys.send("alt-w") - if not chain_is(True): - raise AssertionError(f"Alt+W did not begin the chain ({engine()}):\n{kde.komorebi_log()}") - - -def chain_ends() -> None: - """Waits until the chain is over and the engine holds Alt+W again, which a key pressed - before that would not find.""" - if not chain_is(False): - raise AssertionError(f"the chain did not end ({engine()}):\n{kde.komorebi_log()}") - - -h_before = typed("h") -chain_begins() -checks.check("Alt+W, H runs the binding of the chain", press("h", "keys-chords-h")) -checks.check("the H of the chain does not reach the window", typed("h") == h_before) -chain_ends() -chain_begins() -keys.send("esc") -checks.check( - "Escape ends the chain, which the timeout has not yet done", - chain_is(False, within=CHORD_TIMEOUT / 2), -) -keys.send("h") -checks.check("after Alt+W, Escape, H reaches the window", reaches_wev("h", h_before + 1)) -chain_begins() -checks.check("the chain ends at its timeout", chain_is(False, within=CHORD_TIMEOUT + 1)) -keys.send("l") -checks.check("after Alt+W and the timeout, L reaches the window", reaches_wev("l", 1)) -checks.check("and runs nothing", not ran("keys-chords-l")) -stop() - -# per-application bindings: a key is grabbed only while the focused application has an action -start( - 'alt - g [\n "terminal" : touch /tmp/keys-scopes-terminal\n]\n' - 'alt - n [\n "wev" ~\n * : touch /tmp/keys-scopes-other\n]\n', - "--app-alias", - "terminal=foot", -) -kde.spawn("foot") -if not kde.wait_for(lambda: kde.wid_by_class("foot") != "", timeout=30): - raise AssertionError("foot did not open") -wev, foot = kde.wid_by_class("wev"), kde.wid_by_class("foot") - - -def sees_focus(wid: str, app_id: str) -> bool: - """Activates the window and waits for the engine to log that its application has the focus.""" - activate(wid) - - def seen() -> bool: - lines = [x for x in kde.komorebi_log().splitlines() if "the focus is now" in x] - return bool(lines) and f"({app_id}, " in lines[-1] - - return kde.wait_for(seen, timeout=10) - - -def focus(wid: str, app_id: str) -> None: - """Activates the window, and returns once the engine has grabbed the keys that its - application has an action for, and given the others back.""" - if not sees_focus(wid, app_id): - raise AssertionError(f"the engine did not see {app_id} take the focus") - # the engine logs the focus before it grabs and gives back the keys of the application, and - # answers once it has: a key pressed before that would find the keys of the other window - if not engine(): - raise AssertionError("the engine does not answer") - - -focus(wev, "wev") -g_before, n_before = typed("g"), typed("n") -keys.send("alt-g") -checks.check("in wev, Alt+G (for the terminal only) reaches wev", reaches_wev("g", g_before + 1)) -keys.send("alt-n") -checks.check("in wev, Alt+N (which wev ignores) reaches wev", reaches_wev("n", n_before + 1)) -checks.check("and runs nothing", not ran("keys-scopes-other")) -focus(foot, "foot") -checks.check( - "in foot, Alt+G runs the terminal's binding, by the alias", - press("alt-g", "keys-scopes-terminal"), -) -checks.check( - "in foot, Alt+N runs the binding for every other application", - press("alt-n", "keys-scopes-other"), -) -focus(wev, "wev") -keys.send("alt-g") -checks.check("back in wev, Alt+G reaches wev again", reaches_wev("g", g_before + 2)) - -# An engine that starts while the focused application has nothing to grab starts all the same: -# the key bindings are read again with wev focused, and every binding is for the terminal. -write('alt - j [\n "terminal" : touch /tmp/keys-scopes-reload\n]\n') -reads = kde.komorebi_log().count("bindings for the engine") -kde.komorebic("hotkeys", "reload") -kde.wait_for(lambda: kde.komorebi_log().count("bindings for the engine") > reads, timeout=10) -checks.check( - "an engine that starts with nothing to grab goes on to see foot take the focus", - sees_focus(foot, "foot") and bool(engine()), -) -checks.check( - "and in foot, Alt+J runs the terminal's binding", - press("alt-j", "keys-scopes-reload"), -) -stop() +run_suite(checks, platform_only("kde", kde_keys_engine.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/keys-static/test.py b/nix/tests/vm/suites/keys-static/test.py index f33e666e..e514033b 100644 --- a/nix/tests/vm/suites/keys-static/test.py +++ b/nix/tests/vm/suites/keys-static/test.py @@ -3,47 +3,15 @@ # process. The Rust tests check the files; only a KWin can say that it reads them # and runs their commands on a key: the files in the system profile when the # session starts, and a file written later once `--reload` has handed it over. -from komorebi_vm import Checks, Kde, Keys + +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import keys_static as kde_keys_static start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) -keys = Keys(machine) - - -def ran(marker: str) -> bool: - return machine.execute(f"test -e /tmp/{marker}")[0] == 0 - - -def press(combo: str, marker: str) -> bool: - keys.send(combo) - return kde.wait_for(lambda: ran(marker), timeout=10) - - -print(kde.sh("ls /run/current-system/sw/share/kglobalaccel")) -checks.check("Alt+J runs its command", press("alt-j", "keys-static-alt-j")) -checks.check( - "Alt+Shift+K runs a command that needs a shell", - press("alt-shift-k", "keys-static-alt-shift-k"), -) -checks.check("Alt+P runs a command with a %", press("alt-p", "keys-static-alt-p")) -date = machine.succeed("cat /tmp/keys-static-alt-p").strip() -checks.check(f"the % reached the command as one % ({date!r})", date.isdigit()) - -# a binding written in the middle of the session, into the user's directory -kde.sh("mkdir -p ~/.config/komorebi") -kde.sh("echo 'alt - u : touch /tmp/keys-static-alt-u' > ~/.config/komorebi/skhdrc") -print(kde.sh("komorebic export-kde-shortcuts --reload")) -written = "/home/komorebi/.local/share/kglobalaccel/komorebi-touch-tmp-keys-static-alt-u.desktop" -checks.check( - "the file is in the user's kglobalaccel directory", - machine.execute(f"test -e {written}")[0] == 0, -) -checks.check( - "Alt+U runs its command once --reload has handed it over", - press("alt-u", "keys-static-alt-u"), -) +run_suite(checks, platform_only("kde", kde_keys_static.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/kwin-contract/test.py b/nix/tests/vm/suites/kwin-contract/test.py index 41dd626e..957df9f8 100644 --- a/nix/tests/vm/suites/kwin-contract/test.py +++ b/nix/tests/vm/suites/kwin-contract/test.py @@ -15,158 +15,16 @@ # bridge listens to. # # docs/dev/PLATFORM.md records these as the facts of KWin that komorebi depends on. -from itertools import count -from komorebi_vm import Checks, Kde +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import kwin_contract as kde_kwin_contract start_all() machine.wait_for_unit("multi-user.target") machine.wait_for_unit("user@1000.service") checks = Checks() -# per-output desktops are read when KWin starts, as komorebi's users have them after their first run -machine.succeed( - "runuser -u komorebi -- sh -c 'mkdir -p ~/.config" - ' && printf "[Windows]\\nPerOutputVirtualDesktops=true\\n" > ~/.config/kwinrc\'' -) -kde = Kde.headless(machine, "main", size=(1920, 1080), outputs=2, scale=SCALE) -# what every script is given: the desktop each output shows, and a window by its title -HELPERS = """ -function cur() { - return workspace.screens.map(function (o) { - return workspace.currentDesktopForScreen(o).name; - }).join("/"); -} -function win(title) { - return workspace.windowList().filter(function (w) { return w.caption === title; })[0]; -} -function names(ds) { - return ds.map(function (d) { return d.name; }).join(","); -} -""" - - -def script(name: str, body: str, keep: bool = False) -> list[str]: - return kde.kwin_script(name, HELPERS + body + '\nreport("done");\n', keep=keep) - - -def shows() -> str: - """What each output shows, as `first/second`.""" - lines = script(f"shows-{next(counter)}", "report(cur());") - return lines[0] if lines else "" - - -counter = count(1) - -print("== 1. two outputs, one desktop, and per-output desktops on") -outputs = script( - "outputs", 'report(workspace.screens.map(function (o) { return o.name; }).join(" "));' -) -print(f" outputs: {outputs}") -names_of = outputs[0].split() if outputs else [] -checks.check("KWin has two outputs", len(names_of) == 2) -checks.check("and one desktop", kde.desktops() == 1) -checks.check( - "kwinrc has per-output desktops on", - kde.kwinrc("Windows", "PerOutputVirtualDesktops") == "true", -) - -print("== 2. a desktop created over D-Bus is a desktop of every output") -kde.sh( - "busctl --user call org.kde.KWin /VirtualDesktopManager" - " org.kde.KWin.VirtualDesktopManager createDesktop us 1 two > /dev/null" -) -checks.check("KWin has two desktops", kde.wait_for(lambda: kde.desktops() == 2)) -desktops = script("desktops", "report(names(workspace.desktops));") -checks.check(f"the script sees them in order: {desktops}", desktops[-1:] == ["Desktop 1,two"]) -checks.check("both outputs show the first", shows() == "Desktop 1/Desktop 1") - -print("== 3. one output shows another desktop, and the other keeps its own") -script( - "listen", - 'workspace.currentDesktopChanged.connect(function () { report("changed", cur()); });', - keep=True, -) -script( - "switch", "workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);" -) -checks.check( - "the first output shows the second desktop, and the second output the first", - kde.wait_for(lambda: shows() == "two/Desktop 1"), -) -checks.check( - "KWin said so with currentDesktopChanged", - kde.wait_for(lambda: "changed two/Desktop 1" in kde.kwin_reports("listen")), -) -script("back", "workspace.setCurrentDesktopForScreen(workspace.desktops[0], workspace.screens[0]);") -checks.check("and back", kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1")) - -print("== 4. KWin focuses a window of the desktop it switched an output to") -for title in ["w1", "w2"]: - kde.spawn(f"foot -T {title} sleep 3000") - kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30) -script( - "place", - """ -var d = workspace.desktops; -var w1 = win("w1"), w2 = win("w2"); -w1.desktops = [d[0]]; -w1.frameGeometry = { x: 100, y: 100, width: 600, height: 400 }; -w2.desktops = [d[1]]; -w2.frameGeometry = { x: 800, y: 100, width: 600, height: 400 }; -workspace.activeWindow = w1; -""", -) -checks.check( - "w1 has the focus, on the first desktop", - kde.wait_for(lambda: kde.title(kde.active()) == "w1"), -) -script( - "to-two", "workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);" -) -checks.check( - "after the first output shows the second desktop, w2, which is on it, has the focus", - kde.wait_for(lambda: kde.active() != "" and kde.title(kde.active()) == "w2"), -) - -print("== 5. activating a window on another desktop of its output switches that output to it") -script("raise", 'workspace.activeWindow = win("w1");') -checks.check( - "the first output shows the first desktop again", - kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1"), -) -checks.check("and w1 has the focus", kde.wait_for(lambda: kde.title(kde.active()) == "w1")) - -print("== 6. a window a script moves onto the other output keeps its desktops") -script("cross", 'win("w1").frameGeometry = { x: 2300, y: 100, width: 600, height: 400 };') - - -def where_w1() -> str: - lines = script( - f"where-{next(counter)}", - 'var w = win("w1"); report(w.output.name + " " + names(w.desktops));', - ) - return lines[0] if lines else "" - - -second = names_of[1] if len(names_of) == 2 else "?" -checks.check( - f"w1 is on {second} now, and still on the first desktop only", - kde.wait_for(lambda: where_w1() == f"{second} Desktop 1"), -) - -print("== 7. a window put on another desktop from outside says so") -script( - "watch", - 'var w = win("w1"); w.desktopsChanged.connect(function () { report("moved", names(w.desktops)); });', - keep=True, -) -kde.sh(f"kdotool set_desktop_for_window {kde.wid('w1')} 2") -checks.check( - "w1's desktopsChanged was raised, with the second desktop", - kde.wait_for(lambda: "moved two" in kde.kwin_reports("watch")), -) - -kde.stop() +run_suite(checks, platform_only("kde", kde_kwin_contract.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/kwin-events/test.py b/nix/tests/vm/suites/kwin-events/test.py index 40c4e3c7..21220900 100644 --- a/nix/tests/vm/suites/kwin-events/test.py +++ b/nix/tests/vm/suites/kwin-events/test.py @@ -3,126 +3,16 @@ # `komorebi/src/kwin/state.rs` and `komorebi/tests/wm_events.rs` feed it by hand, in the order KWin # raised them (KWin activates a new window before it announces it), that a window giving itself # another title is reported, and that it takes its script out of KWin when it stops. -import shlex -from komorebi_vm import Checks, Kde, daemon -from komorebi_vm.daemon import Event +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import kwin_events as kde_kwin_events start_all() machine.wait_for_unit("multi-user.target") machine.wait_for_unit("user@1000.service") checks = Checks() -kde = Kde.headless(machine, "main", size=(1280, 720), scale=SCALE) - -def daemon_log() -> str: - return kde.komorebi_log() - - -def handled(event: Event) -> bool: - return event in daemon.events(daemon_log()) - - -kde.spawn("foot -T before sleep 3000") -checks.check( - "a window is open before komorebi starts", - kde.wait_for(lambda: kde.wid("before") != "", timeout=30), -) -before = kde.wid("before") - -kde.start_komorebi() -checks.check( - "the daemon loaded its script into KWin", - kde.wait_for(lambda: "loaded the KWin bridge script" in daemon_log(), timeout=30), -) -checks.check("KWin runs the script", kde.script_loaded()) -checks.check( - "the script reported the window that was already open", - kde.wait_for(lambda: "1 valid windows identified" in daemon_log(), timeout=10), -) -checks.check("the daemon is still running", kde.komorebi_running()) - -print("== a window opens") -kde.spawn("foot -T alpha sleep 3000") -checks.check("KWin has it", kde.wait_for(lambda: kde.wid("alpha") != "", timeout=30)) -alpha = kde.wid("alpha") -checks.check( - "KWin's focus on it reached the daemon, by title", - kde.wait_for(lambda: "alpha" in daemon.window_ids(daemon_log()), timeout=10), -) -ids = daemon.window_ids(daemon_log()) -n = ids.get("alpha", -1) -shown = Event("Show", n, "WindowAdded") -focused = Event("FocusChange", n, "WindowActivated") -checks.check("the daemon handled a Show for it", kde.wait_for(lambda: handled(shown), timeout=10)) -checks.check("... and a FocusChange", kde.wait_for(lambda: handled(focused), timeout=10)) -seen = daemon.events(daemon_log()) -checks.check( - "the Show came first, although KWin activates a window before it announces it", - shown in seen and focused in seen and seen.index(shown) < seen.index(focused), -) - -print("== the focus moves") -kde.activate(before) -checks.check( - "the window that was open before is focused, and the daemon knows it", - kde.wait_for(lambda: "before" in daemon.window_ids(daemon_log()), timeout=10), -) -m = daemon.window_ids(daemon_log()).get("before", -1) -checks.check( - "a FocusChange for it", - kde.wait_for(lambda: handled(Event("FocusChange", m, "WindowActivated")), timeout=10), -) - -print("== minimize, restore, close") -kde.minimize(alpha) -checks.check( - "minimizing is a Minimize", - kde.wait_for(lambda: handled(Event("Minimize", n, "WindowMinimized")), timeout=10), -) -kde.activate(alpha) -checks.check( - "activating a minimized window brings it back: a Restore", - kde.wait_for(lambda: handled(Event("Restore", n, "WindowRestored")), timeout=10), -) -kde.close(alpha) -checks.check( - "closing is a Destroy", - kde.wait_for(lambda: handled(Event("Destroy", n, "WindowRemoved")), timeout=10), -) -mine = [e.kind for e in daemon.events(daemon_log()) if e.window == n] -print(f" the events of alpha, in order: {mine}") -in_order = [kind for kind in mine if kind in ("Show", "Minimize", "Restore", "Destroy")] -checks.check( - "alpha's events came in the order they happened", - in_order == ["Show", "Minimize", "Restore", "Destroy"], -) - -print("== a window gives itself another title") -rename = 'sleep 4; printf "\\033]0;beta-renamed\\007"; sleep 3000' -kde.spawn(f"foot -T beta sh -c {shlex.quote(rename)}") -checks.check( - "KWin's focus on it reached the daemon, by title", - kde.wait_for(lambda: "beta" in daemon.window_ids(daemon_log()), timeout=30), -) -b = daemon.window_ids(daemon_log()).get("beta", -1) -checks.check( - "KWin has it under its new title", - kde.wait_for(lambda: kde.wid("beta-renamed") != "", timeout=20), -) -checks.check( - "the title change is a TitleUpdate", - kde.wait_for(lambda: handled(Event("TitleUpdate", b, "CaptionChanged")), timeout=10), -) - -print("== stop") -kde.stop_komorebi() -checks.check("the daemon exited", not kde.komorebi_running()) -checks.check( - "the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded(), timeout=10) -) -checks.check("the windows are still there", kde.wid("before") != "") - -kde.stop() +run_suite(checks, platform_only("kde", kde_kwin_events.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/kwin/test.py b/nix/tests/vm/suites/kwin/test.py index a861e743..8cc56dd9 100644 --- a/nix/tests/vm/suites/kwin/test.py +++ b/nix/tests/vm/suites/kwin/test.py @@ -1,6 +1,9 @@ # What the harness itself promises: a headless KWin comes up with the outputs asked for, a client # gets a window on it, and the library sees both. -from komorebi_vm import Checks, Kde + +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import kwin as kde_kwin start_all() machine.wait_for_unit("multi-user.target") @@ -8,24 +11,5 @@ machine.wait_for_unit("user@1000.service") checks = Checks() -kde = Kde.headless(machine, "main", size=(1280, 720), outputs=2, scale=SCALE) -checks.check("KWin owns its name on the private bus", kde.has_name("org.kde.KWin")) -checks.check("KWin has the two outputs that were asked for", lambda: kde.outputs() == 2) - -kde.spawn("foot -T alpha sleep 3000") -checks.check("a window appears", kde.wait_for(lambda: kde.wid("alpha") != "", timeout=30)) -wid = kde.wid("alpha") -checks.check("the library reads its title back", lambda: kde.title(wid) == "alpha") -rect = kde.rect(wid) -print(f"alpha is at {rect}") -checks.check("it has a size", rect.w > 0 and rect.h > 0) - -other = Kde.headless(machine, "other", size=(800, 600), scale=SCALE) -checks.check("a second session is its own KWin", lambda: other.outputs() == 1) -checks.check("it does not see the first session's window", other.wid("alpha") == "") -other.stop() - -kde.stop() -checks.check("stopping the session releases its name", not kde.has_name("org.kde.KWin")) - +run_suite(checks, platform_only("kde", kde_kwin.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/latency/test.py b/nix/tests/vm/suites/latency/test.py index 91b46830..46fd0002 100644 --- a/nix/tests/vm/suites/latency/test.py +++ b/nix/tests/vm/suites/latency/test.py @@ -3,81 +3,16 @@ # frame KWin reports for one of the windows it moved, the client's answer included. Every number # here comes from KWin and real clients; the Rust tests cannot measure it. The output is large, so # that ten windows in komorebi's default layout all have room. -from komorebi_vm import Checks, Kde, daemon, latency -W, H = 3840, 2160 -WINDOWS = 10 -ROUNDS = 10 -BUS_LOG = "/tmp/komorebi-bus.log" +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import latency as kde_latency start_all() machine.wait_for_unit("multi-user.target") machine.wait_for_unit("user@1000.service") checks = Checks() -kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) -kde.start_komorebi() -checks.check( - "the daemon loaded its script into KWin", - kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30), -) -kde.monitor_bridge(BUS_LOG) -titles = [f"w{n}" for n in range(1, WINDOWS + 1)] -for title in titles: - kde.spawn(f"foot -T {title} sleep 3000") - kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30) - - -def shown() -> int: - return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show") - - -checks.check(f"the daemon tiles all {WINDOWS}", kde.wait_for(lambda: shown() >= WINDOWS)) - - -def measured() -> list[latency.Round]: - return latency.rounds(machine.succeed(f"cat {BUS_LOG}")) - - -def settled_after(count: int) -> bool: - """A round after the first `count` is over: its windows all reported, and then 0.3 s passed.""" - done = measured() - if len(done) <= count or done[-1].seconds is None: - return False - now = float(machine.succeed("date +%s.%N")) - return now - (done[-1].sent + done[-1].seconds) > 0.3 - - -kde.wait_for(lambda: settled_after(0), timeout=10) -start = len(measured()) - -# each round takes one window out of the layout and puts it back: two retiles -for title in titles[:ROUNDS]: - wid = kde.wid(title) - count = len(measured()) - kde.minimize(wid) - kde.wait_for(lambda count=count: settled_after(count), timeout=10) - count = len(measured()) - kde.activate(wid) - kde.wait_for(lambda count=count: settled_after(count), timeout=10) - -# the rounds before `start` tiled the windows as they opened -rounds = measured()[start:] -settled = [r.seconds * 1000 for r in rounds if r.seconds is not None] -moved = sum(r.windows for r in rounds) / max(1, len(rounds)) -print(f" {len(rounds)} retiles, {moved:.1f} windows moved by each on average, scale {SCALE}") -if settled: - p50, p95 = latency.percentile(settled, 0.5), latency.percentile(settled, 0.95) - print(f" from the batch to the last frame: p50 {p50:.1f} ms, p95 {p95:.1f} ms,") - print(f" max {max(settled):.1f} ms, min {min(settled):.1f} ms") -checks.check(f"{2 * ROUNDS} retiles were measured", len(rounds) == 2 * ROUNDS) -checks.check("every window of every retile reported its frame", len(settled) == len(rounds)) -checks.check( - "a retile reaches the windows within 100 ms (times the machine's scale), at p95", - bool(settled) and latency.percentile(settled, 0.95) <= 100 * SCALE, -) - -kde.stop_komorebi() -kde.stop() +run_suite(checks, platform_only("kde", kde_latency.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/live-resize/test.py b/nix/tests/vm/suites/live-resize/test.py index eabac134..16f095c7 100644 --- a/nix/tests/vm/suites/live-resize/test.py +++ b/nix/tests/vm/suites/live-resize/test.py @@ -11,209 +11,15 @@ # * the windows that are not next to the dragged edge have not moved # * when the button is let go nothing jumps: the neighbors stay where they followed to # * the windows still tile -import re -import time -from komorebi_vm import Checks, Kde, Pointer, daemon - -# the module's unit, which the session starts when it logs in: the daemon the suite drags against -UNIT = "komorebi.service" - -# what an edge of a terminal's frame may be off by: up to a cell of its font -CELL = 24 -# how far from its frame a window's resize border is pressed: in the gap between two tiles -OFFSET = 4 -WINDOWS = 3 - -OPPOSITE = {"L": "R", "R": "L", "T": "B", "B": "T"} -HELD = {"left": "L", "right": "R", "top": "T", "bottom": "B"} +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import live_resize as kde_live_resize start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) - -# KWin snaps an edge the user drags to an edge of another window within its snap zone, 10 pixels -# by default, and the neighbors that follow a drag are about that far from the edge: it would end -# up a few pixels past the pointer. The test measures komorebi, so KWin snaps nothing. -for zone in ("BorderSnapZone", "WindowSnapZone", "CenterSnapZone"): - kde.sh(f"kwriteconfig6 --file kwinrc --group Windows --key {zone} 0") -kde.sh("busctl --user call org.kde.KWin /KWin org.kde.KWin reconfigure") - -# the session started the module's unit when it logged in -checks.check( - "komorebi answers", kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=120) -) - -# The shell makes its panel, and KWin takes room for it a while later, which the daemon learns of -# up to a second after that and tiles the windows again. A case that begins then ends with every -# tile moved by the panel, so the windows are opened after it (`Kde.wait_for_panel_room`). -kde.wait_for_panel_room() - -size = kde.state()["monitors"]["elements"][0]["size"] -W, H = size["right"], size["bottom"] -pointer = Pointer.start(machine, (W, H), scale=SCALE) - -for n in range(1, WINDOWS + 1): - kde.spawn(f"foot -T win{n} sleep 3000") - kde.wait_for(lambda n=n: kde.managed() == n, timeout=30) -checks.check(f"the {WINDOWS} windows are tiled", kde.managed() == WINDOWS) - -Box = tuple[int, int, int, int] - - -def frames() -> dict[str, Box]: - out = {} - for n in range(1, WINDOWS + 1): - r = kde.rect(kde.wid(f"win{n}")) - out[f"win{n}"] = (r.x, r.y, r.w, r.h) - return out - - -def edges(r: Box) -> dict[str, int]: - x, y, w, h = r - return {"L": x, "T": y, "R": x + w, "B": y + h} - - -def settled() -> dict[str, Box]: - """The frames once they have stopped changing""" - last = frames() - deadline = time.monotonic() + 10 * SCALE - while time.monotonic() < deadline: - time.sleep(0.5) - now = frames() - if now == last: - return now - last = now - return last - - -def resize_ends() -> int: - """How many drags of an edge the daemon has handled the end of, by the unit's log""" - log = kde.run(f"journalctl --user -u {UNIT} --no-pager -o cat")[1] - return sum(1 for e in daemon.events(log) if e.kind == "ResizeEnd") - - -def press_point(grab: str, r: Box) -> tuple[int, int]: - x, y, w, h = r - cx, cy = x + w // 2, y + h // 2 - return { - "left": (x - OFFSET, cy), - "right": (x + w + OFFSET, cy), - "top": (cx, y - OFFSET), - "bottom": (cx, y + h + OFFSET), - }[grab] - - -def neighbors(edge: str, name: str, before: dict[str, Box]) -> list[str]: - """The windows within a gap's reach on that side of this one, overlapping it""" - mx, my, mw, mh = before[name] - found = [] - for other, (ox, oy, ow, oh) in before.items(): - if other == name: - continue - v = oy < my + mh and my < oy + oh - h = ox < mx + mw and mx < ox + ow - if ( - (edge == "L" and v and 0 <= mx - (ox + ow) <= 80) - or (edge == "R" and v and 0 <= ox - (mx + mw) <= 80) - or (edge == "T" and h and 0 <= my - (oy + oh) <= 80) - or (edge == "B" and h and 0 <= oy - (my + mh) <= 80) - ): - found.append(other) - return found - - -def where() -> tuple[int, int]: - found = re.search(r"x:(-?\d+) y:(-?\d+)", kde.sh("kdotool getmouselocation")) - assert found, "kdotool says nowhere" - return int(found.group(1)), int(found.group(2)) - - -def run_case(case: str) -> list[str]: - name, grab, d = case.split(":") - dx, dy = (int(v) for v in d.split(",")) - held = HELD[grab] - want = dx if held in "LR" else dy - - kde.komorebic("retile") - before = settled() - near = neighbors(held, name, before) - if not near: - return [f"{name} has nothing next to its {grab} edge"] - ends = resize_ends() - - px, py = press_point(grab, before[name]) - pointer.move(px, py) - pointer.down() - - problems = [] - held_at: dict[str, dict[str, Box]] = {} - for label, fraction in (("part way", 0.5), ("all the way", 1.0)): - pointer.glide(px + round(dx * fraction), py + round(dy * fraction), steps=12, ms=30) - expect = want * fraction - - def moved(now: dict[str, Box], n: str) -> int: - return edges(now[n])[OPPOSITE[held]] - edges(before[n])[OPPOSITE[held]] - - # the pointer is held there; the neighbors follow - kde.wait_for( - lambda expect=expect: all(abs(moved(frames(), n) - expect) <= CELL for n in near), - timeout=5, - ) - now = frames() - held_at[label] = now - print(f"{case} {label}: the pointer is at {where()}, the frames {now}") - - for n in near: - if abs(moved(now, n) - expect) > CELL: - problems.append( - f"{label}: {n}'s {OPPOSITE[held]} edge is {moved(now, n)} from where it was," - f" the pointer {expect:.0f}" - ) - for other, r in before.items(): - if other == name or other in near: - continue - if any(abs(edges(now[other])[e] - edges(r)[e]) > CELL for e in "LTRB"): - # a tile that shares the dragged edge's line may move with it; nothing else may - shared = any(abs(edges(r)[e] - edges(before[name])[held]) <= 80 for e in "LTRB") - if not shared: - problems.append(f"{label}: {other} moved, and it is not next to the edge") - - pointer.up() - kde.wait_for(lambda: resize_ends() > ends, timeout=10) - after = settled() - - for n in near: - jump = edges(after[n])[OPPOSITE[held]] - edges(held_at["all the way"][n])[OPPOSITE[held]] - if abs(jump) > CELL: - problems.append(f"{n} jumped {jump} when the button was let go") - - names = list(after) - for i, n1 in enumerate(names): - x, y, w, h = after[n1] - if x < 0 or y < 0 or x + w > W or y + h > H: - problems.append(f"{n1} {after[n1]} is off the screen") - for n2 in names[i + 1 :]: - ox, oy, ow, oh = after[n2] - if x < ox + ow and ox < x + w and y < oy + oh and oy < y + h: - problems.append(f"{n1} and {n2} overlap") - - print(f"{case}: neighbors {near}, before {before}, let go {after}") - return problems - - -# BSP: win1 is the left half, win2 the top right and win3 the bottom right -cases = [ - "win2:left:-120,0", - "win2:left:90,0", - "win2:bottom:0,100", - "win3:top:0,-80", - "win1:right:100,0", -] -for case in cases: - problems = run_case(case) - checks.check(f"{case}: " + ("as expected" if not problems else "; ".join(problems)), not problems) +run_suite(checks, platform_only("kde", kde_live_resize.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/lock-sleep/test.py b/nix/tests/vm/suites/lock-sleep/test.py index 3a1564db..5dc715df 100644 --- a/nix/tests/vm/suites/lock-sleep/test.py +++ b/nix/tests/vm/suites/lock-sleep/test.py @@ -8,137 +8,15 @@ # komorebi waits for, logind's `PrepareForSleep` and the lock screen's `ActiveChanged`, are # tested on private buses by `komorebi/tests/power.rs`, and the desktop it finds on waking against # the fake by `komorebi/tests/wake.rs`. -import time -from komorebi_vm import Checks, Kde, Rect - -UNIT = "komorebi.service" -TITLES = ["sl-a", "sl-b", "sl-c"] -# what a terminal's frame may be off its tile by: up to a cell of its font -CELL = 24 -# the daemon's log of the day, without colors, which the unit writes -LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import lock_sleep as kde_lock_sleep start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) - - -def daemon_log() -> str: - return machine.execute(f"cat {LOG}")[1] - - -def frames() -> list[Rect]: - return [kde.rect(kde.wid(title)) for title in TITLES] - - -def settled_frames() -> list[Rect]: - """The frames the windows have once they have stopped moving: the same a second apart. - - A window that opens makes komorebi tile the others again, so the frames are not the tiles - until the last window has had its turn. - """ - seen: list[list[Rect]] = [] - - def still() -> bool: - seen.append(frames()) - time.sleep(1 * SCALE) - return len(seen) >= 2 and seen[-1] == seen[-2] - - kde.wait_for(still, timeout=60) - return seen[-1] - - -def tile_of(title: str) -> Rect: - """The tile the daemon has for the window now, from its layout.""" - workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] - for i, container in enumerate(workspace["containers"]["elements"]): - windows = container["windows"] - if windows["elements"][windows["focused"]]["details"]["title"] == title: - tile = workspace["latest_layout"][i] - return Rect(tile["left"], tile["top"], tile["right"], tile["bottom"]) - raise AssertionError(f"the daemon has no container for {title}") - - -def near(a: Rect, b: Rect) -> bool: - """Whether the frame is the tile, give or take the cell of the terminal's font.""" - return max(abs(a.x - b.x), abs(a.y - b.y), abs(a.w - b.w), abs(a.h - b.h)) <= CELL - - -def session_id() -> str: - """The id of the user's graphical session, which is the one that gets locked.""" - for line in kde.sh("loginctl list-sessions --no-legend").splitlines(): - words = line.split() - if len(words) > 2 and words[2] == "komorebi": - if kde.sh(f"loginctl show-session {words[0]} -p Type --value").strip() == "wayland": - return words[0] - raise AssertionError("the user has no Wayland session") - - -print("== 1. komorebi runs in the session, and has three windows") -checks.check( - "the module's unit runs the daemon, which answers komorebic", - kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=60), -) -# The daemon tiles the windows again when it learns of the panel's room. They are opened after that, -# so that they are tiled once. The wait is not a check: a session may never take the room, and it -# ends after a while. -kde.wait_for_panel_room() -for title in TITLES: - kde.spawn(f"foot -T {title} sleep 3010") - kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=60) -checks.check("komorebi manages the three", kde.wait_for(lambda: kde.managed(0) == 3, timeout=30)) -checks.check( - "they are tiled: none is on another", - kde.wait_for( - lambda: not any(a.overlaps(b) for i, a in enumerate(frames()) for b in frames()[i + 1 :]) - ), -) -tiles = settled_frames() -sid = session_id() -print(f" session {sid}; tiles: {tiles}") - -print("== 2. the screen is locked, and a window is moved while nothing can be drawn") -kde.sh(f"loginctl lock-session {sid}") -checks.check( - "komorebi noticed the lock screen coming up", - kde.wait_for(lambda: "the screen was locked" in daemon_log(), timeout=30), -) -kde.sh(f"kdotool windowmove {kde.wid('sl-b')} 400 300") -checks.check( - "while it is locked komorebi has the same three windows: the lock screen is not one", - kde.managed(0) == 3, -) -checks.check( - "the other two did not move for it", - kde.rect(kde.wid("sl-a")) == tiles[0] and kde.rect(kde.wid("sl-c")) == tiles[2], -) - -print("== 3. the screen is unlocked") -kde.sh(f"loginctl unlock-session {sid}") -checks.check( - "komorebi noticed the screen being unlocked", - kde.wait_for(lambda: "the screen was unlocked" in daemon_log(), timeout=30), -) -# the tile it has now, not the one it had: the shell's panel can take room from the windows after -# the windows were tiled, and the daemon puts every window in the room that is left -checks.check( - "the window that was moved is in its tile again", - kde.wait_for(lambda: near(kde.rect(kde.wid("sl-b")), tile_of("sl-b")), timeout=30), -) -checks.check("it still has three windows", kde.managed(0) == 3) -checks.check( - "its idea of the focus is KWin's", - kde.wait_for( - lambda: kde.active() != "" and kde.title(kde.active()) == kde.focused_title(0), - timeout=30, - ), -) -checks.check( - "and it is still running", - kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0, -) +run_suite(checks, platform_only("kde", kde_lock_sleep.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/look/test.py b/nix/tests/vm/suites/look/test.py index e854a306..99b3459d 100644 --- a/nix/tests/vm/suites/look/test.py +++ b/nix/tests/vm/suites/look/test.py @@ -12,229 +12,15 @@ # D no animation, the control: the same flip is there at once # # Every window is a `foot` of one color all over (`Kde.colored_window`). -import time -from komorebi_vm import Checks, Kde, Rect, daemon, pixels - -UNIT = "komorebi.service" -# the daemon's log of the day, without colors, which every run of the unit adds to -LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" -ROUNDED_CORNERS = "kwin4_effect_shapecorners" -GROUP = "Round-Corners" -GEOMETRY_CHANGE = "kwin4_effect_geometry_change" -ANIMATION_GROUP = "Effect-kwin4_effect_geometry_change" -FOCUSED = (66, 165, 245) -UNFOCUSED = (128, 128, 128) -RED = (255, 0, 0) +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import look as kde_look start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) - - -def running() -> bool: - return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 - - -def answering() -> bool: - return kde.run("komorebic monitor-information")[0] == 0 - - -def asked(title: str) -> Rect | None: - """The frame the daemon last asked KWin for, for the window with this title.""" - return daemon.asked(machine.execute(f"cat {LOG}")[1], title) - - -def start_komorebi() -> None: - kde.systemctl("start", UNIT) - kde.wait_for(answering, timeout=60) - # The shell's panel takes room from the windows a while after the shell has made it, and the - # daemon learns that up to a second later. The windows are opened after that: before it they - # are tiled under the panel and then again, and the ring is read in between. - kde.wait_for_panel_room() - # the border effect is written, loaded and told to read its settings as the daemon starts - time.sleep(2) - - -def stop_komorebi() -> None: - kde.systemctl("stop", UNIT) - kde.close_colored_windows() - - -print("== the effect is installed, and not loaded by anyone") -# the session started the module's unit when it logged in: this test starts its own runs -stop_komorebi() -checks.check("KDE Rounded Corners is installed", kde.effect_supported(ROUNDED_CORNERS)) -checks.check("Geometry Change is installed", kde.effect_supported(GEOMETRY_CHANGE)) -checks.check( - "and KWin does not load either by itself (they are built disabled by default)", - not kde.effect_loaded(ROUNDED_CORNERS) and not kde.effect_loaded(GEOMETRY_CHANGE), -) -before = kde.kwinrc_group(GROUP) -before_animation = kde.kwinrc_group(ANIMATION_GROUP) - - -def put_back() -> None: - checks.check("komorebi exited", not running()) - checks.check("the border effect is unloaded again", not kde.effect_loaded(ROUNDED_CORNERS)) - checks.check("the animation effect is unloaded again", not kde.effect_loaded(GEOMETRY_CHANGE)) - checks.check(f"kwinrc [{GROUP}] is as it was", kde.kwinrc_group(GROUP) == before) - checks.check( - f"kwinrc [{ANIMATION_GROUP}] is as it was", - kde.kwinrc_group(ANIMATION_GROUP) == before_animation, - ) - - -print("== A. komorebi starts, with the borders it has by default") -start_komorebi() -checks.check("the border effect is loaded", kde.effect_loaded(ROUNDED_CORNERS)) -rc = kde.kwinrc_group(GROUP) -checks.check( - "the border is the outer outline: 10 px, colored like the focused window", - rc.get("OuterOutlineThickness") == "10" and rc.get("OuterOutlineColor") == "66,165,245", -) -checks.check( - "nothing is drawn inside the window, over its title bar (the effect's default does)", - rc.get("OutlineThickness") == "0" and rc.get("SecondOutlineThickness") == "0", -) -checks.check( - "the unfocused window gets the other color", - rc.get("InactiveOuterOutlineColor") == "128,128,128", -) -checks.check("the corner radius is the border radius", rc.get("Size") == "10") - -print("== A. two windows, side by side") -kde.colored_window("red", "ff0000") -time.sleep(1) -kde.colored_window("blue", "0000ff") -checks.check("komorebi tiles both", kde.wait_for(lambda: kde.managed() == 2, timeout=30)) -time.sleep(3) -red, blue = kde.wid("red"), kde.wid("blue") -red_frame, blue_frame = kde.rect(red), kde.rect(blue) -print(f" red: {red_frame} blue: {blue_frame}") -checks.check("they are next to each other", not red_frame.overlaps(blue_frame)) -image = kde.shot("tiled") - -print("== A. the border is just outside the frame, on all four sides") -wrong = pixels.ring(image, blue_frame, FOCUSED) -checks.check( - "the focused window (blue) has the focus color around it" - + "".join(f"\n {w}" for w in wrong), - wrong == [], -) -wrong = pixels.ring(image, red_frame, UNFOCUSED) -checks.check( - "the other window (red) has the unfocused color around it" - + "".join(f"\n {w}" for w in wrong), - wrong == [], -) -inside = pixels.pixel(image, blue_frame.x + 40, blue_frame.y + 5) -checks.check( - f"the border does not cover the title bar (inside the frame, near its top: {inside})", - not pixels.near(inside, FOCUSED), -) - -print("== B. the commands that set the border reach the effect") -kde.komorebic("border-width", "6") -checks.check( - "a narrower border is a thinner outline", - kde.wait_for(lambda: kde.kwinrc_group(GROUP).get("OuterOutlineThickness") == "6", timeout=10), -) -kde.komorebic("border", "disable") -checks.check( - "no border unloads the effect", kde.wait_for(lambda: not kde.effect_loaded(ROUNDED_CORNERS)) -) -checks.check(f"and puts kwinrc [{GROUP}] back as it was", kde.kwinrc_group(GROUP) == before) -kde.komorebic("border", "enable") -checks.check( - "a border again loads the effect, with the width that was set", - kde.wait_for(lambda: kde.effect_loaded(ROUNDED_CORNERS), timeout=10) - and kde.kwinrc_group(GROUP).get("OuterOutlineThickness") == "6", -) - -print("== B. the layout leaves the room the border takes") -room = asked("blue") -kde.komorebic("border-width", "0") -kde.komorebic("retile") - - -def grew() -> bool: - now = asked("blue") - return room is not None and now is not None and (now.w - room.w, now.h - room.h) == (20, 20) - - -checks.check( - f"without the 10 px of border on each side the tile is 20 px wider and higher ({room})", - kde.wait_for(grew, timeout=10), -) - -stop_komorebi() -put_back() - - -def flip_of_red() -> tuple[Rect, Rect]: - """Flips the layout, and returns the frame red had and the one komorebi gave it.""" - kde.colored_window("red", "ff0000") - time.sleep(1) - kde.colored_window("blue", "0000ff") - kde.wait_for(lambda: kde.managed() == 2, timeout=30) - # well past the half of it, where an ease out is at 97 %: the windows have got where they go - time.sleep(16 * SCALE) - before_flip = kde.rect(kde.wid("red")) - kde.komorebic("flip-layout", "horizontal") - kde.wait_for(lambda: kde.rect(kde.wid("red")) != before_flip, timeout=10) - return before_flip, kde.rect(kde.wid("red")) - - -def point_in(frame: Rect) -> tuple[int, int]: - """A point inside the frame, far from where red came from, which is on its left.""" - return frame.x + frame.w - 60, frame.y + frame.h // 2 - - -print("== C. komorebi runs a 30 s animation") -start_komorebi() -kde.komorebic("animation-duration", "30000") -# an ease out is at 97 % after half of its time, which the waits below rely on (the default style -# is linear, which is at half) -kde.komorebic("animation-style", "--style", "ease-out-expo") -kde.komorebic("animation", "enable") -checks.check( - "the animation effect is loaded", - kde.wait_for(lambda: kde.effect_loaded(GEOMETRY_CHANGE), timeout=10), -) -animation = kde.kwinrc_group(ANIMATION_GROUP) -checks.check( - "it lasts what it was asked to, without cross-fading", - animation.get("Duration") == "30000" and animation.get("CrossFade") == "false", -) -was, now = flip_of_red() -print(f" red: {was} -> {now}") -checks.check("komorebi moved the window", was != now) -x, y = point_in(now) -soon = pixels.pixel(kde.shot("soon"), x, y) -checks.check( - f"a moment after the flip red has not got to its new place ({soon})", - not pixels.near(soon, RED), -) -time.sleep(16 * SCALE) -later = pixels.pixel(kde.shot("later"), x, y) -checks.check(f"and 16 s later it has ({later})", pixels.near(later, RED)) -stop_komorebi() -put_back() - -print("== D. without an animation, the control, the same flip is there at once") -start_komorebi() -checks.check("the animation effect is not loaded", not kde.effect_loaded(GEOMETRY_CHANGE)) -was, now = flip_of_red() -x, y = point_in(now) -at_once = pixels.pixel(kde.shot("control"), x, y) -checks.check( - f"red is at its new place when the screenshot is taken ({at_once})", - pixels.near(at_once, RED), -) -stop_komorebi() -put_back() +run_suite(checks, platform_only("kde", kde_look.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/module/test.py b/nix/tests/vm/suites/module/test.py index e86c9d6e..51cdc58f 100644 --- a/nix/tests/vm/suites/module/test.py +++ b/nix/tests/vm/suites/module/test.py @@ -8,211 +8,15 @@ # `komorebic enable-autostart` writes the entry systemd's autostart generator makes a unit of. The # options and the unit the module writes are checked without a machine by `nixos-module-eval` # (`nix/tests/nixos-module.nix`). -import json -import shlex -from komorebi_vm import Checks, Kde, Rect, daemon - -UNIT = "komorebi.service" -# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for -CELL = 24 -# the daemon's log of the day, without colors, which the unit's journal has -LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import module as kde_module start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) - - -def active() -> bool: - return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 - - -def failed() -> bool: - return kde.run(f"systemctl --user is-failed --quiet {UNIT}")[0] == 0 - - -def main_pid() -> str: - return kde.sh(f"systemctl --user show --property MainPID --value {UNIT}").strip() - - -def answering() -> bool: - return kde.run("komorebic monitor-information")[0] == 0 - - -def managed_titles() -> list[str]: - """The titles of the windows komorebi has on the first workspace of the first monitor.""" - workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] - return [ - window["details"]["title"] - for container in workspace["containers"]["elements"] - for window in container["windows"]["elements"] - ] - - -def daemon_log() -> str: - return machine.execute(f"cat {LOG}")[1] - - -print("== 1. logging in starts komorebi") -checks.check("the session started the module's unit", kde.wait_for(active, timeout=60)) -checks.check("its daemon answers komorebic", kde.wait_for(answering, timeout=60)) - -pid = main_pid() -command = kde.sh(f"tr '\\0' ' ' < /proc/{pid}/cmdline").split() -print(f" the unit runs: {' '.join(command)}") -checks.check("the unit runs bin/komorebi", command[0].endswith("/bin/komorebi")) -checks.check("... at the module's log level", command[1:3] == ["--log-level", "debug"]) -checks.check( - "... with the komorebi.json the module wrote as its --config", - len(command) == 5 and command[3] == "--config" and command[4].endswith("-komorebi.json"), -) -environment = kde.sh(f"tr '\\0' '\\n' < /proc/{pid}/environ").splitlines() -path = next((line[len("PATH=") :] for line in environment if line.startswith("PATH=")), "") -checks.check( - "... with the PATH of the user's session", - path.split(":") - == ["/run/wrappers/bin", "/etc/profiles/per-user/komorebi/bin", "/run/current-system/sw/bin"], -) - -print("== 1b. the daemon is configured by the file") -workspaces = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"] -checks.check( - "its workspaces are the ones the file names", - [workspace["name"] for workspace in workspaces] == ["web", "code"], -) -checks.check( - "KWin has a virtual desktop for each of them", - kde.wait_for(lambda: kde.desktops() >= 2, timeout=30), -) -checks.check( - "the settings the daemon says it has are the file's", - json.loads(kde.komorebic("generate-static-config"))["default_workspace_padding"] == 40, -) - -print("== 2. a window opened in the session is tiled") -width = json.loads(kde.komorebic("monitor-information"))[0]["size"]["right"] - - -def asked() -> Rect | None: - return daemon.asked(daemon_log(), "tiled") - - -def tiled() -> bool: - """KWin has the window where komorebi asked, and that is a tile across the screen.""" - want, wid = asked(), kde.wid("tiled") - if want is None or wid == "": - return False - have = kde.rect(wid) - return ( - (have.x, have.y) == (want.x, want.y) - and 0 <= want.w - have.w < CELL - and 0 <= want.h - have.h < CELL - and want.w > width // 2 - ) - - -kde.spawn("foot -T tiled sleep 3000") -checks.check("the window opens", kde.wait_for(lambda: kde.wid("tiled") != "", timeout=60)) -checks.check("komorebi manages it", kde.wait_for(lambda: "tiled" in managed_titles(), timeout=30)) -checks.check("KWin has it on its tile", kde.wait_for(tiled, timeout=30)) -print(f" asked {asked()}, has {kde.rect(kde.wid('tiled'))}") -want = asked() -checks.check( - "its tile is as far from the edge as the file's workspace padding says", - want is not None and want.x == 40, -) - -print("== 3. systemd starts a komorebi that was killed again") -kde.systemctl("kill", "--signal=SIGKILL", UNIT) -checks.check( - "the unit runs a new daemon", - kde.wait_for(lambda: active() and main_pid() not in ("0", pid), timeout=30), -) -checks.check("... which answers komorebic", kde.wait_for(answering, timeout=60)) -checks.check( - "... and manages the window again", - kde.wait_for(lambda: "tiled" in managed_titles(), timeout=30), -) - -print("== 4. a stop is not a failure") -kde.systemctl("stop", UNIT) -checks.check("stopped with SIGTERM, the unit is inactive", not active()) -checks.check("... and not failed", not failed()) -kde.systemctl("start", UNIT) -checks.check("started again, its daemon answers", kde.wait_for(answering, timeout=60)) -kde.komorebic("stop") -checks.check("komorebic stop stops the unit", kde.wait_for(lambda: not active(), timeout=30)) -checks.check("... which is not failed", not failed()) -checks.check("... and not started again", not kde.wait_for(active, timeout=5)) - -print("== 5. a daemon follows the file it is started with, and reloads it when it changes") -MINE = "/home/komorebi/mine.json" - - -def write(text: str) -> None: - kde.sh(f"printf %s {shlex.quote(text)} > {MINE}") - - -def resize_delta() -> int: - return json.loads(kde.komorebic("generate-static-config"))["resize_delta"] - - -def workspace_names() -> list[str]: - elements = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"] - return [workspace["name"] for workspace in elements] - - -write('{ "resize_delta": 100 }') -kde.komorebic("start", "--config", MINE) -checks.check("komorebic start --config starts a daemon that answers", kde.wait_for(answering)) -checks.check("... which has the settings of the file", resize_delta() == 100) - -write( - '{ "resize_delta": 33, "monitors": [ { "workspaces": [' - ' { "name": "one" }, { "name": "two" }, { "name": "three" } ] } ] }' -) -checks.check( - "a change to the file is applied", - kde.wait_for( - lambda: resize_delta() == 33 and workspace_names() == ["one", "two", "three"], - timeout=30, - ), -) -kde.komorebic("focus-workspace", "2") -checks.check( - "... and a workspace it added is one KWin shows", - kde.wait_for(lambda: kde.shown() == 3, timeout=30), -) -kde.komorebic("stop") -checks.check("that daemon stops", kde.wait_for(lambda: not answering(), timeout=30)) - -print("== 6. an autostart entry is run by the session") -ENTRY = "/home/komorebi/.config/autostart/komorebi.desktop" -AUTOSTART = "app-komorebi@autostart.service" -kde.komorebic("enable-autostart", "--config", MINE) -checks.check( - "komorebic enable-autostart writes the entry, with the file it is given", - f'Exec=komorebi --config "{MINE}"' in machine.succeed(f"cat {ENTRY}"), -) -kde.systemctl("daemon-reload") -status, unit_text = kde.run(f"systemctl --user cat {AUTOSTART}") -print(unit_text) -checks.check( - "systemd's autostart generator makes a unit of it, which runs komorebi", - status == 0 and "komorebi" in unit_text, -) -kde.systemctl("start", AUTOSTART) -checks.check("... which starts a daemon that answers", kde.wait_for(answering, timeout=60)) -checks.check("... with the file the entry gave it", resize_delta() == 33) -kde.komorebic("stop") -checks.check("that daemon stops", kde.wait_for(lambda: not answering(), timeout=30)) -kde.komorebic("disable-autostart") -checks.check( - "komorebic disable-autostart takes the entry away", - machine.execute(f"test -e {ENTRY}")[0] != 0, -) +run_suite(checks, platform_only("kde", kde_module.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/rdp/test.py b/nix/tests/vm/suites/rdp/test.py index 29daa393..8952ac14 100644 --- a/nix/tests/vm/suites/rdp/test.py +++ b/nix/tests/vm/suites/rdp/test.py @@ -7,51 +7,15 @@ # The client is FreeRDP's, on an X server of its own (`komorebi_vm.RdpClient`), so its picture can be # read back and compared with a screenshot of the display. The suite `run-kde` runs the same checks # with a password that the demo guest takes from the host's directory. -import secrets -import time -from komorebi_vm import Checks, Kde, RdpClient -from komorebi_vm.rdp import colors - -PASSWORD_FILE = "/home/komorebi/.config/komorebi-vm/rdp-password" +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import rdp as kde_rdp start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) -rdp = RdpClient(machine, kde) - - -def active(unit: str) -> bool: - return kde.run(f"systemctl --user is-active --quiet {unit}")[0] == 0 - - -checks.check("komorebi runs in the session", kde.wait_for(lambda: active("komorebi"), timeout=60)) -checks.check("with no password, KRDP does not start", not active("krdp")) - -password = secrets.token_hex(16) -kde.as_user( - f"umask 077 && mkdir -p $(dirname {PASSWORD_FILE}) && printf %s {password} > {PASSWORD_FILE}" -) -kde.systemctl("start", "krdp.service") - -checks.check("with a password, KRDP listens on port 3389", kde.wait_for(rdp.listening, timeout=60)) - -rdp.start_x_server() - -checks.check("a client with the password is let in", rdp.logs_in(password)) -checks.check("a client with another password is not", not rdp.logs_in("not-" + password)) - -started = time.monotonic() -rdp.connect(password) -checks.check("the client's picture is the display", rdp.shows_display()) -print(f"after {time.monotonic() - started:.1f}s") - -remote = rdp.picture() -print(f"the client's picture: {remote.size}, {colors(remote)} colors") -remote.save(machine.out_dir / "client.png") -print(machine.execute("journalctl --no-pager _SYSTEMD_USER_UNIT=krdp.service | tail -n 20")[1]) -print(machine.execute("tail -n 20 /tmp/xfreerdp.log")[1]) +run_suite(checks, platform_only("kde", kde_rdp.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/render-smoke/test.py b/nix/tests/vm/suites/render-smoke/test.py index 77b0e621..9b44079f 100644 --- a/nix/tests/vm/suites/render-smoke/test.py +++ b/nix/tests/vm/suites/render-smoke/test.py @@ -1,9 +1,11 @@ # A Plasma session draws a desktop in the test machine, so that every test after this one can trust # a screenshot. KSplash has thousands of colors on it too, so "not blank" is not the check: the # splash has to be gone and a window has to be painted on the desktop. -import time -from komorebi_vm import Checks, Kde +import time +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import render_smoke as kde_render_smoke start_all() started = time.monotonic() @@ -11,34 +13,5 @@ machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) -print(f"the desktop is up after {time.monotonic() - started:.0f}s") - - -def konsole() -> str: - return kde.run("kdotool search --class konsole | head -1")[1].strip() - - -kde.spawn("konsole") -checks.check("a window appears", kde.wait_for(lambda: konsole() != "", timeout=60)) -rect = kde.rect(konsole()) -checks.check("the window has a size", rect.w > 0 and rect.h > 0) - - -def painted() -> bool: - image = kde.shot("desktop") - center = image.getpixel((rect.x + rect.w // 2, rect.y + rect.h // 2)) - assert isinstance(center, tuple) - # the terminal's background is dark; the wallpaper behind it is not - return sum(center) < 3 * 90 - - -checks.check("the window is painted on the screen", kde.wait_for(painted, timeout=60)) - -image = kde.shot("desktop") -colors = image.getcolors(maxcolors=image.width * image.height) -assert colors is not None -print(f"the screenshot is {image.size[0]}x{image.size[1]} with {len(colors)} colors") -checks.check("the desktop behind it is drawn", len(colors) > 5000) - +run_suite(checks, platform_only("kde", kde_render_smoke.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/restart-survival/test.py b/nix/tests/vm/suites/restart-survival/test.py index 263084d2..91038514 100644 --- a/nix/tests/vm/suites/restart-survival/test.py +++ b/nix/tests/vm/suites/restart-survival/test.py @@ -3,117 +3,15 @@ # KWin, so a KWin that restarts forgets them. Only a real session can say that the module's unit # releases the keys of a daemon that was killed, that a new daemon takes them over, and that the # daemon registers them again with the kglobalaccel of a new KWin. -import json -import shlex -from komorebi_vm import Checks, Kde, Keys +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import restart_survival as kde_restart_survival start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) -keys = Keys(machine) - - -def presses() -> int: - """How many times a binding has run.""" - return len(machine.execute("cat /tmp/keys-restart")[1].split()) - - -def press(combo: str) -> bool: - before = presses() - keys.send(combo) - return kde.wait_for(lambda: presses() > before, timeout=10) - - -def registered(actions: list[str], timeout: float = 30) -> bool: - return kde.wait_for(lambda: kde.shortcut_actions() == actions, timeout=timeout) - - -def write(skhdrc: str) -> None: - kde.sh( - f"mkdir -p ~/.config/komorebi && printf '%s' {shlex.quote(skhdrc)}" - " > ~/.config/komorebi/skhdrc" - ) - - -def main_pid() -> str: - return kde.systemctl("show", "--property=MainPID", "--value", "komorebi.service").strip() - - -# the module's unit runs the daemon, which reads the skhdrc of the config directory at start -write("alt - h : echo h >> /tmp/keys-restart\n") -kde.systemctl("restart", "komorebi.service") -checks.check("the daemon of the unit registers Alt+H", registered(["Alt+H"])) -checks.check("Alt+H runs its binding", press("alt-h")) - -state = json.loads(kde.komorebic("hotkeys", "state")) -checks.check( - f"hotkeys state shows the key and the engine ({state})", - state["registered"] == ["Alt+H"] - and state["engine"]["mode"] == "default" - and state["engine"]["active"] == ["Alt+H"], -) - -# a daemon that does not answer leaves its keys dead, until they are released -machine.succeed("pkill -STOP -x komorebi") -before = presses() -keys.send("alt-h") -checks.check( - "the key of a stopped daemon runs nothing", - not kde.wait_for(lambda: presses() > before, timeout=3), -) -released = kde.komorebic("hotkeys", "release") -checks.check(f"hotkeys release unregisters it ({released.strip()})", "Alt+H" in released) -checks.check("no key is registered after the release", kde.shortcut_actions() == []) -machine.succeed("pkill -CONT -x komorebi") -kde.systemctl("restart", "komorebi.service") -checks.check("a new daemon registers the key again", registered(["Alt+H"])) -checks.check("Alt+H runs its binding again", press("alt-h")) - -# a daemon that is killed: the unit releases its keys, and systemd starts a new one -old = main_pid() -# the main process alone, as a crash: killing the whole unit would kill ExecStopPost too -kde.systemctl("kill", "--kill-whom=main", "--signal=SIGKILL", "komorebi.service") -checks.check( - "systemd starts the daemon again", - kde.wait_for(lambda: main_pid() not in ("0", old), timeout=30), -) - - -def journal() -> str: - """The journal of the machine since it booted: the unit's lines, ExecStopPost's among them.""" - return machine.execute("journalctl --no-pager -o cat -b")[1] - - -released = kde.wait_for(lambda: "released 1 keys: Alt+H" in journal(), timeout=10) -words = ("released", "had no key", "could not release", "komorebi.service") -seen = [line for line in journal().splitlines() if any(word in line for word in words)] -checks.check(f"the unit released the keys of the killed daemon (it logged {seen[-6:]})", released) -checks.check("the new daemon has the key", registered(["Alt+H"])) -checks.check("Alt+H runs its binding after the kill", press("alt-h")) - -# KWin restarts, and kglobalaccel with it -kwins = machine.succeed("pgrep -a kwin_wayland || true") -print(kwins) -compositors = [ - line.split()[0] - for line in kwins.splitlines() - if line.strip() and "wrapper" not in line.split()[1] -] -machine.succeed(f"kill -KILL {' '.join(compositors)}") -checks.check( - "a new KWin owns kglobalaccel", - kde.wait_for(lambda: kde.has_name("org.kde.kglobalaccel"), timeout=60), -) -checks.check("the daemon registers the key with the new KWin", registered(["Alt+H"], timeout=60)) -checks.check("Alt+H runs its binding after KWin restarted", press("alt-h")) - -# a reload reads the file again -write("alt - j : echo j >> /tmp/keys-restart\n") -kde.komorebic("hotkeys", "reload") -checks.check("after a reload the daemon has the key of the new file", registered(["Alt+J"])) -checks.check("Alt+J runs its binding", press("alt-j")) +run_suite(checks, platform_only("kde", kde_restart_survival.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/run-kde/test.py b/nix/tests/vm/suites/run-kde/test.py index ae9ebc57..cda9d6be 100644 --- a/nix/tests/vm/suites/run-kde/test.py +++ b/nix/tests/vm/suites/run-kde/test.py @@ -10,154 +10,15 @@ # KRDP by hand here: that it listens shows that the guest took the password before the login, as the # command's guest has to. The command itself, `scripts/run-kde`, is checked by `run-kde-dry-run` and # `run-kde-doctor`, which a VM cannot: it is a program of the host. -import re -from komorebi_vm import Checks, Kde, RdpClient -from komorebi_vm.rdp import colors - -SHARED = "/run/run-kde" -TAKEN = "/run/run-kde-guest" -PASSWORD = "a-password-of-the-host" -CHEAT_SHEET_TITLE = "komorebi cheat sheet" +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import run_kde as kde_run_kde start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) -rdp = RdpClient(machine, kde) - - -def active(unit: str) -> bool: - return kde.run(f"systemctl --user is-active --quiet {unit}")[0] == 0 - - -def tiles() -> list[str]: - """The titles of the tiled windows of the first workspace, or none while the daemon is busy.""" - try: - return [title for container in kde.containers(0) for title in container] - except AssertionError: - return [] - - -def demo_is_open() -> bool: - titles = tiles() - return ( - sum("Konsole" in title for title in titles) == 2 - and any("Kate" in title for title in titles) - and any("Dolphin" in title for title in titles) - ) - - -checks.check("komorebi runs in the session", kde.wait_for(lambda: active("komorebi"), timeout=60)) - -print("== the windows of the demo") -checks.check( - "the demo opens two Konsole windows, Kate and Dolphin, and komorebi tiles them", - kde.wait_for(demo_is_open, timeout=240), -) -checks.check( - "the cheat sheet is a window", - kde.wait_for(lambda: kde.wid(CHEAT_SHEET_TITLE) != "", timeout=120), -) -titles = tiles() -print(f"the tiles: {titles}") -checks.check("the cheat sheet is not one of the tiles", len(titles) == 4) - -# a window tiled before komorebi knew the panel's room is tiled under the panel -monitor = kde.state()["monitors"]["elements"][0] -work = monitor["work_area_size"] -work_bottom = work["top"] + work["bottom"] -bottoms = {title: (lambda r: r.y + r.h)(kde.rect(kde.wid(title))) for title in titles} -print(f"the bottom of the work area: {work_bottom}; of the tiles: {bottoms}") -checks.check( - "every tile ends above the panel", - all(bottom <= work_bottom for bottom in bottoms.values()), -) -checks.check("the screen shows a desktop", colors(kde.shot("demo")) > 1000) - -print("== the cheat sheet") -checks.check( - "the cheat sheet has the bindings of the sample file", - machine.execute("grep -q 'alt + shift - 0x21' /etc/run-kde/cheat-sheet.txt")[0] == 0 - and machine.execute("grep -q 'komorebic change-layout' /etc/run-kde/cheat-sheet.txt")[0] == 0, -) -checks.check( - "KWin's renderer is found, and said as the cheat sheet says it", - kde.wait_for( - lambda: machine.execute(f"test -s /run/user/{kde.uid}/run-kde-renderer")[0] == 0, - timeout=60, - ), -) -renderer = machine.succeed(f"cat /run/user/{kde.uid}/run-kde-renderer").strip() -print(f"the renderer: {renderer}") -checks.check( - "a node with no GPU draws in software", - re.match(r"software \(llvmpipe\): ", renderer) is not None, -) -checks.check( - "the console is told too", - machine.execute( - "journalctl -b -u run-kde-report --no-pager | grep -q 'run-kde: KWin draws with'" - )[0] - == 0, -) - -status, out = kde.run("KOMOREBI_CONFIG_HOME=/etc/run-kde/config-home komorebic check") -print(out) -checks.check( - "komorebic check, as the cheat sheet runs it, has no error", - status == 0 and "\n0 error(s)" in out, -) -checks.check( - "it reads the key bindings the daemon runs", - re.search(r"ok +\S*skhdrc has \d+ key bindings?", out) is not None, -) -checks.check( - "it sees komorebi, and its script in KWin", - "komorebi is running, and its script is in KWin" in out, -) - -print("== what the host shares") -checks.check( - "the guest's user cannot read the host's directory", - machine.execute(f"runuser -u komorebi -- cat {SHARED}/rdp-password")[0] != 0, -) -checks.check( - "the password is taken for the user, and for no one else", - machine.succeed(f"stat -c '%U %a' {TAKEN}/rdp-password").strip() == "komorebi 400", -) -checks.check( - "the key is taken as the user's authorized key", - machine.succeed(f"cat {TAKEN}/authorized_keys.d/komorebi").split()[:2] - == machine.succeed(f"cut -d' ' -f1,2 {SHARED}/ssh_key.pub").split(), -) -machine.succeed("install -m 600 /etc/run-kde-test/ssh_key /tmp/ssh_key") -ssh = ( - "ssh -i /tmp/ssh_key -o IdentitiesOnly=yes -o StrictHostKeyChecking=no" - " -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o LogLevel=ERROR komorebi@127.0.0.1" -) -machine.wait_for_unit("sshd.service") -checks.check("ssh lets in the host's key", machine.execute(f"{ssh} true")[0] == 0) -checks.check( - "and no other", - machine.execute( - "ssh-keygen -q -t ed25519 -N '' -f /tmp/other_key" - f" && {ssh.replace('/tmp/ssh_key', '/tmp/other_key')} true" - )[0] - != 0, -) - -print("== RDP, with the host's password") -checks.check( - "KRDP started by itself and listens on port 3389", - kde.wait_for(lambda: active("krdp") and rdp.listening(), timeout=60), -) -rdp.start_x_server() -checks.check("a client with the host's password is let in", rdp.logs_in(PASSWORD)) -checks.check("a client with another password is not", not rdp.logs_in("not-" + PASSWORD)) -rdp.connect(PASSWORD) -checks.check("the client's picture is the display", rdp.shows_display()) -rdp.picture().save(machine.out_dir / "client.png") +run_suite(checks, platform_only("kde", kde_run_kde.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/user-maximize/test.py b/nix/tests/vm/suites/user-maximize/test.py index 02332bcd..a493ef62 100644 --- a/nix/tests/vm/suites/user-maximize/test.py +++ b/nix/tests/vm/suites/user-maximize/test.py @@ -4,165 +4,16 @@ # and put the window back in its tile when it is restored, by the user or by komorebi. # `komorebi/tests/user_maximize.rs` checks what the window manager does against the fake; this # checks that KWin reports the user's maximize, and the restore, the way komorebi reads them. -import json -import shlex -import time -from typing import Any -from komorebi_vm import Checks, Kde, Rect, daemon - -W, H = 1920, 1080 -# The windows are tiled with a gap of 10 pixels around the workspace and between the tiles: a tile -# has padding, and a maximized window has none. The windows are not animated. -CONFIG = "/tmp/user-maximize-config.json" +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import user_maximize as kde_user_maximize start_all() machine.wait_for_unit("multi-user.target") machine.wait_for_unit("user@1000.service") checks = Checks() -kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) - -def workspace() -> dict[str, Any]: - return kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] - - -def containers() -> int: - return len(workspace()["containers"]["elements"]) - - -def maximized_title() -> str | None: - window = workspace()["maximized_window"] - return None if window is None else window["details"]["title"] - - -def fills(r: Rect) -> bool: - """The work area is the whole output: a virtual KWin has no panel.""" - return r.w >= W - 40 and r.h >= H - 80 - - -def rect_of(title: str) -> Rect: - return kde.rect(kde.wid(title)) - - -def open_window(title: str) -> None: - kde.spawn(f"foot -T {title} sleep 3000") - kde.wait_for(lambda: kde.wid(title) != "", timeout=30) - - -print("== three windows, tiled") -kde.sh( - "printf %s " - + shlex.quote( - json.dumps( - { - "default_workspace_padding": 10, - "default_container_padding": 10, - "animation": {"enabled": False}, - } - ) - ) - + f" > {CONFIG}" -) -kde.start_komorebi("--config", CONFIG) -kde.wait_for(lambda: kde.run("komorebic monitor-information")[0] == 0, timeout=30) -for title in ("um-a", "um-b", "um-c"): - open_window(title) -checks.check("komorebi has three tiles", kde.wait_for(lambda: containers() == 3, timeout=20)) -# The bridge asks again for the position of a window that is not where komorebi put it for a second -# after it did (PLATFORM.md, "How clients answer a frame"), which would put a window that is -# maximized in that second back where its tile was: wait that second out, as a person would. -kde.wait_for(lambda: kde.focused_title() == "um-c", timeout=20) -time.sleep(3 * SCALE) -tiles = {title: rect_of(title) for title in ("um-a", "um-b", "um-c")} -print(f" the tiles are {tiles}") - -print("== 1. the user maximizes a window with its title bar") -kde.maximize(kde.wid("um-b")) -checks.check( - "komorebi has it as its maximized window", - kde.wait_for(lambda: maximized_title() == "um-b", timeout=20), -) -checks.check( - f"it fills the work area ({rect_of('um-b')})", - kde.wait_for(lambda: fills(rect_of("um-b")), timeout=10), -) -checks.check("and its tile is gone: two are left", containers() == 2) -checks.check( - "komorebi handled it as a change of the window's maximized state", - any( - event.kind == "MaximizeChange" and event.notification == "WindowMaximizedChanged" - for event in daemon.events(kde.komorebi_log()) - ), -) -checks.check("it still has all three windows", kde.managed_all() == 3) - -print("== 2. what is asked of the layout does nothing") -beside = {title: rect_of(title) for title in ("um-a", "um-c")} -for command in [ - "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", -]: - kde.komorebic(*command.split()) -time.sleep(1 * SCALE) -checks.check( - "it is still maximized, and still komorebi's maximized window", - fills(rect_of("um-b")) and maximized_title() == "um-b", -) -checks.check( - "the others did not move, and nothing floats or is in the monocle", - {title: rect_of(title) for title in ("um-a", "um-c")} == beside - and containers() == 2 - and workspace()["floating_windows"]["elements"] == [] - and workspace()["monocle_container"] is None, -) -checks.check( - "komorebi noted that it ignored them", - "ignoring" in kde.komorebi_log() and "the window in front is maximized" in kde.komorebi_log(), -) - -print("== 3. toggle-maximize restores it") -kde.komorebic("toggle-maximize") -checks.check( - f"it is back in its tile ({tiles['um-b']})", - kde.wait_for(lambda: rect_of("um-b") == tiles["um-b"], timeout=20), -) -checks.check( - "and nothing is maximized", - maximized_title() is None and containers() == 3, -) - -print("== 4. the user restores it with the title bar") -kde.maximize(kde.wid("um-c")) -checks.check( - "maximized again", - kde.wait_for(lambda: maximized_title() == "um-c" and containers() == 2, timeout=20), -) -kde.unmaximize(kde.wid("um-c")) -checks.check( - f"restored by the user, it is back in its tile ({tiles['um-c']})", - kde.wait_for(lambda: rect_of("um-c") == tiles["um-c"], timeout=20), -) -checks.check( - "and nothing is maximized", - kde.wait_for(lambda: maximized_title() is None and containers() == 3, timeout=10), -) - -kde.komorebic("stop") -kde.wait_for(lambda: not kde.komorebi_running()) -kde.stop() +run_suite(checks, platform_only("kde", kde_user_maximize.run, machine, checks, SCALE)) checks.finish() diff --git a/nix/tests/vm/suites/wallpaper/test.py b/nix/tests/vm/suites/wallpaper/test.py index ff6462b5..4817d03e 100644 --- a/nix/tests/vm/suites/wallpaper/test.py +++ b/nix/tests/vm/suites/wallpaper/test.py @@ -11,249 +11,15 @@ # # The pictures are a dozen bands of color each, since a palette wants at least eight: a warm one for # the monitor, a cool one for the second workspace, and a green one the test sets by hand. -import base64 -import io -import re -import shlex -import time -from PIL import Image - -from komorebi_vm import Checks, Kde, Rect, pixels - -UNIT = "komorebi.service" -SHELL_UNIT = "plasma-plasmashell.service" -# the daemon's log of the day, without colors, which every run of the unit adds to -LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" -CONFIG = "/home/komorebi/.config/komorebi/komorebi.json" -PICTURES = "/tmp/wallpapers" -WARM = f"{PICTURES}/warm.png" -COOL = f"{PICTURES}/my pictures/cool.png" -OTHER = f"{PICTURES}/other.png" -WARM_URL = f"file://{PICTURES}/warm.png" -COOL_URL = f"file://{PICTURES}/my%20pictures/cool.png" -# `Image.PreserveAspectCrop`, which is how komorebi has the shell fill the screen -FILL = 2 +from komorebi_vm import Checks +from komorebi_vm.core.suite import platform_only, run_suite +from komorebi_vm.platforms.kde.extras import wallpaper as kde_wallpaper start_all() machine.wait_for_unit("multi-user.target") checks = Checks() -kde = Kde.session(machine, scale=SCALE) - - -def picture(hue: tuple[int, int, int], ramp: int) -> bytes: - """A 192 by 108 PNG of diagonal bands of `hue`, going dark and light, `ramp` varying the hue.""" - data: list[tuple[int, int, int]] = [] - for y in range(108): - for x in range(192): - band = (x // 16 + y // 16) % 12 - shade = 40 + (band % 4) * 55 - red, green, blue = hue - green = min(255, green + band * ramp) - data.append( - (min(255, red * shade // 255), min(255, green * shade // 255), blue * shade // 255) - ) - image = Image.new("RGB", (192, 108)) - image.putdata(data) - out = io.BytesIO() - image.save(out, "PNG") - return out.getvalue() - - -def put(path: str, data: bytes) -> None: - """Writes `data` to `path` in the machine, where the test user can read it.""" - directory = shlex.quote(path.rsplit("/", 1)[0]) - encoded = base64.b64encode(data).decode() - machine.succeed(f"mkdir -p {directory} && chmod a+rx {directory}") - machine.succeed(f"echo {encoded} | base64 -d > {shlex.quote(path)}") - machine.succeed(f"chmod a+r {shlex.quote(path)}") - - -def running() -> bool: - return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 - - -def answering() -> bool: - return kde.run("komorebic monitor-information")[0] == 0 - - -def start_komorebi() -> None: - kde.systemctl("start", UNIT) - kde.wait_for(answering, timeout=60) - time.sleep(2) - - -def stop_komorebi() -> None: - kde.systemctl("stop", UNIT) - kde.close_colored_windows() - - -def shell_wallpaper() -> tuple[str, int]: - """What the shell shows on its first screen: the picture's URL, and the fill mode.""" - out = kde.run( - "busctl --user call org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell wallpaper u 0" - )[1] - image = re.search(r'"Image" s "([^"]*)"', out) - fill = re.search(r'"FillMode" i (\d+)', out) - return (image.group(1) if image else "", int(fill.group(1)) if fill else -1) - - -def shows(url: str) -> bool: - return shell_wallpaper()[0] == url - - -def hue_of(image: Image.Image) -> str: - """Warm, cool or neither: the average color of a grid of points of the screen.""" - width, height = image.size - points = [ - pixels.pixel(image, width * i // 10, height * j // 12) - for i in range(1, 10) - for j in range(1, 9) - ] - red = sum(p[0] for p in points) / len(points) - blue = sum(p[2] for p in points) / len(points) - return "warm" if red > blue + 40 else "cool" if blue > red + 40 else "neither" - - -def screen_is(hue: str, name: str) -> bool: - """Takes pictures of the screen until it is `hue`: one can catch the shell half way.""" - return kde.wait_for(lambda: hue_of(kde.shot(name)) == hue, timeout=20) - - -def ring_hue(frame: Rect, image: Image.Image) -> str: - """The hue of the ring just outside the left edge of a frame.""" - red, _, blue = pixels.pixel(image, frame.x - 5, frame.y + frame.h // 2) - return "warm" if red > blue + 40 else "cool" if blue > red + 40 else "neither" - - -def has_ring(title: str, hue: str, name: str) -> bool: - """Returns true if the window has a ring of `hue` in a screenshot taken until it does.""" - return kde.wait_for( - lambda: ring_hue(kde.rect(kde.wid(title)), kde.shot(name)) == hue, timeout=20 - ) - - -print("== the pictures, and the wallpapers of the configuration") -put(WARM, picture((255, 0, 20), 20)) -put(COOL, picture((20, 80, 255), 14)) -put(OTHER, picture((60, 255, 60), 0)) -kde.sh(f"mkdir -p {shlex.quote(CONFIG.rsplit('/', 1)[0])}") -config = ( - '{ "monitors": [ { "wallpaper": { "path": "' + WARM + '" },' - ' "workspaces": [ { "name": "one" },' - ' { "name": "two", "wallpaper": { "path": "' + COOL + '" } } ] } ] }' -) -kde.sh(f"echo {shlex.quote(config)} > {CONFIG}") -kde.sh("rm -rf ~/.cache/komorebi") - -# the session started the module's unit when it logged in: this test starts its own runs -stop_komorebi() -kde.sh(f"plasma-apply-wallpaperimage {shlex.quote(OTHER)}") -checks.check( - "the shell shows a picture of the user's choice to begin with", - kde.wait_for(lambda: shows(f"file://{OTHER}"), timeout=20), -) - -print("== A. set at start, and by workspace") -start_komorebi() -checks.check( - "at start the shell shows the monitor's wallpaper", - kde.wait_for(lambda: shows(WARM_URL), timeout=20), -) -checks.check("it fills the screen", shell_wallpaper()[1] == FILL) -checks.check("and the screen is warm", screen_is("warm", "a1")) - -began = time.monotonic() -kde.komorebic("focus-workspace", "1") -checks.check( - "workspace two's own wallpaper is shown when it is (the path has a space in it)", - kde.wait_for(lambda: shows(COOL_URL), timeout=10), -) -took = time.monotonic() - began -checks.check(f"it took under two seconds ({took:.1f} s)", took < 2 * max(1, SCALE)) -checks.check("and the screen is cool", screen_is("cool", "a2")) - -kde.komorebic("focus-workspace", "0") -checks.check( - "back on workspace one, the monitor's wallpaper again", - kde.wait_for(lambda: shows(WARM_URL), timeout=10), -) - -print("== B. a switch somebody else made") -kde.sh("kdotool set_desktop 2") -checks.check( - "the desktop was changed outside komorebi, and its wallpaper came with it", - kde.wait_for(lambda: shows(COOL_URL), timeout=10), -) -kde.sh("kdotool set_desktop 1") -checks.check("and back", kde.wait_for(lambda: shows(WARM_URL), timeout=10)) - -print("== C. the borders follow the wallpaper") -kde.colored_window("left", "303030") -time.sleep(1.5) -checks.check( - "on the warm workspace the focused window's ring is warm", has_ring("left", "warm", "c1") -) -kde.komorebic("focus-workspace", "1") -time.sleep(2) -kde.colored_window("right", "303030") -time.sleep(2) -checks.check("on the cool one it is cool", has_ring("right", "cool", "c2")) -kde.komorebic("focus-workspace", "0") -time.sleep(2.5) -checks.check("and warm again when the first is back", has_ring("left", "warm", "c3")) - -print("== D. a wallpaper changed by hand is put back") -kde.sh(f"plasma-apply-wallpaperimage {shlex.quote(OTHER)}") -checks.check( - "the user changed it", - kde.wait_for(lambda: shows(f"file://{OTHER}"), timeout=10), -) -kde.komorebic("focus-workspace", "1") -time.sleep(1) -kde.komorebic("focus-workspace", "0") -checks.check( - "showing the workspace again set it back", - kde.wait_for(lambda: shows(WARM_URL), timeout=10), -) - -print("== E. the palette is kept") -cache = kde.sh("ls ~/.cache/komorebi 2>/dev/null || true").split() -print(f" the cache: {cache}") -checks.check( - "a palette for each wallpaper is in the cache, named for the picture", - any(n.startswith("warm-") for n in cache) and any(n.startswith("cool-") for n in cache), -) -daemon_log = machine.execute(f"cat {LOG}")[1] -checks.check( - "komorebi did not complain", - "failed to set wallpaper" not in daemon_log - and "gave up setting the wallpaper" not in daemon_log, -) -stop_komorebi() - -print("== F. komorebi starts before the Plasma shell") -kde.sh(f"plasma-apply-wallpaperimage {shlex.quote(OTHER)}") -kde.systemctl("stop", SHELL_UNIT) -checks.check( - "the shell is gone", kde.wait_for(lambda: not kde.has_name("org.kde.plasmashell"), timeout=20) -) -start_komorebi() -time.sleep(3) -checks.check("no shell to answer: komorebi is still managing", answering()) -kde.systemctl("start", SHELL_UNIT) -checks.check( - "the shell is back", kde.wait_for(lambda: kde.has_name("org.kde.plasmashell"), timeout=60) -) -checks.check( - "once the shell is up the wallpaper is set", - kde.wait_for(lambda: shows(WARM_URL), timeout=60), -) -daemon_log = machine.execute(f"cat {LOG}")[1] -checks.check( - "and komorebi did not give up and say so", "gave up setting the wallpaper" not in daemon_log -) -stop_komorebi() +run_suite(checks, platform_only("kde", kde_wallpaper.run, machine, checks, SCALE)) checks.finish()