feat(wm): a monitor changes size

When an output gets another resolution or scale, or a panel starts, grows or
hides, the work area the layout fills is not the one komorebi tiled in, and
nothing moved the windows until something else tiled them again.

The bridge now sends the outputs, with their geometry and the work area of the
desktop each shows, when KWin says they changed, when a dock window opens,
closes or moves, and once a second, because KWin has no signal for the room a
panel leaves. The table turns a monitor whose size or work area changed into a
monitor notification. It is not a window event, since it is about no window: it
goes to the monitor reconciliator, a thread that takes the window manager's lock
as the threads of events and messages do, reads the size and work area of every
monitor again and tiles the workspace in front of the focused monitor. Another
monitor's windows keep their tiles until a retile. Every subscriber is notified
of it, whether or not the state changed.

vm-hotplug starts with the scale of one of two outputs changing under a running
daemon. The VM library gets kde.outputs, which lists, disables, enables and
scales outputs, for the commits that unplug and plug them.
This commit is contained in:
LGUG2Z committed 2026-10-28 07:20:57 -07:00
1 parent c03e5d2970
commit c8dc92a236
27 files changed
+1044 -75

No files matched your search

+15 -2
View File
@@ -6,6 +6,8 @@ A suite imports what it needs from here:
* [`Kde`](komorebi_vm.kde.Kde) is a KWin session inside a test machine, with
the tools to look at it (`kdotool`, `busctl`, `kscreen-doctor`, screenshots)
and the komorebi daemon that runs in it.
* [`Outputs`](komorebi_vm.kde.Outputs) are the session's outputs, which a suite
disables, enables and scales to change the monitors under the daemon.
* [`daemon`](komorebi_vm.daemon) reads what the daemon logs about the events it
handles and the frames it asks for.
* [`pixels`](komorebi_vm.pixels) reads a screenshot: the color of a pixel, and
@@ -22,8 +24,19 @@ against a fake machine (the `vm-lib` check does).
from komorebi_vm import daemon, latency, pixels, uinput
from komorebi_vm.checks import Checks
from komorebi_vm.kde import Kde, Rect
from komorebi_vm.kde import Kde, Outputs, Rect
from komorebi_vm.machine import Machine
from komorebi_vm.pointer import Pointer
__all__ = ["Checks", "Kde", "Machine", "Pointer", "Rect", "daemon", "latency", "pixels", "uinput"]
__all__ = [
"Checks",
"Kde",
"Machine",
"Outputs",
"Pointer",
"Rect",
"daemon",
"latency",
"pixels",
"uinput",
]
+63 -6
View File
@@ -31,6 +31,57 @@ class Rect:
and other.y < self.y + self.h
)
def inside(self, area: "Rect", slack: int = 0) -> bool:
"""Returns true if and only if every pixel of this rectangle is a pixel of `area`, give
or take `slack` pixels at each edge."""
return (
self.x >= area.x - slack
and self.y >= area.y - slack
and self.x + self.w <= area.x + area.w + slack
and self.y + self.h <= area.y + area.h + slack
)
class Outputs:
"""The outputs of a KWin session, as `kscreen-doctor` lists and changes them.
A [`Kde`][] has one, as [`Kde.outputs`][]. Calling it gives the number of outputs KWin has
enabled. An output is named as KWin names it (`Virtual-0`), and a disabled output keeps its
name, so that it can be enabled again.
"""
def __init__(self, kde: "Kde") -> None:
self._kde = kde
def __call__(self) -> int:
"""The number of outputs KWin has enabled."""
return int(
self._kde.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'")
)
def names(self, *, enabled: bool = True) -> list[str]:
"""The names of the outputs that are enabled (or, with `enabled` false, disabled), from
left to right."""
listed = self._kde.sh(
f"kscreen-doctor -j | jq -r '[.outputs[] | select(.enabled == {str(enabled).lower()})]"
" | sort_by(.pos.x) | .[].name'"
)
return listed.split()
def disable(self, name: str) -> None:
"""Unplugs an output, as far as KWin can tell: it is disabled, and its windows go to the
outputs that are left."""
self._kde.sh(f"kscreen-doctor output.{name}.disable")
def enable(self, name: str) -> None:
"""Plugs an output back in, as far as KWin can tell."""
self._kde.sh(f"kscreen-doctor output.{name}.enable")
def scale(self, name: str, factor: float) -> None:
"""Gives an output another scale: its size in pixels, as the windows see it, becomes
its mode divided by `factor`."""
self._kde.sh(f"kscreen-doctor output.{name}.scale.{factor:g}")
class Kde:
"""One KWin session of the test user, with its own session bus and Wayland socket.
@@ -455,7 +506,11 @@ class Kde:
return self.run(f"kdotool search --class {pattern} | head -1")[1].strip()
def rect(self, wid: str) -> Rect:
"""The position and size KWin reports for the window."""
"""The position and size KWin reports for the window, rounded to whole pixels.
At a fractional scale the frame is not a whole number of pixels in the logical
coordinates KWin reports.
"""
out = self.sh(f"kdotool getwindowgeometry {shlex.quote(wid)}")
position = size = None
for line in out.splitlines():
@@ -466,8 +521,8 @@ class Kde:
size = words[1]
if position is None or size is None:
raise AssertionError(f"no geometry in {out!r}")
x, y = (int(v) for v in position.split(","))
w, h = (int(v) for v in size.split("x"))
x, y = (round(float(v)) for v in position.split(","))
w, h = (round(float(v)) for v in size.split("x"))
return Rect(x, y, w, h)
def title(self, wid: str) -> str:
@@ -625,9 +680,11 @@ class Kde:
mark = f"KS:{name} "
return [line.split(mark, 1)[1] for line in log.splitlines() if mark in line]
def outputs(self) -> int:
"""The number of outputs KWin has enabled."""
return int(self.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'"))
@property
def outputs(self) -> Outputs:
"""The session's outputs: `kde.outputs()` is how many are enabled, and `kde.outputs` has
the ones to enable, disable and scale ([`Outputs`][])."""
return Outputs(self)
def _effects(self, method: str, name: str) -> bool:
"""Asks KWin's `/Effects` object a yes or no question about the effect `name`."""
+60 -1
View File
@@ -3,7 +3,7 @@ import shlex
import pytest
from komorebi_vm import Kde, Rect
from komorebi_vm import Kde, Outputs, Rect
from .conftest import FakeMachine
@@ -75,6 +75,15 @@ def test_rect_parses_what_kdotool_prints(machine: FakeMachine) -> None:
assert Kde(machine, "main").rect("{abc}") == Rect(10, 20, 300, 400)
def test_rect_rounds_what_a_fractional_scale_makes_of_a_frame(machine: FakeMachine) -> None:
machine.reply(
"getwindowgeometry",
output="Window {abc}\n Position: 0.4,10.5\n Geometry: 695.3333333333334x400.6\n",
)
assert Kde(machine, "main").rect("{abc}") == Rect(0, 10, 695, 401)
def test_rect_fails_on_output_it_does_not_understand(machine: FakeMachine) -> None:
machine.reply("getwindowgeometry", output="nothing useful")
@@ -716,3 +725,53 @@ def test_a_kwin_script_that_never_reports_it_is_done_fails_the_test(machine: Fak
with pytest.raises(AssertionError, match="never reported"):
kde.kwin_script("silent", "")
def test_a_rect_is_inside_an_area_that_has_every_one_of_its_pixels() -> None:
area = Rect(0, 0, 1920, 1080)
assert Rect(0, 0, 1920, 1080).inside(area)
assert Rect(100, 50, 800, 600).inside(area)
assert not Rect(-1, 0, 100, 100).inside(area)
assert not Rect(1900, 0, 100, 100).inside(area)
assert not Rect(0, 1000, 100, 100).inside(area)
assert Rect(1920, 0, 800, 600).inside(Rect(1920, 0, 1920, 1080))
assert Rect(-1, 0, 1921, 1080).inside(area, slack=1)
assert not Rect(-2, 0, 100, 100).inside(area, slack=1)
def test_outputs_count_the_enabled_ones_when_called(machine: FakeMachine) -> None:
machine.reply("length", output="2\n")
assert Kde(machine, "main").outputs() == 2
assert isinstance(Kde(machine, "main").outputs, Outputs)
def test_outputs_are_named_left_to_right_and_a_disabled_one_keeps_its_name(
machine: FakeMachine,
) -> None:
machine.reply("select(.enabled == true)", output="Virtual-0\nVirtual-1\n")
machine.reply("select(.enabled == false)", output="Virtual-1\n")
outputs = Kde(machine, "main").outputs
assert outputs.names() == ["Virtual-0", "Virtual-1"]
assert outputs.names(enabled=False) == ["Virtual-1"]
assert all("sort_by(.pos.x)" in inner(command) for command in machine.commands)
def test_an_output_is_disabled_enabled_and_scaled_with_kscreen_doctor(
machine: FakeMachine,
) -> None:
outputs = Kde(machine, "main").outputs
outputs.disable("Virtual-1")
outputs.enable("Virtual-1")
outputs.scale("Virtual-0", 1.5)
outputs.scale("Virtual-0", 1)
assert [inner(command) for command in machine.commands] == [
"kscreen-doctor output.Virtual-1.disable",
"kscreen-doctor output.Virtual-1.enable",
"kscreen-doctor output.Virtual-0.scale.1.5",
"kscreen-doctor output.Virtual-0.scale.1",
]
+5
View File
@@ -0,0 +1,5 @@
{
tier = "fast";
kind = "headless";
timeoutMinutes = 15;
}
+98
View File
@@ -0,0 +1,98 @@
# Monitors that change, against a real headless KWin with two outputs. What only a real KWin can
# tell: that `kscreen-doctor` changing the scale of an output reaches komorebi as a change of that
# monitor's size, that the windows on it are tiled again in the size it has now, and that they
# fill it again when it has its size back. `komorebi/tests/monitor_resize.rs` checks the same
# against the fake.
from komorebi_vm import Checks, Kde, Rect
W, H = 1920, 1080
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), outputs=2, scale=SCALE)
TITLES = ["w1", "w2", "w3"]
def monitor(idx: int) -> Rect:
"""The bounds komorebi has for a monitor."""
size = kde.state()["monitors"]["elements"][idx]["size"]
return Rect(size["left"], size["top"], size["right"], size["bottom"])
def tiled_in(area: Rect) -> bool:
"""Every one of the three windows is inside `area`, and none is on another.
A pixel is allowed at each edge: at a fractional scale KWin reports frames that are not
whole pixels.
"""
rects = [kde.rect(kde.wid(title)) for title in TITLES]
return all(r.inside(area, slack=1) for r in rects) and not any(
a.overlaps(b) for i, a in enumerate(rects) for b in rects[i + 1 :]
)
def resizes_handled() -> int:
"""How many times the daemon has read the sizes of its monitors again."""
return kde.komorebi_log().count("updated monitor size and work area")
print("== 1. two outputs, and three windows on the left one")
left, right = kde.outputs.names()
print(f" outputs: {left} (left), {right} (right)")
kde.start_komorebi()
checks.check(
"the daemon answers komorebic, with both monitors",
kde.wait_for(
lambda: kde.run("komorebic state")[0] == 0
and len(kde.state()["monitors"]["elements"]) == 2,
timeout=30,
),
)
for title in TITLES:
kde.spawn(f"foot -T {title} sleep 3000")
kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30)
checks.check(
"komorebi has the three windows on the left monitor",
kde.wait_for(lambda: kde.managed(0) == 3),
)
checks.check("the left monitor has the size of its output", monitor(0) == Rect(0, 0, W, H))
checks.check("the windows are tiled inside it", kde.wait_for(lambda: tiled_in(monitor(0))))
print("== 2. the scale of the left output changes")
before = resizes_handled()
kde.outputs.scale(left, 1.5)
smaller = Rect(0, 0, W * 2 // 3, H * 2 // 3)
checks.check(
f"komorebi has the new size of the monitor, {smaller}",
kde.wait_for(lambda: monitor(0) == smaller, timeout=20),
)
checks.check("it read the sizes again for it", resizes_handled() > before)
checks.check(
"the windows are tiled again inside the monitor as it is now",
kde.wait_for(lambda: tiled_in(smaller)),
)
print("== 3. and back")
kde.outputs.scale(left, 1)
checks.check(
"the monitor has its size back",
kde.wait_for(lambda: monitor(0) == Rect(0, 0, W, H), timeout=20),
)
checks.check(
"the windows fill it again, side by side",
kde.wait_for(lambda: tiled_in(Rect(0, 0, W, H)) and kde.rect(kde.wid("w1")).w < W - 100),
)
print("== 4. nothing is left behind")
checks.check(
"komorebi is running and answers",
kde.komorebi_running() and kde.run("komorebic state")[0] == 0,
)
kde.stop_komorebi()
checks.check("komorebi stopped", not kde.komorebi_running())
checks.finish()