Files
hyprland-headless-stream-pl…/src/hhstream_pointer/backend.py
T
HermenixandClaude Opus 5 0d414d76bc 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
2026-10-02 00:15:50 +00:00

279 lines
11 KiB
Python

"""The pywayland half: one virtual pointer per output, created on demand.
This is the only module that imports pywayland, so everything above it can be
tested without a compositor. It implements :class:`hhstream_pointer.ops.PointerSink`
and nothing else; the decisions are all next door.
Three things here are load-bearing:
* ``zwlr_virtual_pointer_manager_v1`` is bound at **version 2** and pointers are
created with :func:`create_virtual_pointer_with_output`. Version 1's
``create_virtual_pointer`` yields a pointer whose coordinates are the *global*
layout, so a warp to (0.5, 0.5) lands in the middle of the whole desktop
rather than the middle of the session's output. That is silently wrong — the
click happens, just somewhere else — so a version-1-only manager raises
:class:`ManagerTooOld` and the driver refuses to start. There is no fallback
on purpose.
* ``wl_output`` is bound at version 4, because the ``name`` event is the only
way to match the compositor's ``hh-<session-id>`` to a protocol object.
* Coordinates arrive normalised and ``motion_absolute`` takes integers, so they
are scaled by a fixed :data:`EXTENT` rather than by the output's mode. The
compositor divides by the extent we send, so the output can be resized
underneath us without changing what (0.5, 0.5) means.
"""
from __future__ import annotations
import logging
import os
import time
from pathlib import Path
from pywayland.client import Display
from pywayland.protocol.wayland import WlOutput, WlSeat
from ._protocol.wlr_virtual_pointer_unstable_v1 import ZwlrVirtualPointerManagerV1
log = logging.getLogger("hhstream_pointer.backend")
#: Denominator for normalised coordinates. 16 bits of resolution across an
#: output is ~0.02px on a 1280-wide one: far finer than anything can observe.
EXTENT = 0xFFFF
#: The ``wl_output`` version that first carried the ``name`` event.
OUTPUT_VERSION = 4
#: The manager version that first carried ``create_virtual_pointer_with_output``.
MANAGER_VERSION = 2
class CompositorUnavailable(Exception):
"""No display to connect to, or the connection died. Fatal; do not guess."""
class ManagerTooOld(Exception):
"""``zwlr_virtual_pointer_manager_v1`` is offered below version 2.
Reported, never worked around: see the module docstring.
"""
def __init__(self, offered: int) -> None:
super().__init__(
f"zwlr_virtual_pointer_manager_v1 is version {offered}, need "
f"{MANAGER_VERSION} for create_virtual_pointer_with_output; without it "
"coordinates would be global and every warp would aim at the wrong "
"output. Refusing to start."
)
self.offered = offered
class OutputUnknown(Exception):
"""The compositor advertises no output by that name."""
def find_wayland_display(runtime_dir: Path) -> str:
"""The name of the compositor's socket inside its runtime directory.
The broker hands us a directory, not a socket, because that is what the
compositor's unit is configured with. One socket is the normal case; more
than one means two compositors share the directory and guessing which is
the session one would be a coin flip, so we refuse.
"""
try:
candidates = sorted(
p.name
for p in runtime_dir.iterdir()
if p.name.startswith("wayland-") and not p.name.endswith(".lock")
)
except OSError as exc:
raise CompositorUnavailable(f"cannot read {runtime_dir}: {exc}") from None
if not candidates:
raise CompositorUnavailable(f"no wayland-* socket in {runtime_dir}")
if len(candidates) > 1:
raise CompositorUnavailable(
f"{len(candidates)} wayland sockets in {runtime_dir} ({', '.join(candidates)}); "
"pass --wayland-display to say which"
)
return candidates[0]
class _Output:
__slots__ = ("proxy", "name")
def __init__(self, proxy) -> None:
self.proxy = proxy
self.name: str | None = None
class WaylandSink:
"""A connection, a manager, and a lazily created pointer per output."""
def __init__(self, runtime_dir: Path, display_name: str | None = None) -> None:
self._runtime_dir = Path(runtime_dir)
self._display_name = display_name
self._display: Display | None = None
self._registry = None
self._seat = None
self._manager = None
self._manager_version = 0
self._output_version = 0
#: registry global id -> output
self._outputs: dict[int, _Output] = {}
#: output name -> virtual pointer proxy
self._pointers: dict[str, object] = {}
# -- lifecycle --------------------------------------------------------
def connect(self) -> None:
"""Connect, bind, and prove the manager is version 2.
``XDG_RUNTIME_DIR`` is set rather than passed because that is the only
way libwayland resolves a socket *name*; the alternative is opening the
socket ourselves and handing over an fd, which buys nothing.
"""
name = self._display_name or find_wayland_display(self._runtime_dir)
os.environ["XDG_RUNTIME_DIR"] = str(self._runtime_dir)
display = Display(name)
try:
display.connect()
except Exception as exc: # pywayland raises bare exceptions here
raise CompositorUnavailable(f"cannot connect to {self._runtime_dir}/{name}: {exc}") from None
self._display = display
self._registry = display.get_registry()
self._registry.dispatcher["global"] = self._on_global
self._registry.dispatcher["global_remove"] = self._on_global_remove
# Two round trips: the first delivers the globals, the second the
# `name` events the outputs emit once bound.
self._sync()
self._sync()
if self._manager is None:
if self._manager_version:
raise ManagerTooOld(self._manager_version)
raise CompositorUnavailable(
"compositor does not advertise zwlr_virtual_pointer_manager_v1"
)
if self._outputs and self._output_version < OUTPUT_VERSION:
raise CompositorUnavailable(
f"wl_output is version {self._output_version}, need {OUTPUT_VERSION} "
"to learn output names"
)
log.info(
"connected to %s: manager v%d, %d output(s)",
name,
self._manager_version,
len(self._outputs),
)
def close(self) -> None:
if self._display is None:
return
self._pointers.clear()
try:
self._display.disconnect()
finally:
self._display = None
def outputs(self) -> list[str]:
"""Output names currently advertised, for the log line on startup."""
return sorted(o.name for o in self._outputs.values() if o.name)
# -- PointerSink ------------------------------------------------------
def motion_absolute(self, output: str, x: float, y: float) -> None:
pointer = self._pointer(output)
pointer.motion_absolute(_now_ms(), round(x * EXTENT), round(y * EXTENT), EXTENT, EXTENT)
self._flush()
def button(self, output: str, code: int, state: int) -> None:
self._pointer(output).button(_now_ms(), code, state)
self._flush()
def frame(self, output: str) -> None:
self._pointer(output).frame()
self._flush()
# -- internals --------------------------------------------------------
def _pointer(self, output: str):
existing = self._pointers.get(output)
if existing is not None:
return existing
proxy = self._resolve(output)
pointer = self._manager.create_virtual_pointer_with_output(self._seat, proxy)
self._pointers[output] = pointer
log.debug("created virtual pointer for output %s", output)
return pointer
def _resolve(self, output: str):
"""Find an output by name, re-syncing once in case it is new.
Outputs come and go with sessions, so a miss is routine rather than an
error: the broker may have created the container microseconds ago.
"""
for attempt in (0, 1):
for entry in self._outputs.values():
if entry.name == output:
return entry.proxy
if attempt == 0:
self._sync()
self._sync()
known = ", ".join(self.outputs()) or "none"
raise OutputUnknown(f"no output named {output!r} (known: {known})")
def _sync(self) -> None:
try:
self._display.roundtrip()
except Exception as exc:
raise CompositorUnavailable(f"compositor connection lost: {exc}") from None
def _flush(self) -> None:
try:
self._display.flush()
except Exception as exc:
raise CompositorUnavailable(f"compositor connection lost: {exc}") from None
def _on_global(self, registry, global_id: int, interface: str, version: int) -> None:
if interface == ZwlrVirtualPointerManagerV1.name:
self._manager_version = version
if version >= MANAGER_VERSION:
self._manager = registry.bind(global_id, ZwlrVirtualPointerManagerV1, MANAGER_VERSION)
elif interface == WlSeat.name and self._seat is None:
self._seat = registry.bind(global_id, WlSeat, min(version, WlSeat.version))
elif interface == WlOutput.name:
self._output_version = max(self._output_version, version)
entry = _Output(registry.bind(global_id, WlOutput, min(version, OUTPUT_VERSION)))
entry.proxy.dispatcher["name"] = lambda _proxy, name, e=entry: self._name_output(e, name)
self._outputs[global_id] = entry
def _on_global_remove(self, registry, global_id: int) -> None:
entry = self._outputs.pop(global_id, None)
if entry is None or entry.name is None:
return
# The pointer was bound to an output that no longer exists; a warp
# through it would go nowhere, so drop it and let the next one be
# created against whatever replaced it.
pointer = self._pointers.pop(entry.name, None)
if pointer is not None:
pointer.destroy()
log.info("output %s went away", entry.name)
@staticmethod
def _name_output(entry: _Output, name: str) -> None:
entry.name = name
def _now_ms() -> int:
"""A millisecond timestamp for the protocol's ``time`` arguments.
The compositor only compares these to each other, so any monotonic source
will do; it is truncated to 32 bits because the wire field is a ``uint``.
"""
return int(time.monotonic() * 1000) & 0xFFFFFFFF