fix(nix): KdePlatform meets the contract Windows already does

spawn raised nowhere on KDE when the window never came, so a check
that a window stays unmanaged passed for a window that was not there.
It does raise now, as do close, minimize, activate and move_window for
a window that does not exist, and a program name Windows rejects. A
title is looked for as it is and not as a pattern. displays() is what
KWin says of each output and not the size the session was given
(Kde.screens, the same script that gives the work area).

The docstrings of Platform say what each member promises and what a
scenario may not lean on.
This commit is contained in:
LGUG2Z committed 2026-10-30 12:51:01 -07:00
1 parent 5c4621ae44
commit 40eba4aade
5 files changed
+176 -46

No files matched your search

+32 -9
View File
@@ -34,8 +34,12 @@ class OsWindow:
title: str
frame: Rect
"""The visible frame: the compositor's on KDE, the DWM's extended frame on Windows."""
"""The visible frame: the compositor's on KDE, the DWM's extended frame on Windows, without
the invisible borders and the shadow. A scenario does not read the frame of a window that is
minimized: it is where the system keeps it, which is not the same on every port."""
focused: bool
"""The window has the keyboard focus, as the operating system says. At most one window of a
desktop does; none does while another program's window has it."""
class Pointer(Protocol):
@@ -93,7 +97,12 @@ class Platform(Protocol):
...
def wait_for(self, predicate: "Predicate", timeout: float = 10) -> bool:
"""Polls `predicate` until it holds or `timeout` seconds, scaled for this host, pass."""
"""Polls `predicate` until it holds or `timeout` seconds, scaled for this host, pass.
A predicate answers false for what it cannot tell yet. A port may treat a `komorebic`
that fails, in a predicate, as a false (Windows does, while the host is busy), and one may
not (KDE raises): a predicate does not rely on either.
"""
...
def start_komorebi(self) -> None:
@@ -128,7 +137,10 @@ class Platform(Protocol):
...
def spawn(self, title: str, app_id: str | None = None, exe: str | None = None) -> Client:
"""Opens a window with this title and waits until the platform has it.
"""Opens a window with this title and waits until the platform has it, and raises if it
never does: a scenario that waits for a window to stay unmanaged must be sure it is there.
A title is a name that no other window has, taken as it is: it is never a pattern.
`app_id` is the class of the window (its app id on Wayland, its window class on Windows)
for a rule that matches by it; the platform's own when there is none.
@@ -164,7 +176,11 @@ class Platform(Protocol):
def displays(self) -> list[Rect]:
"""The displays the operating system has, left to right: each one's rectangle in the
coordinates of the desktop. The daemon is not asked."""
coordinates of the desktop. The daemon is not asked.
Displays are not the same size (the one `add_display` plugs in may be smaller than the
first) and need not touch: a scenario uses each one's own rectangle and does not compute
where the next begins."""
...
def add_display(self) -> None:
@@ -174,16 +190,22 @@ class Platform(Protocol):
...
def remove_display(self) -> None:
"""Unplugs the display that was plugged in last, and returns when the operating system no
longer has it."""
"""Unplugs the last display (the rightmost, which is the one `add_display` plugged in last),
and returns when the operating system no longer has it.
Only a display `add_display` plugged in is certain to be removable: Windows refuses
any other, KDE unplugs the last of the outputs it has. A scenario unplugs a display only
after it plugged one in, unless its suite started the platform with more than one."""
...
def close(self, client: Client) -> None:
"""Closes the window, as its close button would."""
"""Closes the window, as its close button would, and returns without waiting for it to be
gone. Raises if there is no such window."""
...
def minimize(self, client: Client) -> None:
"""Minimizes the window, as its title bar button would. `activate` restores it."""
"""Minimizes the window, as its title bar button would. `activate` restores it. Raises if
there is no such window."""
...
def lock(self) -> None:
@@ -213,7 +235,8 @@ class Platform(Protocol):
...
def activate(self, client: Client) -> None:
"""Gives the window the focus, as a click on it would."""
"""Gives the window the focus, as a click on it would, and restores it if it was minimized.
Raises if there is no such window."""
...
def screenshot(self, name: str) -> Image.Image:
+32 -24
View File
@@ -499,8 +499,10 @@ class Kde:
return status == 0
def wid(self, title: str) -> str:
"""The id of the first window whose title is exactly `title`, or the empty string."""
pattern = shlex.quote(f"^{title}$")
"""The id of the first window whose title is exactly `title` (it is not a pattern), or the
empty string."""
literal = re.sub(r"([\\.+*?()|\[\]{}^$])", r"\\\1", title)
pattern = shlex.quote(f"^{literal}$")
return self.run(f"kdotool search --name {pattern} | head -1")[1].strip()
def wid_by_class(self, app: str) -> str:
@@ -702,43 +704,49 @@ class Kde:
)
return [line for line in self.kwin_reports(name) if line != "done"]
def work_area(self) -> Rect | None:
"""The area of the first output that windows may take, as KWin has it (its placement
area: the output less the panels), or `None` when KWin does not say.
def screens(self) -> list[tuple[Rect, Rect]] | None:
"""What KWin says of each enabled output, left to right: its rectangle in the coordinates
of the desktop, and the area of it that windows may take (KWin's placement area: the
output less the panels, as the daemon's bridge reads it). `None` when KWin does not say.
The first output is the leftmost one. It is the area of the desktop the output shows, as
the daemon's bridge reads it. A KWin script asks, because `kdotool` has no call for it.
A KWin script asks, because `kdotool` has no call for either.
"""
source = """
var first = null;
for (var i = 0; i < workspace.screens.length; i++) {
var s = workspace.screens[i];
if (first === null || s.geometry.x < first.geometry.x
|| (s.geometry.x === first.geometry.x && s.geometry.y < first.geometry.y)) {
first = s;
}
}
if (first !== null) {
var g = s.geometry;
var a = workspace.clientArea(
KWin.PlacementArea, first, workspace.currentDesktopForScreen(first));
report("area", Math.round(a.x), Math.round(a.y), Math.round(a.width),
KWin.PlacementArea, s, workspace.currentDesktopForScreen(s));
report("screen", Math.round(g.x), Math.round(g.y), Math.round(g.width),
Math.round(g.height), Math.round(a.x), Math.round(a.y), Math.round(a.width),
Math.round(a.height));
}
report("done");
"""
try:
lines = self.kwin_script(f"work-area-{next(_PROBES)}", source)
lines = self.kwin_script(f"screens-{next(_PROBES)}", source)
except AssertionError:
return None
found: list[tuple[Rect, Rect]] = []
for line in lines:
words = line.split()
if words[:1] == ["area"] and len(words) == 5:
try:
x, y, w, h = (int(word) for word in words[1:])
except ValueError:
return None
return Rect(x, y, w, h) if w > 0 and h > 0 else None
return None
if words[:1] != ["screen"] or len(words) != 9:
continue
try:
n = [int(word) for word in words[1:]]
except ValueError:
return None
if n[2] <= 0 or n[3] <= 0 or n[6] <= 0 or n[7] <= 0:
return None
found.append((Rect(*n[0:4]), Rect(*n[4:8])))
found.sort(key=lambda pair: (pair[0].x, pair[0].y))
return found or None
def work_area(self) -> Rect | None:
"""The area of the first (leftmost) output that windows may take, as KWin has it, or `None`
when KWin does not say ([`Kde.screens`][])."""
screens = self.screens()
return screens[0][1] if screens else None
def kwin_reports(self, name: str) -> list[str]:
"""Every line the KWin script `name` has reported so far ([`Kde.kwin_script`][])."""
+29 -8
View File
@@ -2,6 +2,7 @@
neutral vocabulary."""
import json
import re
import shlex
from typing import Any
@@ -21,6 +22,9 @@ PARK = "komorebi-park"
# the file the daemon is started with, and where a program with a name of its own is made
CONFIG = "/tmp/e2e-restart-config.json"
BIN = "/tmp/e2e-bin"
# what a program name may be made of: the same on every platform, so that a scenario cannot pass
# one that another port rejects
PROGRAM = re.compile(r"[A-Za-z0-9_-]+")
class KdePlatform:
@@ -91,7 +95,9 @@ class KdePlatform:
def spawn(self, title: str, app_id: str | None = None, exe: str | None = None) -> Client:
name = f"-a {shlex.quote(app_id)} " if app_id else ""
program = "foot"
if exe:
if exe is not None:
if not PROGRAM.fullmatch(exe):
raise ValueError(f"not a program name: {exe!r}")
# the daemon reads the executable from /proc, where a link shows its target: a copy
# of the terminal is what has the name, made once: a copy that is running cannot be
# written over
@@ -100,9 +106,18 @@ class KdePlatform:
f"mkdir -p {BIN} && {{ test -x {program} || cp -L $(command -v foot) {program}; }}"
)
self.kde.spawn(f"{program} {name}-T {shlex.quote(title)} sleep 3000")
self.kde.wait_for(lambda: self.kde.wid(title) != "", timeout=30)
if not self.kde.wait_for(lambda: self.kde.wid(title) != "", timeout=30):
raise AssertionError(f"no window titled {title!r} appeared")
return Client(title)
def _wid(self, client: Client) -> str:
"""The id of the window of `client`, which has to exist: a command for a window that is
not there fails, as it does on every platform."""
wid = self.kde.wid(client.title)
if wid == "":
raise AssertionError(f"no window titled {client.title!r}")
return wid
def exe_id(self, program: str) -> str:
return program
@@ -131,8 +146,14 @@ class KdePlatform:
return desk != 0 and desk != self.kde.shown()
def displays(self) -> list[Rect]:
"""The enabled outputs, which this session gives the size it was started with, side by side
from the left (at the scale of 1 that a scenario leaves them at)."""
"""The enabled outputs, as KWin has them, left to right.
Where KWin does not say, they are the size the session was started with, side by side
from the left (at the scale of 1 that a scenario leaves them at).
"""
screens = self.kde.screens()
if screens:
return [display for display, _ in screens]
width, height = self.size
return [Rect(i * width, 0, width, height) for i in range(len(self.kde.outputs.names()))]
@@ -153,7 +174,7 @@ class KdePlatform:
self.kde.wait_for(lambda: len(self.kde.outputs.names()) == len(names) - 1, timeout=20)
def close(self, client: Client) -> None:
self.kde.close(self.kde.wid(client.title))
self.kde.close(self._wid(client))
def _session_id(self) -> str:
"""The id of the user's Wayland session, which is the one that gets locked."""
@@ -180,7 +201,7 @@ class KdePlatform:
raise AssertionError("the screen did not unlock")
def move_window(self, client: Client, x: int, y: int) -> None:
self.kde.sh(f"kdotool windowmove {self.kde.wid(client.title)} {x} {y}")
self.kde.sh(f"kdotool windowmove {self._wid(client)} {x} {y}")
def work_area(self) -> Rect:
"""What KWin says windows may take of the first output, which is the output less the
@@ -193,10 +214,10 @@ class KdePlatform:
return area if area is not None else Rect(0, 0, *self.size)
def minimize(self, client: Client) -> None:
self.kde.minimize(self.kde.wid(client.title))
self.kde.minimize(self._wid(client))
def activate(self, client: Client) -> None:
self.kde.activate(self.kde.wid(client.title))
self.kde.activate(self._wid(client))
def screenshot(self, name: str) -> Image.Image:
return self.kde.shot(name)
+9
View File
@@ -824,3 +824,12 @@ def test_shortcut_actions_are_the_action_names_of_the_component(machine: FakeMac
machine.replies.clear()
machine.reply("allActionsForComponent", status=1)
assert Kde(machine, "main").shortcut_actions() == []
def test_wid_takes_a_title_as_it_is_and_not_as_a_pattern(machine: FakeMachine) -> None:
machine.reply("kdotool search", output="{one}\n")
Kde(machine, "main").wid("a (b) [c].d+")
command = inner(machine.commands[0])
assert r"'^a \(b\) \[c\]\.d\+$'" in command
+74 -5
View File
@@ -6,6 +6,7 @@ import pytest
import komorebi_vm.kde as kde_module
from komorebi_vm import Kde, Rect
from komorebi_vm.core.platform import Client
from komorebi_vm.kde_platform import KdePlatform
from .conftest import FakeMachine
@@ -13,24 +14,24 @@ from .conftest import FakeMachine
@pytest.fixture(autouse=True)
def probes(monkeypatch: pytest.MonkeyPatch) -> None:
"""The first probe a test makes is `work-area-1`."""
"""The first probe a test makes is `screens-1`."""
monkeypatch.setattr(kde_module, "_PROBES", count(1))
def kde_with_area(machine: FakeMachine, area: str) -> KdePlatform:
machine.reply("loadScript", output="i 7\n")
machine.reply("journalctl", output=f"{area}KS:work-area-1 done\n")
machine.reply("journalctl", output=f"{area}KS:screens-1 done\n")
return KdePlatform(Kde(machine, "main", scale=0.01), (1920, 1080))
def test_the_work_area_is_what_kwin_says_and_not_the_whole_output(machine: FakeMachine) -> None:
platform = kde_with_area(machine, "KS:work-area-1 area 0 0 1920 1040\n")
platform = kde_with_area(machine, "KS:screens-1 screen 0 0 1920 1080 0 0 1920 1040\n")
assert platform.work_area() == Rect(0, 0, 1920, 1040)
def test_the_work_area_is_asked_of_the_first_output_less_its_panels(machine: FakeMachine) -> None:
platform = kde_with_area(machine, "KS:work-area-1 area 0 0 1920 1040\n")
platform = kde_with_area(machine, "KS:screens-1 screen 0 0 1920 1080 0 0 1920 1040\n")
platform.work_area()
@@ -49,6 +50,74 @@ def test_the_work_area_is_the_whole_output_where_kwin_does_not_answer(
def test_the_work_area_is_the_whole_output_where_kwin_says_nonsense(machine: FakeMachine) -> None:
platform = kde_with_area(machine, "KS:work-area-1 area 0 0 many 1040\n")
platform = kde_with_area(machine, "KS:screens-1 screen 0 0 1920 1080 0 0 many 1040\n")
assert platform.work_area() == Rect(0, 0, 1920, 1080)
def test_a_window_that_never_appears_fails_the_spawn(machine: FakeMachine) -> None:
"""A scenario that waits for a window to stay unmanaged would pass for one that is not there."""
platform = KdePlatform(Kde(machine, "main", scale=0.01), (1920, 1080))
with pytest.raises(AssertionError, match="no window titled 'ghost'"):
platform.spawn("ghost")
def test_a_window_that_appears_is_a_client(machine: FakeMachine) -> None:
machine.reply("kdotool search", output="{abc}\n")
platform = KdePlatform(Kde(machine, "main", scale=0.01), (1920, 1080))
assert platform.spawn("here").title == "here"
@pytest.mark.parametrize("name", ["a b", "x;y", "../x", "", "e2e.exe"])
def test_a_program_name_a_port_would_reject_is_rejected(machine: FakeMachine, name: str) -> None:
platform = KdePlatform(Kde(machine, "main", scale=0.01), (1920, 1080))
with pytest.raises(ValueError, match="not a program name"):
platform.spawn("w", exe=name)
@pytest.mark.parametrize("act", ["close", "minimize", "activate", "move"])
def test_a_command_for_a_window_that_is_not_there_fails(machine: FakeMachine, act: str) -> None:
platform = KdePlatform(Kde(machine, "main", scale=0.01), (1920, 1080))
client = Client("gone")
with pytest.raises(AssertionError, match="no window titled 'gone'"):
if act == "move":
platform.move_window(client, 1, 2)
else:
getattr(platform, act)(client)
assert not any("kdotool window" in c for c in machine.commands)
def test_the_displays_are_what_kwin_says_and_not_the_size_they_were_started_with(
machine: FakeMachine,
) -> None:
platform = kde_with_area(
machine,
"KS:screens-1 screen 1920 0 1280 800 1920 0 1280 800\n"
"KS:screens-1 screen 0 0 1920 1080 0 0 1920 1040\n",
)
assert platform.displays() == [Rect(0, 0, 1920, 1080), Rect(1920, 0, 1280, 800)]
def test_the_work_area_is_that_of_the_leftmost_output(machine: FakeMachine) -> None:
platform = kde_with_area(
machine,
"KS:screens-1 screen 1920 0 1280 800 1920 0 1280 800\n"
"KS:screens-1 screen 0 0 1920 1080 0 0 1920 1040\n",
)
assert platform.work_area() == Rect(0, 0, 1920, 1040)
def test_the_displays_are_side_by_side_at_the_size_given_where_kwin_does_not_say(
machine: FakeMachine,
) -> None:
machine.reply("loadScript", output="i 7\n")
machine.reply("kscreen-doctor -j", output="Virtual-0\nVirtual-1\n")
platform = KdePlatform(Kde(machine, "main", scale=0.01), (1920, 1080))
assert platform.displays() == [Rect(0, 0, 1920, 1080), Rect(1920, 0, 1920, 1080)]