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:
1 parent
98374b8457
commit
0d414d76bc
21 files changed
+2417
-2
No files matched your search
@@ -0,0 +1,287 @@
|
||||
"""The pointer lease and the aiming arithmetic (CONTRACT-sessions.md §3.3).
|
||||
|
||||
Two measured facts about this compositor build force this module to exist.
|
||||
|
||||
*There is exactly one cursor.* Every virtual pointer writes to the same
|
||||
singleton position; binding a pointer to an output scopes the *coordinate
|
||||
frame*, not the focus. So two sessions moving the mouse at once would fight
|
||||
over one cursor, and the only honest fix is to let one session hold it at a
|
||||
time. That holder is the lease, and this module is the whole of it.
|
||||
|
||||
*A virtual pointer object stores no position* — only its output. So nothing
|
||||
downstream can answer "where was this session's cursor?". We remember it here,
|
||||
as a :class:`Bookmark`, and hand it back when the lease ends.
|
||||
|
||||
The module is pure: no Wayland, no socket, no ``time.sleep``. The clock is
|
||||
injected so expiry is a function of a number the test chooses, which is why
|
||||
there is not one sleep in ``tests/pointer``.
|
||||
|
||||
Expiry is deliberately *not* implicit. :meth:`PointerLease.acquire` refuses a
|
||||
busy lease rather than quietly reaping a stale one, because the stale holder
|
||||
may have left a mouse button down: only the broker can lift it, on the driver,
|
||||
and it only learns it must when :meth:`PointerLease.expire` tells it so.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
|
||||
class LeaseBusy(Exception):
|
||||
"""Someone else holds the pointer. ``holder`` is the session id."""
|
||||
|
||||
def __init__(self, holder: str) -> None:
|
||||
super().__init__(f"pointer held by {holder}")
|
||||
self.holder = holder
|
||||
|
||||
|
||||
class LeaseInvalid(Exception):
|
||||
"""Not held at all, or held by another session, or a stale ``lease_id``."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Bookmark:
|
||||
"""Where a session left the cursor, in its own output's frame.
|
||||
|
||||
Normalised rather than pixels: the output can be resized under us, and a
|
||||
fraction survives that where a pixel pair does not.
|
||||
"""
|
||||
|
||||
x: float
|
||||
y: float
|
||||
output: str
|
||||
at: str # ISO-8601 UTC, for humans; nothing computes with it.
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LeaseInfo:
|
||||
session_id: str
|
||||
lease_id: str
|
||||
acquired_at: float
|
||||
expires_at: float
|
||||
hard_deadline: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LeaseOutcome:
|
||||
bookmark: Bookmark | None
|
||||
reason: str
|
||||
buttons_lifted: list[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Held:
|
||||
"""The live lease. Mutable because ``refresh`` moves ``expires_at``."""
|
||||
|
||||
session_id: str
|
||||
lease_id: str
|
||||
acquired_at: float
|
||||
expires_at: float
|
||||
hard_deadline: float
|
||||
bookmark: Bookmark | None = None
|
||||
#: Insertion-ordered set: a dict with ignored values. Order is kept so a
|
||||
#: forced release lifts buttons in the order they went down.
|
||||
buttons: dict[str, None] = field(default_factory=dict)
|
||||
|
||||
def info(self) -> LeaseInfo:
|
||||
return LeaseInfo(
|
||||
session_id=self.session_id,
|
||||
lease_id=self.lease_id,
|
||||
acquired_at=self.acquired_at,
|
||||
expires_at=self.expires_at,
|
||||
hard_deadline=self.hard_deadline,
|
||||
)
|
||||
|
||||
|
||||
class PointerLease:
|
||||
"""One holder at a time, with two deadlines.
|
||||
|
||||
``ttl_s`` is the idle timeout, pushed forward by :meth:`refresh`.
|
||||
``max_s`` is the hard cap, fixed at acquisition: an agent that refreshes in
|
||||
a loop still loses the pointer eventually, so a stuck agent cannot lock
|
||||
every other session out of the mouse forever.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ttl_s: float = 30.0,
|
||||
max_s: float = 300.0,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
) -> None:
|
||||
self.ttl_s = float(ttl_s)
|
||||
self.max_s = float(max_s)
|
||||
self._clock = clock
|
||||
self._held: _Held | None = None
|
||||
|
||||
# -- acquisition ------------------------------------------------------
|
||||
|
||||
def acquire(self, session_id: str) -> str:
|
||||
"""Take the pointer. Returns the ``lease_id`` every verb must quote.
|
||||
|
||||
A second ``acquire`` raises :class:`LeaseBusy` even when the caller is
|
||||
the current holder: handing the same session a second ``lease_id``
|
||||
would silently invalidate the first, and a half-finished drag would
|
||||
then fail with "stale lease" for no reason the agent can see.
|
||||
"""
|
||||
|
||||
if self._held is not None:
|
||||
raise LeaseBusy(self._held.session_id)
|
||||
now = self._clock()
|
||||
lease_id = uuid.uuid4().hex
|
||||
self._held = _Held(
|
||||
session_id=session_id,
|
||||
lease_id=lease_id,
|
||||
acquired_at=now,
|
||||
expires_at=now + self.ttl_s,
|
||||
hard_deadline=now + self.max_s,
|
||||
)
|
||||
return lease_id
|
||||
|
||||
def refresh(self, session_id: str, lease_id: str) -> None:
|
||||
"""Push the idle deadline out. The hard cap does not move.
|
||||
|
||||
A lease already past either deadline cannot be revived — it is held
|
||||
only until the broker's next :meth:`expire`, and reviving it here would
|
||||
let a refresh loop outrun the reaper.
|
||||
"""
|
||||
|
||||
held = self._check(session_id, lease_id)
|
||||
now = self._clock()
|
||||
if self._past_deadline(held, now):
|
||||
raise LeaseInvalid("lease has expired; it is awaiting release")
|
||||
held.expires_at = now + self.ttl_s
|
||||
|
||||
def release(self, session_id: str, lease_id: str, reason: str) -> LeaseOutcome:
|
||||
"""Give the pointer back, reporting the bookmark and what was lifted."""
|
||||
|
||||
held = self._check(session_id, lease_id)
|
||||
self._held = None
|
||||
return LeaseOutcome(
|
||||
bookmark=held.bookmark,
|
||||
reason=reason,
|
||||
buttons_lifted=list(held.buttons),
|
||||
)
|
||||
|
||||
def expire(self) -> LeaseInfo | None:
|
||||
"""Force-release a lease past its TTL or its hard cap.
|
||||
|
||||
Returns what was released, or ``None`` if nothing was due. The caller
|
||||
lifts the buttons on the driver: this object's button set is a mirror
|
||||
of the driver's, never the authority, so it is simply dropped here and
|
||||
``release_all`` on the driver is what actually ungrabs the mouse.
|
||||
"""
|
||||
|
||||
held = self._held
|
||||
if held is None:
|
||||
return None
|
||||
if not self._past_deadline(held, self._clock()):
|
||||
return None
|
||||
self._held = None
|
||||
return held.info()
|
||||
|
||||
def state(self) -> dict:
|
||||
held = self._held
|
||||
if held is None:
|
||||
return {"holder": None, "since": None, "lease_id": None, "expires_at": None}
|
||||
return {
|
||||
"holder": held.session_id,
|
||||
"since": held.acquired_at,
|
||||
"lease_id": held.lease_id,
|
||||
"expires_at": held.expires_at,
|
||||
}
|
||||
|
||||
# -- buttons ----------------------------------------------------------
|
||||
|
||||
def press(self, session_id: str, button: str) -> None:
|
||||
self._holder(session_id).buttons[button] = None
|
||||
|
||||
def unpress(self, session_id: str, button: str) -> list[str]:
|
||||
"""Lift one button. Returns what actually came up — ``[]`` if it was
|
||||
never down, so a duplicate release is reported rather than invented."""
|
||||
|
||||
buttons = self._holder(session_id).buttons
|
||||
if button not in buttons:
|
||||
return []
|
||||
del buttons[button]
|
||||
return [button]
|
||||
|
||||
def pressed(self) -> list[str]:
|
||||
"""Buttons currently down, oldest first. Empty when unheld."""
|
||||
|
||||
return [] if self._held is None else list(self._held.buttons)
|
||||
|
||||
# -- bookmark ---------------------------------------------------------
|
||||
|
||||
def mark(self, session_id: str, lease_id: str, bookmark: Bookmark) -> None:
|
||||
"""Record where the cursor now is.
|
||||
|
||||
Beyond §3.3, and the smallest addition that makes the contract's own
|
||||
``LeaseOutcome.bookmark`` reachable: nothing else in the interface can
|
||||
set it, so without this it would be ``None`` forever. See the slice
|
||||
report.
|
||||
"""
|
||||
|
||||
self._check(session_id, lease_id).bookmark = bookmark
|
||||
|
||||
# -- internals --------------------------------------------------------
|
||||
|
||||
def _past_deadline(self, held: _Held, now: float) -> bool:
|
||||
return now >= held.expires_at or now >= held.hard_deadline
|
||||
|
||||
def _holder(self, session_id: str) -> _Held:
|
||||
"""The lease, if ``session_id`` holds it. Verbs that carry no
|
||||
``lease_id`` (``press``/``unpress``) can only check the holder."""
|
||||
|
||||
held = self._held
|
||||
if held is None:
|
||||
raise LeaseInvalid("no pointer lease is held")
|
||||
if held.session_id != session_id:
|
||||
raise LeaseInvalid(f"pointer is held by {held.session_id}, not {session_id}")
|
||||
return held
|
||||
|
||||
def _check(self, session_id: str, lease_id: str) -> _Held:
|
||||
held = self._holder(session_id)
|
||||
if held.lease_id != lease_id:
|
||||
raise LeaseInvalid("stale lease_id")
|
||||
return held
|
||||
|
||||
|
||||
def window_to_absolute(
|
||||
point: tuple[int, int],
|
||||
window: tuple[int, int, int, int],
|
||||
monitor: tuple[int, int, int, int],
|
||||
) -> tuple[float, float]:
|
||||
"""Window-local pixels to a 0..1 position in the monitor's own frame.
|
||||
|
||||
``point`` is relative to the window's top-left; ``window`` and ``monitor``
|
||||
are ``(x, y, w, h)`` in the compositor's global layout. The monitor
|
||||
offset is the part that breaks in practice: with two outputs side by side
|
||||
the second one's windows have large global ``x``, and forgetting to
|
||||
subtract the monitor origin aims the cursor off the right-hand edge — where
|
||||
it clamps to 1.0 and looks like "the click landed, just in the wrong
|
||||
place". Hence the subtraction, and hence a test for it.
|
||||
|
||||
The window's far edges count as inside: a caller aiming at the
|
||||
bottom-right corner means ``(w, h)``, and rejecting it would leave the
|
||||
corner unaimable. Anything beyond raises, because a point outside the
|
||||
window is a caller bug — clamping it would quietly click on whatever
|
||||
happens to be next door.
|
||||
"""
|
||||
|
||||
px, py = point
|
||||
wx, wy, ww, wh = window
|
||||
mx, my, mw, mh = monitor
|
||||
|
||||
if ww <= 0 or wh <= 0:
|
||||
raise ValueError(f"window has no area: {window!r}")
|
||||
if mw <= 0 or mh <= 0:
|
||||
raise ValueError(f"monitor has no area: {monitor!r}")
|
||||
if not (0 <= px <= ww and 0 <= py <= wh):
|
||||
raise ValueError(f"point {point!r} is outside window {window!r}")
|
||||
|
||||
x = (wx + px - mx) / mw
|
||||
y = (wy + py - my) / mh
|
||||
return (min(1.0, max(0.0, x)), min(1.0, max(0.0, y)))
|
||||
Reference in new issue
Block a user