pointer: the lease, and a driver process that only executes

There is one cursor on this compositor build and every virtual pointer
writes to it, so aiming at a session is a matter of serialising input, not
of binding harder. Two pieces, and the split between them is the point.

`hhstreamd/pointer.py` is the lease: one holder, an idle TTL and a hard cap
on an injected clock, tracked buttons, and the window-local-to-normalised
arithmetic that makes "click 40px into this window" mean something on an
output that is not at the layout origin. Pure, so the expiry tests move
time instead of sleeping.

`hhstream_pointer/` is the driver: its own process because a Wayland client
needs its own connection and a blocked one must not stall the broker. It
holds no lease state -- it is told what to do and does it. The manager is
bound at version 2 and pointers are created with
`create_virtual_pointer_with_output`; a version-1-only manager is reported
and refused rather than quietly aiming at the global layout.

The wlr protocol module is vendored scanner output under `_protocol/`, so a
checkout builds without a code generator; `_protocol/regenerate.py` says how
to refresh it and why pywayland's own scanner entry point cannot be used.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011txKimbdkqPFpq6m8KDELu
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-02 00:15:50 +00:00
1 parent 98374b8457
commit 0d414d76bc
21 files changed
+2417 -2

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
"""Fixtures for the pointer tests. Nothing here sleeps and nothing connects.
``src`` goes on the path because these tests run straight out of a checkout
(``nix develop -c python -m pytest tests/pointer -q``) rather than against an
installed package.
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src"))
from hhstreamd.pointer import PointerLease # noqa: E402
class FakeClock:
"""The injected clock. Tests move time; time never moves on its own."""
def __init__(self, now: float = 1000.0) -> None:
self.now = float(now)
def __call__(self) -> float:
return self.now
def advance(self, seconds: float) -> None:
self.now += float(seconds)
@pytest.fixture
def clock() -> FakeClock:
return FakeClock()
@pytest.fixture
def lease(clock: FakeClock) -> PointerLease:
"""Short deadlines so the arithmetic in a failing test is readable."""
return PointerLease(ttl_s=30.0, max_s=300.0, clock=clock)
+245
View File
@@ -0,0 +1,245 @@
"""The lease state machine (CONTRACT-sessions.md §3.3).
There is one cursor on this compositor and every virtual pointer writes to it,
so the lease is the only thing standing between two agents and a mouse that
jumps between their windows. These tests are therefore about refusal as much as
about success: who is turned away, and with what name attached.
"""
from __future__ import annotations
import pytest
from hhstreamd.pointer import Bookmark, LeaseBusy, LeaseInvalid, PointerLease
def test_unheld_lease_reports_nothing_held(lease):
assert lease.state() == {
"holder": None,
"since": None,
"lease_id": None,
"expires_at": None,
}
assert lease.pressed() == []
assert lease.expire() is None
def test_acquire_then_release_is_a_full_cycle(lease, clock):
lease_id = lease.acquire("alpha")
assert lease.state() == {
"holder": "alpha",
"since": 1000.0,
"lease_id": lease_id,
"expires_at": 1030.0,
}
outcome = lease.release("alpha", lease_id, "done")
assert outcome.reason == "done"
assert outcome.bookmark is None
assert outcome.buttons_lifted == []
assert lease.state()["holder"] is None
# And the pointer is free again, to a different session.
assert lease.acquire("beta") != lease_id
def test_second_holder_is_rejected_by_name(lease):
lease.acquire("alpha")
with pytest.raises(LeaseBusy) as caught:
lease.acquire("beta")
assert caught.value.holder == "alpha"
assert "alpha" in str(caught.value)
def test_reacquiring_as_the_same_session_is_also_busy(lease):
"""A second lease_id for one session would invalidate the first mid-drag."""
lease.acquire("alpha")
with pytest.raises(LeaseBusy) as caught:
lease.acquire("alpha")
assert caught.value.holder == "alpha"
def test_a_verb_from_a_non_holder_is_invalid(lease):
lease_id = lease.acquire("alpha")
with pytest.raises(LeaseInvalid, match="held by alpha"):
lease.refresh("beta", lease_id)
with pytest.raises(LeaseInvalid, match="held by alpha"):
lease.release("beta", lease_id, "theft")
with pytest.raises(LeaseInvalid, match="held by alpha"):
lease.press("beta", "left")
with pytest.raises(LeaseInvalid, match="held by alpha"):
lease.unpress("beta", "left")
def test_a_verb_on_an_unheld_lease_is_invalid(lease):
with pytest.raises(LeaseInvalid, match="no pointer lease"):
lease.refresh("alpha", "whatever")
with pytest.raises(LeaseInvalid, match="no pointer lease"):
lease.press("alpha", "left")
def test_a_stale_lease_id_is_rejected(lease, clock):
"""The session is right and the id is not: the classic retry-after-expiry."""
first = lease.acquire("alpha")
lease.release("alpha", first, "done")
second = lease.acquire("alpha")
assert second != first
with pytest.raises(LeaseInvalid, match="stale lease_id"):
lease.refresh("alpha", first)
with pytest.raises(LeaseInvalid, match="stale lease_id"):
lease.release("alpha", first, "late")
with pytest.raises(LeaseInvalid, match="stale lease_id"):
lease.mark("alpha", first, Bookmark(0.5, 0.5, "hh-a", "2026-10-01T00:00:00Z"))
# The real holder is untouched by the stale caller's attempts.
lease.refresh("alpha", second)
def test_refresh_pushes_the_idle_deadline_but_not_the_hard_cap(lease, clock):
lease_id = lease.acquire("alpha")
clock.advance(20.0)
lease.refresh("alpha", lease_id)
assert lease.state()["expires_at"] == 1050.0
assert lease.expire() is None
# Keep refreshing inside the idle window, right up to the hard cap.
while clock.now < 1299.0:
clock.advance(min(20.0, 1299.0 - clock.now))
lease.refresh("alpha", lease_id)
assert lease.expire() is None
assert lease.state()["expires_at"] == 1329.0
clock.advance(1.0) # t = 1300, the hard deadline, which did not move
info = lease.expire()
assert info is not None
assert info.hard_deadline == 1300.0
def test_ttl_expiry_releases_the_lease(lease, clock):
lease_id = lease.acquire("alpha")
clock.advance(29.9)
assert lease.expire() is None
clock.advance(0.1) # exactly at the deadline, which is inclusive
info = lease.expire()
assert info is not None
assert info.session_id == "alpha"
assert info.lease_id == lease_id
assert info.acquired_at == 1000.0
assert info.expires_at == 1030.0
assert info.hard_deadline == 1300.0
assert lease.state()["holder"] is None
assert lease.expire() is None # idempotent: nothing left to reap
def test_hard_cap_expiry_beats_an_endless_refresh_loop(clock):
lease = PointerLease(ttl_s=30.0, max_s=100.0, clock=clock)
lease_id = lease.acquire("alpha")
for _ in range(9):
clock.advance(10.0)
lease.refresh("alpha", lease_id)
assert lease.expire() is None, "the idle clock keeps being pushed out"
clock.advance(10.0) # t = 1100, the hard deadline
info = lease.expire()
assert info is not None
assert info.hard_deadline == 1100.0
# The idle deadline was still in the future; the cap is what fired.
assert info.expires_at > info.hard_deadline
def test_an_expired_lease_cannot_be_refreshed_back_to_life(lease, clock):
lease_id = lease.acquire("alpha")
clock.advance(31.0)
with pytest.raises(LeaseInvalid, match="expired"):
lease.refresh("alpha", lease_id)
# Still held, because only expire() releases: the broker has to be told so
# it can lift buttons on the driver.
assert lease.state()["holder"] == "alpha"
assert lease.expire() is not None
def test_expire_does_nothing_when_nothing_is_due(lease, clock):
lease.acquire("alpha")
clock.advance(29.0)
assert lease.expire() is None
assert lease.state()["holder"] == "alpha"
def test_press_and_lift_one_button(lease):
lease_id = lease.acquire("alpha")
lease.press("alpha", "left")
assert lease.pressed() == ["left"]
assert lease.unpress("alpha", "left") == ["left"]
assert lease.pressed() == []
assert lease.release("alpha", lease_id, "done").buttons_lifted == []
def test_lifting_a_button_that_is_not_down_reports_nothing(lease):
lease.acquire("alpha")
assert lease.unpress("alpha", "left") == []
lease.press("alpha", "left")
lease.unpress("alpha", "left")
assert lease.unpress("alpha", "left") == []
def test_multiple_buttons_are_tracked_and_lifted_independently(lease):
lease_id = lease.acquire("alpha")
lease.press("alpha", "left")
lease.press("alpha", "right")
lease.press("alpha", "middle")
assert lease.pressed() == ["left", "right", "middle"]
assert lease.unpress("alpha", "right") == ["right"]
assert lease.pressed() == ["left", "middle"]
# A release lifts whatever is still down, oldest first.
outcome = lease.release("alpha", lease_id, "timeout")
assert outcome.buttons_lifted == ["left", "middle"]
assert outcome.reason == "timeout"
assert lease.pressed() == []
def test_pressing_twice_leaves_one_button_down(lease):
lease.acquire("alpha")
lease.press("alpha", "left")
lease.press("alpha", "left")
assert lease.pressed() == ["left"]
assert lease.unpress("alpha", "left") == ["left"]
assert lease.pressed() == []
def test_expiry_does_not_leak_buttons_to_the_next_holder(lease, clock):
lease.acquire("alpha")
lease.press("alpha", "left")
clock.advance(31.0)
assert lease.expire() is not None
assert lease.pressed() == []
lease.acquire("beta")
assert lease.pressed() == []
def test_bookmark_survives_to_the_release_outcome(lease):
lease_id = lease.acquire("alpha")
mark = Bookmark(x=0.25, y=0.75, output="hh-alpha", at="2026-10-01T12:00:00Z")
lease.mark("alpha", lease_id, mark)
assert lease.release("alpha", lease_id, "done").bookmark == mark
def test_a_new_lease_starts_without_the_previous_bookmark(lease):
first = lease.acquire("alpha")
lease.mark("alpha", first, Bookmark(0.25, 0.75, "hh-alpha", "2026-10-01T12:00:00Z"))
lease.release("alpha", first, "done")
second = lease.acquire("beta")
assert lease.release("beta", second, "done").bookmark is None
def test_defaults_match_the_contract():
lease = PointerLease()
assert (lease.ttl_s, lease.max_s) == (30.0, 300.0)
+244
View File
@@ -0,0 +1,244 @@
"""The driver's protocol (CONTRACT-sessions.md §3.4).
The dispatcher is tested against a recording sink rather than a compositor, so
these assertions are about the exact events that would go on the wire: which
pointer they go to, in what order, and which requests are refused instead.
The driver is an executor. It is *not* tested for serialisation, authority, or
any notion of who may ask — none of that is here, on purpose. The lease is in
``hhstreamd.pointer`` and the broker owns it.
"""
from __future__ import annotations
import pytest
from hhstream_pointer import buttons
from hhstream_pointer.ops import Dispatcher
LEFT = buttons.CODES["left"]
RIGHT = buttons.CODES["right"]
DOWN = buttons.STATES["down"]
UP = buttons.STATES["up"]
class RecordingSink:
"""Every call, in order, as a tuple. Nothing else."""
def __init__(self) -> None:
self.calls: list[tuple] = []
def motion_absolute(self, output, x, y):
self.calls.append(("motion", output, x, y))
def button(self, output, code, state):
self.calls.append(("button", output, code, state))
def frame(self, output):
self.calls.append(("frame", output))
class FailingSink(RecordingSink):
"""A sink whose motion raises, standing in for an output that vanished."""
class Boom(Exception):
pass
def motion_absolute(self, output, x, y):
raise FailingSink.Boom(output)
@pytest.fixture
def sink() -> RecordingSink:
return RecordingSink()
@pytest.fixture
def driver(sink) -> Dispatcher:
return Dispatcher(sink)
def warp(driver, output="hh-alpha", x=0.5, y=0.5):
return driver.handle({"op": "warp", "output": output, "x": x, "y": y})
# -- happy paths ------------------------------------------------------------
def test_warp_sends_one_motion_and_no_implicit_frame(driver, sink):
assert warp(driver, x=0.42, y=0.61) == {"ok": True}
assert sink.calls == [("motion", "hh-alpha", 0.42, 0.61)]
def test_frame_is_a_separate_op(driver, sink):
warp(driver)
assert driver.handle({"op": "frame"}) == {"ok": True}
assert sink.calls[-1] == ("frame", "hh-alpha")
def test_a_click_is_warp_button_frame(driver, sink):
warp(driver, x=0.25, y=0.75)
driver.handle({"op": "button", "button": "left", "state": "down"})
driver.handle({"op": "button", "button": "left", "state": "up"})
driver.handle({"op": "frame"})
assert sink.calls == [
("motion", "hh-alpha", 0.25, 0.75),
("button", "hh-alpha", LEFT, DOWN),
("button", "hh-alpha", LEFT, UP),
("frame", "hh-alpha"),
]
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []}
def test_the_boundary_coordinates_are_accepted(driver, sink):
assert warp(driver, x=0.0, y=0.0) == {"ok": True}
assert warp(driver, x=1.0, y=1.0) == {"ok": True}
# Integers are numbers too; 0 and 1 are the corners.
assert warp(driver, x=0, y=1) == {"ok": True}
assert [c[2:] for c in sink.calls] == [(0.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
def test_buttons_follow_the_last_warp_not_the_first(driver, sink):
warp(driver, output="hh-alpha")
warp(driver, output="hh-beta")
driver.handle({"op": "button", "button": "left", "state": "down"})
assert sink.calls[-1] == ("button", "hh-beta", LEFT, DOWN)
# -- pressed / release_all --------------------------------------------------
def test_pressed_reports_what_is_down_oldest_first(driver):
warp(driver)
driver.handle({"op": "button", "button": "right", "state": "down"})
driver.handle({"op": "button", "button": "left", "state": "down"})
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": ["right", "left"]}
def test_release_all_lifts_everything_and_frames_once(driver, sink):
warp(driver)
driver.handle({"op": "button", "button": "left", "state": "down"})
driver.handle({"op": "button", "button": "right", "state": "down"})
sink.calls.clear()
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]}
assert sink.calls == [
("button", "hh-alpha", LEFT, UP),
("button", "hh-alpha", RIGHT, UP),
("frame", "hh-alpha"),
]
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []}
def test_release_all_on_a_quiet_driver_lifts_nothing(driver, sink):
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []}
assert sink.calls == []
def test_release_all_lifts_through_the_pointer_the_press_went_to(driver, sink):
"""The expiry path: the broker lifts after the cursor has moved on.
A button pressed on one output must come up on that output's pointer, not
on whatever is aimed now, or the first session keeps a stuck drag.
"""
warp(driver, output="hh-alpha")
driver.handle({"op": "button", "button": "left", "state": "down"})
warp(driver, output="hh-beta")
driver.handle({"op": "button", "button": "right", "state": "down"})
sink.calls.clear()
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]}
assert sink.calls == [
("button", "hh-alpha", LEFT, UP),
("button", "hh-beta", RIGHT, UP),
("frame", "hh-alpha"),
("frame", "hh-beta"),
]
def test_a_lifted_button_is_forgotten(driver):
warp(driver)
driver.handle({"op": "button", "button": "left", "state": "down"})
driver.handle({"op": "button", "button": "left", "state": "up"})
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []}
def test_every_known_button_name_round_trips(driver, sink):
warp(driver)
for name in buttons.NAMES:
assert driver.handle({"op": "button", "button": name, "state": "down"}) == {"ok": True}
assert driver.handle({"op": "pressed"})["buttons"] == list(buttons.NAMES)
assert driver.handle({"op": "release_all"})["lifted"] == list(buttons.NAMES)
# -- refusals ---------------------------------------------------------------
def test_button_before_any_warp_is_refused(driver, sink):
assert driver.handle({"op": "button", "button": "left", "state": "down"}) == {
"ok": False,
"error": "no output is aimed; warp before button or frame",
}
assert sink.calls == []
def test_frame_before_any_warp_is_refused(driver, sink):
assert driver.handle({"op": "frame"})["ok"] is False
assert sink.calls == []
def test_a_failed_warp_does_not_change_the_aim():
"""Otherwise the next button lands on a session we never reached."""
driver = Dispatcher(RecordingSink())
warp(driver, output="hh-alpha")
driver._sink = FailingSink()
with pytest.raises(FailingSink.Boom):
warp(driver, output="hh-beta")
driver._sink = sink = RecordingSink()
driver.handle({"op": "button", "button": "left", "state": "down"})
assert sink.calls == [("button", "hh-alpha", LEFT, DOWN)]
@pytest.mark.parametrize(
"request_, fragment",
[
({}, "no 'op'"),
({"op": 7}, "no 'op'"),
({"op": "nonsense"}, "unknown op 'nonsense'"),
({"op": "warp", "x": 0.5, "y": 0.5}, "'output' must be"),
({"op": "warp", "output": "", "x": 0.5, "y": 0.5}, "'output' must be"),
({"op": "warp", "output": "hh-a", "y": 0.5}, "'x' must be a number"),
({"op": "warp", "output": "hh-a", "x": "0.5", "y": 0.5}, "'x' must be a number"),
({"op": "warp", "output": "hh-a", "x": True, "y": 0.5}, "'x' must be a number"),
({"op": "warp", "output": "hh-a", "x": 1.5, "y": 0.5}, "outside 0..1"),
({"op": "warp", "output": "hh-a", "x": 0.5, "y": -0.1}, "outside 0..1"),
({"op": "button", "state": "down"}, "'button' must be a string"),
({"op": "button", "button": "left"}, "'state' must be"),
({"op": "button", "button": "pinky", "state": "down"}, "unknown button 'pinky'"),
({"op": "button", "button": "left", "state": "sideways"}, "unknown button state"),
],
)
def test_malformed_requests_are_answered_not_fatal(sink, request_, fragment):
driver = Dispatcher(sink)
# Aim first, so a refusal is about the field under test rather than the aim.
warp(driver)
sink.calls.clear()
response = driver.handle(request_)
assert response["ok"] is False
assert fragment in response["error"]
assert sink.calls == [], "a refused request must emit nothing"
@pytest.mark.parametrize("request_", [[], "warp", None, 7])
def test_a_non_object_request_is_refused(driver, request_):
assert driver.handle(request_)["ok"] is False
assert "must be a JSON object" in driver.handle(request_)["error"]
def test_the_contracts_five_ops_are_exactly_what_is_implemented():
assert set(Dispatcher._ops) == {"warp", "button", "frame", "pressed", "release_all"}
+136
View File
@@ -0,0 +1,136 @@
"""The driver's socket: framing, not logic.
The dispatcher is tested next door; what is proved here is that a real
``AF_UNIX`` connection carrying newline-delimited JSON gets one response object
per request line, that a garbled line is answered rather than fatal, and that
the connection stays open for the next request — which matters because the
broker holds one connection for the life of a lease.
"""
from __future__ import annotations
import json
import shutil
import socket
import tempfile
import threading
from pathlib import Path
import pytest
from hhstream_pointer.ops import Dispatcher
from hhstream_pointer.server import PointerServer
from test_ops import RecordingSink
#: Linux's sun_path is 108 bytes including the NUL, and pytest's tmp_path can
#: exceed it, so the socket lives in a shallow directory of its own.
SUN_PATH_MAX = 107
@pytest.fixture
def connection():
"""A listening driver and a connected client, torn down together."""
directory = Path(tempfile.mkdtemp(prefix="hhp"))
path = directory / "p.sock"
if len(str(path).encode()) > SUN_PATH_MAX:
pytest.skip(f"socket path too long for AF_UNIX: {path}")
sink = RecordingSink()
server = PointerServer(path, Dispatcher(sink).handle)
server.listen()
thread = threading.Thread(target=_serve_once, args=(server,), daemon=True)
thread.start()
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.settimeout(5.0)
client.connect(str(path))
try:
yield _Client(client), sink
finally:
client.close()
thread.join(timeout=5.0)
server.close()
shutil.rmtree(directory, ignore_errors=True)
def _serve_once(server: PointerServer) -> None:
conn, _ = server._sock.accept()
with conn:
server._serve_connection(conn)
class _Client:
def __init__(self, sock: socket.socket) -> None:
self._stream = sock.makefile("rwb")
def call(self, request: dict) -> dict:
self._stream.write(json.dumps(request).encode() + b"\n")
self._stream.flush()
return json.loads(self._stream.readline())
def send_raw(self, line: bytes) -> dict:
self._stream.write(line)
self._stream.flush()
return json.loads(self._stream.readline())
def test_one_request_gets_one_response(connection):
client, _ = connection
assert client.call({"op": "pressed"}) == {"ok": True, "buttons": []}
def test_many_requests_share_one_connection(connection):
client, sink = connection
assert client.call({"op": "warp", "output": "hh-a", "x": 0.5, "y": 0.5}) == {"ok": True}
assert client.call({"op": "button", "button": "left", "state": "down"}) == {"ok": True}
assert client.call({"op": "frame"}) == {"ok": True}
assert client.call({"op": "pressed"}) == {"ok": True, "buttons": ["left"]}
assert client.call({"op": "release_all"}) == {"ok": True, "lifted": ["left"]}
assert [c[0] for c in sink.calls] == ["motion", "button", "frame", "button", "frame"]
def test_a_rejected_request_leaves_the_connection_usable(connection):
client, _ = connection
assert client.call({"op": "nonsense"})["ok"] is False
assert client.call({"op": "pressed"})["ok"] is True
def test_malformed_json_is_answered_not_fatal(connection):
client, _ = connection
response = client.send_raw(b"{not json\n")
assert response["ok"] is False
assert "malformed JSON" in response["error"]
# Still talking.
assert client.call({"op": "pressed"})["ok"] is True
def test_an_oversized_line_is_refused(connection):
from hhstream_pointer.server import MAX_LINE_BYTES
client, _ = connection
response = client.send_raw(b'{"op":"' + b"x" * MAX_LINE_BYTES + b'"}\n')
assert response == {"ok": False, "error": "request line too long"}
def test_listen_replaces_a_stale_socket_file():
"""A crashed driver leaves the file behind; the unit must still start."""
directory = Path(tempfile.mkdtemp(prefix="hhp"))
path = directory / "p.sock"
if len(str(path).encode()) > SUN_PATH_MAX:
pytest.skip("socket path too long for AF_UNIX")
try:
first = PointerServer(path, Dispatcher(RecordingSink()).handle)
first.listen()
first._sock.close() # the file survives; the listener does not
second = PointerServer(path, Dispatcher(RecordingSink()).handle)
second.listen()
assert path.is_socket()
assert path.stat().st_mode & 0o777 == 0o660
second.close()
assert not path.exists()
finally:
shutil.rmtree(directory, ignore_errors=True)
+94
View File
@@ -0,0 +1,94 @@
"""The vendored protocol and the packaging around it.
The whole point of slice D is that coordinates are *output-local*, and the only
thing that makes them so is ``create_virtual_pointer_with_output``, which exists
at version 2 of ``zwlr_virtual_pointer_manager_v1`` and not at version 1. So
the version is asserted here, cheaply, on the generated source — a regeneration
against an older XML would otherwise be a silent downgrade of the one guarantee
the slice exists to provide.
The pywayland import is checked when pywayland is present and skipped when it is
not: the dev shell has no pywayland, the built package does, and this file is
run in both.
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import pytest
HAVE_PYWAYLAND = importlib.util.find_spec("pywayland") is not None
# Located through the import system, not through a path relative to this file,
# so the suite is the same whether it runs in a checkout or against the
# installed package in a build sandbox.
_spec = importlib.util.find_spec("hhstream_pointer")
assert _spec is not None and _spec.origin, "hhstream_pointer is not importable"
PACKAGE = Path(_spec.origin).parent
PROTOCOL_DIR = PACKAGE / "_protocol/wlr_virtual_pointer_unstable_v1"
MANAGER = PROTOCOL_DIR / "zwlr_virtual_pointer_manager_v1.py"
#: Only present in a checkout; a build sandbox gets the test directory alone.
PYPROJECT = Path(__file__).resolve().parents[2] / "pyproject.toml"
def test_the_generated_protocol_is_vendored():
assert (PROTOCOL_DIR / "__init__.py").is_file()
assert MANAGER.is_file()
assert (PROTOCOL_DIR / "zwlr_virtual_pointer_v1.py").is_file()
# Every vendored file is scanner output; a hand-edit should be noticed.
for path in PROTOCOL_DIR.glob("*.py"):
assert path.read_text().startswith("# This file has been autogenerated")
def test_the_manager_is_version_2_with_the_output_request():
source = MANAGER.read_text()
assert " version = 2\n" in source
assert "def create_virtual_pointer_with_output(self, seat" in source
assert "output: WlOutput | None" in source
def test_the_shim_resolves_the_generated_relative_import():
assert "from ..wayland import WlOutput" in MANAGER.read_text()
shim = (PROTOCOL_DIR.parent / "wayland.py").read_text()
assert "from pywayland.protocol.wayland import WlOutput, WlSeat" in shim
@pytest.mark.skipif(not PYPROJECT.is_file(), reason="not running from a checkout")
def test_pyproject_declares_the_entry_point_and_the_dependency():
pyproject = PYPROJECT.read_text()
assert 'hhstream-pointer = "hhstream_pointer.__main__:main"' in pyproject
assert "pywayland" in pyproject
@pytest.mark.skipif(
not HAVE_PYWAYLAND,
reason="pywayland is not in this environment (it is in the built package)",
)
def test_the_protocol_binds_against_the_installed_pywayland():
from hhstream_pointer._protocol.wlr_virtual_pointer_unstable_v1 import (
ZwlrVirtualPointerManagerV1,
ZwlrVirtualPointerV1,
)
assert ZwlrVirtualPointerManagerV1.version == 2
assert ZwlrVirtualPointerV1.version == 2
assert hasattr(
ZwlrVirtualPointerManagerV1.proxy_class, "create_virtual_pointer_with_output"
)
@pytest.mark.skipif(
not HAVE_PYWAYLAND,
reason="pywayland is not in this environment (it is in the built package)",
)
def test_the_backend_refuses_a_version_1_manager():
from hhstream_pointer.backend import MANAGER_VERSION, ManagerTooOld
assert MANAGER_VERSION == 2
message = str(ManagerTooOld(1))
assert "version 1" in message
assert "create_virtual_pointer_with_output" in message
assert "Refusing to start" in message
+93
View File
@@ -0,0 +1,93 @@
"""Aiming arithmetic (CONTRACT-sessions.md §3.3).
An agent says "click 40 pixels into this window"; the virtual pointer wants a
fraction of its output. Everything between is this one function, and the case
that breaks in the field is the last one: a window on an output that is not at
the layout origin.
"""
from __future__ import annotations
import pytest
from hhstreamd.pointer import window_to_absolute
#: A 1280x720 output at the origin, and a 640x480 window centred in it.
ORIGIN_MONITOR = (0, 0, 1280, 720)
CENTRED_WINDOW = (320, 120, 640, 480)
def test_window_centre_is_the_window_centre_not_the_monitor_centre():
# (320 + 320) / 1280 = 0.5 and (120 + 240) / 720 = 0.5 — the window happens
# to be centred, so this also pins down the easy reading of the maths.
assert window_to_absolute((320, 240), CENTRED_WINDOW, ORIGIN_MONITOR) == (0.5, 0.5)
def test_an_off_centre_window_centre_is_not_the_monitor_centre():
window = (0, 0, 640, 480)
assert window_to_absolute((320, 240), window, ORIGIN_MONITOR) == (0.25, 1 / 3)
@pytest.mark.parametrize(
"corner, expected",
[
((0, 0), (320 / 1280, 120 / 720)), # top-left
((640, 0), (960 / 1280, 120 / 720)), # top-right
((0, 480), (320 / 1280, 600 / 720)), # bottom-left
((640, 480), (960 / 1280, 600 / 720)), # bottom-right
],
)
def test_all_four_window_corners(corner, expected):
assert window_to_absolute(corner, CENTRED_WINDOW, ORIGIN_MONITOR) == expected
def test_the_far_edge_is_inside():
"""``(w, h)`` is the bottom-right corner; rejecting it makes it unaimable."""
assert window_to_absolute((640, 480), CENTRED_WINDOW, ORIGIN_MONITOR) == (0.75, 600 / 720)
@pytest.mark.parametrize("point", [(-1, 0), (0, -1), (641, 0), (0, 481), (641, 481)])
def test_a_point_outside_the_window_raises(point):
with pytest.raises(ValueError, match="outside window"):
window_to_absolute(point, CENTRED_WINDOW, ORIGIN_MONITOR)
def test_a_window_on_the_second_monitor_uses_that_monitors_frame():
"""The offset case.
Two 1280x720 outputs side by side; the window is on the right-hand one, so
its global x starts at 1280. Without subtracting the monitor origin every
coordinate would exceed 1.0, clamp, and quietly aim at the far right edge —
a click that happens, in the wrong place.
"""
monitor = (1280, 0, 1280, 720)
window = (1280 + 320, 120, 640, 480)
assert window_to_absolute((320, 240), window, monitor) == (0.5, 0.5)
assert window_to_absolute((0, 0), window, monitor) == (320 / 1280, 120 / 720)
assert window_to_absolute((640, 480), window, monitor) == (960 / 1280, 600 / 720)
def test_a_vertically_stacked_monitor_uses_its_own_origin():
monitor = (0, 720, 1280, 720)
window = (0, 720, 1280, 720)
assert window_to_absolute((640, 360), window, monitor) == (0.5, 0.5)
assert window_to_absolute((0, 0), window, monitor) == (0.0, 0.0)
def test_a_window_hanging_off_the_monitor_clamps_rather_than_overflowing():
"""Hyprland will place a window partly off-screen; 1.0 is the honest answer
for "as far as this output goes"."""
window = (1000, 600, 640, 480)
assert window_to_absolute((640, 480), window, ORIGIN_MONITOR) == (1.0, 1.0)
# Negative global coordinates clamp at the other end.
assert window_to_absolute((0, 0), (-100, -50, 640, 480), ORIGIN_MONITOR) == (0.0, 0.0)
def test_a_degenerate_window_or_monitor_raises():
with pytest.raises(ValueError, match="window has no area"):
window_to_absolute((0, 0), (0, 0, 0, 480), ORIGIN_MONITOR)
with pytest.raises(ValueError, match="monitor has no area"):
window_to_absolute((0, 0), CENTRED_WINDOW, (0, 0, 1280, 0))