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

+163
View File
@@ -0,0 +1,163 @@
"""The private broker↔driver protocol (CONTRACT-sessions.md §3.4).
Newline-delimited JSON, one request object per line, one response object back.
Every response is ``{"ok": true, ...}`` or ``{"ok": false, "error": "<text>"}``;
a rejected request is answered, never fatal, because the broker is a long-lived
peer and dropping its connection would cost it a cursor it still holds a lease
on.
This module is the whole of the driver's logic and it touches no Wayland. It
speaks to a :class:`PointerSink` — "send this to the virtual pointer bound to
*this* output" — which is the one thing pywayland is needed for. That seam is
why the dispatcher can be tested without a compositor, and the test suite does
exactly that.
The dispatcher keeps two pieces of *device* state, which is not lease state:
* the output of the last ``warp``, because ``button`` and ``frame`` carry no
output of their own and there is only one cursor to aim;
* which buttons are down and on which pointer, because ``release_all`` has to
report what it lifted and must lift it through the pointer it went down on.
It keeps no notion of who is allowed to ask. That is the lease, and the lease
lives in the broker.
"""
from __future__ import annotations
from typing import Any, Protocol
from . import buttons
class PointerSink(Protocol):
"""A virtual pointer per output. Implemented by :mod:`.backend`."""
def motion_absolute(self, output: str, x: float, y: float) -> None:
"""Warp to ``x``/``y``, each 0..1 in ``output``'s own frame."""
def button(self, output: str, code: int, state: int) -> None:
"""An evdev button code and a ``wl_pointer.button_state``."""
def frame(self, output: str) -> None:
"""Commit the queued events. Nothing is delivered until this."""
class Rejected(Exception):
"""The request was understood and refused; the text goes to the broker."""
class Dispatcher:
def __init__(self, sink: PointerSink) -> None:
self._sink = sink
self._output: str | None = None
#: button name -> the output its press was sent to. Insertion-ordered,
#: so a release_all lifts in the order things went down.
self._pressed: dict[str, str] = {}
def handle(self, request: Any) -> dict[str, Any]:
"""One request object to one response object. Never raises."""
try:
return self._handle(request)
except Rejected as exc:
return {"ok": False, "error": str(exc)}
def _handle(self, request: Any) -> dict[str, Any]:
if not isinstance(request, dict):
raise Rejected(f"request must be a JSON object, got {type(request).__name__}")
op = request.get("op")
if not isinstance(op, str):
raise Rejected("request has no 'op'")
handler = self._ops.get(op)
if handler is None:
raise Rejected(f"unknown op {op!r} (known: {', '.join(sorted(self._ops))})")
return handler(self, request)
# -- ops --------------------------------------------------------------
def _op_warp(self, request: dict) -> dict[str, Any]:
output = _require_output(request)
x = _require_unit(request, "x")
y = _require_unit(request, "y")
self._sink.motion_absolute(output, x, y)
# Only now: a sink that raised must not leave us aiming at an output we
# never reached, or the next `button` would land on the wrong session.
self._output = output
return {"ok": True}
def _op_button(self, request: dict) -> dict[str, Any]:
name = request.get("button")
if not isinstance(name, str):
raise Rejected("'button' must be a string")
state = request.get("state")
if not isinstance(state, str):
raise Rejected("'state' must be 'down' or 'up'")
try:
code = buttons.code_for(name)
value = buttons.state_for(state)
except ValueError as exc:
raise Rejected(str(exc)) from None
output = self._aimed()
self._sink.button(output, code, value)
if state == "down":
self._pressed[name] = output
else:
self._pressed.pop(name, None)
return {"ok": True}
def _op_frame(self, request: dict) -> dict[str, Any]:
self._sink.frame(self._aimed())
return {"ok": True}
def _op_pressed(self, request: dict) -> dict[str, Any]:
return {"ok": True, "buttons": list(self._pressed)}
def _op_release_all(self, request: dict) -> dict[str, Any]:
"""Lift everything. The broker calls this when a lease expires, so it
must not depend on an aim: each button is lifted through the pointer it
was pressed on, even if the cursor has since been warped elsewhere."""
lifted = list(self._pressed)
outputs = list(dict.fromkeys(self._pressed.values()))
for name in lifted:
self._sink.button(self._pressed[name], buttons.code_for(name), buttons.STATES["up"])
self._pressed.clear()
for output in outputs:
self._sink.frame(output)
return {"ok": True, "lifted": lifted}
_ops = {
"warp": _op_warp,
"button": _op_button,
"frame": _op_frame,
"pressed": _op_pressed,
"release_all": _op_release_all,
}
# -- internals --------------------------------------------------------
def _aimed(self) -> str:
if self._output is None:
raise Rejected("no output is aimed; warp before button or frame")
return self._output
def _require_output(request: dict) -> str:
output = request.get("output")
if not isinstance(output, str) or not output:
raise Rejected("'output' must be a non-empty string")
return output
def _require_unit(request: dict, key: str) -> float:
value = request.get(key)
# bool is an int in Python and would pass silently; a boolean coordinate is
# a bug in the caller, not a 0 or a 1.
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise Rejected(f"'{key}' must be a number in 0..1")
value = float(value)
if not 0.0 <= value <= 1.0:
raise Rejected(f"'{key}' is {value}, outside 0..1 — coordinates are normalised")
return value