A session could move a cursor and press it, but not scroll. The protocol already had the request -- zwlr_virtual_pointer_v1.axis(time, axis, value) -- it had simply never been implemented, in the driver or the broker. hhstream session pointer scroll <id> --axis vertical --amount 3 Positive is down (vertical) or right (horizontal): the protocol's direction, not a choice of ours, which is why direction travels in the sign and there is deliberately no up/down vocabulary layered over it. The output is whatever the last warp aimed at, exactly like a button, so scrolling somewhere else is a warp first -- and the lease is what keeps the whole gesture atomic. Bounded at 100 wheel clicks per request on both sides, because a decimal-point slip should be a refusal rather than a session scrolled somewhere unrecoverable. The resume point is re-stamped, not moved: the cursor did not go anywhere, so the coordinates are re-affirmed and only the stamp advances. Recorded in the contract as an amendment to the frozen op set, because adding an op to a frozen interface should be visible rather than implied. Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
203 lines
7.7 KiB
Python
203 lines
7.7 KiB
Python
"""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 axis(self, output: str, axis: int, value: float) -> None:
|
|
"""Scroll by ``value`` wheel clicks along ``axis`` (a ``wl_pointer_axis``).
|
|
|
|
Positive vertical is *down* and positive horizontal is *right*, which is
|
|
the protocol's direction and not a choice of ours.
|
|
"""
|
|
|
|
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_axis(self, request: dict) -> dict[str, Any]:
|
|
"""Scroll the aimed output.
|
|
|
|
The output is implicit, like ``button``: there is one cursor, and a
|
|
scroll belongs to whatever it is currently over. A caller that wants to
|
|
scroll somewhere else warps first, which is also what makes the gesture
|
|
serialisable by the lease.
|
|
"""
|
|
|
|
name = request.get("axis", "vertical")
|
|
if not isinstance(name, str):
|
|
raise Rejected("'axis' must be a string")
|
|
try:
|
|
code = buttons.axis_for(name)
|
|
except ValueError as exc:
|
|
raise Rejected(str(exc)) from None
|
|
|
|
value = request.get("value", 1.0)
|
|
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
raise Rejected("'value' must be a number of wheel clicks")
|
|
value = float(value)
|
|
if value != value or value in (float("inf"), float("-inf")):
|
|
raise Rejected("'value' must be finite")
|
|
if abs(value) > buttons.MAX_AXIS_VALUE:
|
|
raise Rejected(
|
|
f"'value' {value} exceeds the {buttons.MAX_AXIS_VALUE:g} wheel-click limit"
|
|
)
|
|
|
|
self._sink.axis(self._aimed(), code, value)
|
|
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,
|
|
"axis": _op_axis,
|
|
"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
|