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

+13
View File
@@ -0,0 +1,13 @@
"""The pointer driver: a Wayland client that moves one cursor on command.
Its own process, for two reasons that are not negotiable. A Wayland client
needs its own connection to the compositor, and the broker is not one. And a
Wayland round-trip can block indefinitely — on a compositor that is busy, or
wedged — so running it inside the broker would let a stuck cursor stall every
other session's lifecycle.
It holds **no lease state**. It is told what to do and does it; the broker owns
the lease. See ``docs/CONTRACT-sessions.md`` §3.4. A driver that could be
trusted to serialise would eventually be trusted to, and there is exactly one
cursor to get that wrong with.
"""
+155
View File
@@ -0,0 +1,155 @@
"""``hhstream-pointer`` — the driver's entry point (CONTRACT-sessions.md §3.4).
The broker starts it with exactly:
hhstream-pointer --socket /run/hhstream/pointer.sock \\
--compositor-runtime-dir /run/hypr-stream
Both flags default to those frozen paths (§5) so the binary is also runnable by
hand when diagnosing a stuck cursor.
It connects to the compositor *before* it listens. A socket that exists is a
promise that warps will work, and a driver that accepted requests while still
looking for a version-2 manager would answer the first few with errors the
broker cannot tell apart from a bad output name.
"""
from __future__ import annotations
import argparse
import logging
import signal
import sys
from pathlib import Path
from typing import Any
from .backend import CompositorUnavailable, ManagerTooOld, OutputUnknown, WaylandSink
from .ops import Dispatcher
from .server import PointerServer
log = logging.getLogger("hhstream_pointer")
#: Mirrors ``hhstreamd.protocol.ExitCode`` (CONTRACT-sessions.md §4) without
#: importing it: the driver is a separate package on purpose and must not grow
#: a dependency on the broker's internals.
EXIT_OK = 0
EXIT_USAGE = 2
EXIT_COMPOSITOR = 10
DEFAULT_SOCKET = Path("/run/hhstream/pointer.sock")
DEFAULT_RUNTIME_DIR = Path("/run/hypr-stream")
class _Terminated(Exception):
"""SIGTERM/SIGINT arrived; unwind through the normal shutdown path."""
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="hhstream-pointer",
description="Move one headless Hyprland cursor on the broker's instruction.",
)
parser.add_argument(
"--socket", type=Path, default=DEFAULT_SOCKET, help="broker↔driver socket to create"
)
parser.add_argument(
"--compositor-runtime-dir",
type=Path,
default=DEFAULT_RUNTIME_DIR,
help="the compositor's XDG_RUNTIME_DIR, holding its wayland-* socket",
)
parser.add_argument(
"--wayland-display",
default=None,
help="socket name within that directory; only needed if it holds more than one",
)
parser.add_argument(
"--socket-mode",
type=lambda s: int(s, 8),
default=0o660,
help="octal mode for the driver socket (default 660)",
)
parser.add_argument("--log-level", default="info", help="debug, info, warning, error")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
logging.basicConfig(
level=getattr(logging, args.log_level.upper(), logging.INFO),
format="%(levelname)s %(name)s: %(message)s",
)
sink = WaylandSink(args.compositor_runtime_dir, args.wayland_display)
try:
sink.connect()
except ManagerTooOld as exc:
# The one failure worth shouting about: everything would appear to work
# and every click would land on the wrong output.
log.error("%s", exc)
return EXIT_COMPOSITOR
except CompositorUnavailable as exc:
log.error("%s", exc)
return EXIT_COMPOSITOR
dispatcher = Dispatcher(sink)
server = PointerServer(args.socket, _handler(dispatcher), socket_mode=args.socket_mode)
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, _raise_terminated)
try:
server.listen()
log.info("outputs: %s", ", ".join(sink.outputs()) or "none yet")
server.serve_forever()
except _Terminated:
log.info("terminating")
return EXIT_OK
except CompositorUnavailable as exc:
log.error("%s", exc)
return EXIT_COMPOSITOR
except OSError as exc:
log.error("socket %s: %s", args.socket, exc)
return EXIT_USAGE
finally:
# Never exit with a button held: the compositor would keep it down and
# the next session would inherit a drag it never started.
_lift_everything(dispatcher)
server.close()
sink.close()
def _handler(dispatcher: Dispatcher):
"""Turn a recoverable backend failure into an answer, not a crash.
An unknown output is routine — the broker may be racing a container it just
tore down — so it is reported on the wire. A lost compositor connection is
not recoverable and is allowed through, because a driver talking to a dead
display has nothing useful left to say.
"""
def handle(request: Any) -> dict[str, Any]:
try:
return dispatcher.handle(request)
except OutputUnknown as exc:
return {"ok": False, "error": str(exc)}
return handle
def _lift_everything(dispatcher: Dispatcher) -> None:
try:
lifted = dispatcher.handle({"op": "release_all"}).get("lifted") or []
except Exception as exc: # shutdown is not a place to raise
log.warning("could not lift buttons on the way out: %s", exc)
return
if lifted:
log.info("lifted on shutdown: %s", ", ".join(lifted))
def _raise_terminated(signum: int, frame) -> None:
raise _Terminated(signal.Signals(signum).name)
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,12 @@
"""The wlr virtual-pointer protocol, generated and vendored.
``wlr_virtual_pointer_unstable_v1/`` is byte-for-byte pywayland scanner output
for ``wlr-virtual-pointer-unstable-v1.xml``; do not hand-edit it. Regenerate
with :mod:`hhstream_pointer._protocol.regenerate`, which prints the command.
Vendored rather than generated at build time for one reason: the scanner needs
``wlr-protocols`` and a working pywayland on the *build* host, so generating
would put a code generator between a checkout and a runnable driver — including
in the dev shell, which has neither. Vendored, the file is reviewable in a
diff, and a protocol bump shows up as a protocol bump.
"""
@@ -0,0 +1,72 @@
"""Regenerate the vendored protocol package. Run by hand after a bump.
nix shell --impure --expr 'with (builtins.getFlake "nixpkgs").legacyPackages.${builtins.currentSystem}; [ (python3.withPackages (p: [ p.pywayland ])) wlr-protocols ]' \\
--command python3 -m hhstream_pointer._protocol.regenerate
The XML lives at ``share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml``
in ``pkgs.wlr-protocols`` — note that this is *not* the path
``docs/CONTRACT-sessions.md`` §3.4 gives; see the slice report.
pywayland's own ``python -m pywayland.scanner`` is not usable here: it builds
its import map only from the files it was handed, so scanning the wlr XML alone
raises ``KeyError: 'wl_seat'``. We seed the map with the core interfaces
pywayland already ships, then let the scanner emit ``from ..wayland import ...``
against the shim next door.
"""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
#: Where ``pkgs.wlr-protocols`` puts it, relative to the package root.
XML_SUFFIX = "share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml"
def find_xml() -> Path | None:
"""Look for the protocol XML on ``XDG_DATA_DIRS`` and in the nix profile."""
roots = [Path(p).parent for p in os.environ.get("XDG_DATA_DIRS", "").split(":") if p]
roots += [Path("/run/current-system/sw"), Path.home() / ".nix-profile"]
for root in roots:
candidate = root / XML_SUFFIX
if candidate.is_file():
return candidate
return None
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--xml", type=Path, default=None, help=f"path to .../{XML_SUFFIX}")
parser.add_argument(
"--output-dir",
type=Path,
default=Path(__file__).resolve().parent,
help="where the protocol package is written (default: next to this file)",
)
args = parser.parse_args(argv)
xml = args.xml or find_xml()
if xml is None:
parser.error(f"could not find {XML_SUFFIX}; pass --xml (is wlr-protocols in the shell?)")
from pywayland.protocol import wayland as core
from pywayland.scanner.protocol import Protocol
protocol = Protocol.parse_file(str(xml))
module = protocol.name.replace("-", "_")
# Interface -> protocol module. The core interfaces resolve to the shim in
# this directory; ours resolve to themselves.
core_dir = Path(core.__file__).parent
imports = {p.stem: "wayland" for p in core_dir.glob("wl_*.py")}
imports.update({iface.name: module for iface in protocol.interface})
protocol.output(str(args.output_dir), imports)
print(f"generated {module} from {xml} into {args.output_dir}")
return 0
if __name__ == "__main__":
sys.exit(main())
+12
View File
@@ -0,0 +1,12 @@
"""Resolve the generated module's ``from ..wayland import ...``.
The scanner emits a package-relative import for interfaces defined in another
protocol, so the vendored ``zwlr_virtual_pointer_manager_v1`` asks its sibling
``wayland`` module for ``wl_seat`` and ``wl_output``. Those are core Wayland
and pywayland already ships them; re-exporting here keeps the generated file
unpatched, and keeps exactly one Python class per Wayland interface — two would
each register their own ``wl_interface`` and the registry would bind the wrong
one.
"""
from pywayland.protocol.wayland import WlOutput, WlSeat # noqa: F401
@@ -0,0 +1,25 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2019 Josef Gajdusek
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from .zwlr_virtual_pointer_manager_v1 import ZwlrVirtualPointerManagerV1 # noqa: F401
from .zwlr_virtual_pointer_v1 import ZwlrVirtualPointerV1 # noqa: F401
@@ -0,0 +1,117 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2019 Josef Gajdusek
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from ..wayland import WlOutput
from ..wayland import WlSeat
from .zwlr_virtual_pointer_v1 import ZwlrVirtualPointerV1
class ZwlrVirtualPointerManagerV1(Interface):
"""Virtual pointer manager
This object allows clients to create individual virtual pointer objects.
"""
name = "zwlr_virtual_pointer_manager_v1"
version = 2
class ZwlrVirtualPointerManagerV1Proxy(Proxy[ZwlrVirtualPointerManagerV1]):
interface = ZwlrVirtualPointerManagerV1
@ZwlrVirtualPointerManagerV1.request(
Argument(ArgumentType.Object, interface=WlSeat, nullable=True),
Argument(ArgumentType.NewId, interface=ZwlrVirtualPointerV1),
)
def create_virtual_pointer(self, seat: WlSeat | None) -> Proxy[ZwlrVirtualPointerV1]:
"""Create a new virtual pointer
Creates a new virtual pointer. The optional seat is a suggestion to the
compositor.
:param seat:
:type seat:
:class:`~pywayland.protocol.wayland.WlSeat` or `None`
:returns:
:class:`~pywayland.protocol.wlr_virtual_pointer_unstable_v1.ZwlrVirtualPointerV1`
"""
id = self._marshal_constructor(0, ZwlrVirtualPointerV1, seat)
return id
@ZwlrVirtualPointerManagerV1.request(version=1)
def destroy(self) -> None:
"""Destroy the virtual pointer manager
"""
self._marshal(1)
self._destroy()
@ZwlrVirtualPointerManagerV1.request(
Argument(ArgumentType.Object, interface=WlSeat, nullable=True),
Argument(ArgumentType.Object, interface=WlOutput, nullable=True),
Argument(ArgumentType.NewId, interface=ZwlrVirtualPointerV1),
version=2,
)
def create_virtual_pointer_with_output(self, seat: WlSeat | None, output: WlOutput | None) -> Proxy[ZwlrVirtualPointerV1]:
"""Create a new virtual pointer
Creates a new virtual pointer. The seat and the output arguments are
optional. If the seat argument is set, the compositor should assign the
input device to the requested seat. If the output argument is set, the
compositor should map the input device to the requested output.
:param seat:
:type seat:
:class:`~pywayland.protocol.wayland.WlSeat` or `None`
:param output:
:type output:
:class:`~pywayland.protocol.wayland.WlOutput` or `None`
:returns:
:class:`~pywayland.protocol.wlr_virtual_pointer_unstable_v1.ZwlrVirtualPointerV1`
"""
id = self._marshal_constructor(2, ZwlrVirtualPointerV1, seat, output)
return id
class ZwlrVirtualPointerManagerV1Resource(Resource):
interface = ZwlrVirtualPointerManagerV1
class ZwlrVirtualPointerManagerV1Global(Global):
interface = ZwlrVirtualPointerManagerV1
ZwlrVirtualPointerManagerV1._gen_c()
ZwlrVirtualPointerManagerV1.proxy_class = ZwlrVirtualPointerManagerV1Proxy
ZwlrVirtualPointerManagerV1.resource_class = ZwlrVirtualPointerManagerV1Resource
ZwlrVirtualPointerManagerV1.global_class = ZwlrVirtualPointerManagerV1Global
@@ -0,0 +1,267 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2019 Josef Gajdusek
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
class ZwlrVirtualPointerV1(Interface):
"""Virtual pointer
This protocol allows clients to emulate a physical pointer device. The
requests are mostly mirror opposites of those specified in
:class:`~pywayland.protocol.wayland.WlPointer`.
"""
name = "zwlr_virtual_pointer_v1"
version = 2
class error(enum.IntEnum):
invalid_axis = 0
invalid_axis_source = 1
class ZwlrVirtualPointerV1Proxy(Proxy[ZwlrVirtualPointerV1]):
interface = ZwlrVirtualPointerV1
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Fixed),
)
def motion(self, time: int, dx: float, dy: float) -> None:
"""Pointer relative motion event
The pointer has moved by a relative amount to the previous request.
Values are in the global compositor space.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param dx:
displacement on the x-axis
:type dx:
`ArgumentType.Fixed`
:param dy:
displacement on the y-axis
:type dy:
`ArgumentType.Fixed`
"""
self._marshal(0, time, dx, dy)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def motion_absolute(self, time: int, x: int, y: int, x_extent: int, y_extent: int) -> None:
"""Pointer absolute motion event
The pointer has moved in an absolute coordinate frame.
Value of x can range from 0 to x_extent, value of y can range from 0 to
y_extent.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param x:
position on the x-axis
:type x:
`ArgumentType.Uint`
:param y:
position on the y-axis
:type y:
`ArgumentType.Uint`
:param x_extent:
extent of the x-axis
:type x_extent:
`ArgumentType.Uint`
:param y_extent:
extent of the y-axis
:type y_extent:
`ArgumentType.Uint`
"""
self._marshal(1, time, x, y, x_extent, y_extent)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def button(self, time: int, button: int, state: int) -> None:
"""Button event
A button was pressed or released.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param button:
button that produced the event
:type button:
`ArgumentType.Uint`
:param state:
physical state of the button
:type state:
`ArgumentType.Uint`
"""
self._marshal(2, time, button, state)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Fixed),
)
def axis(self, time: int, axis: int, value: float) -> None:
"""Axis event
Scroll and other axis requests.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param axis:
axis type
:type axis:
`ArgumentType.Uint`
:param value:
length of vector in touchpad coordinates
:type value:
`ArgumentType.Fixed`
"""
self._marshal(3, time, axis, value)
@ZwlrVirtualPointerV1.request()
def frame(self) -> None:
"""End of a pointer event sequence
Indicates the set of events that logically belong together.
"""
self._marshal(4)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
)
def axis_source(self, axis_source: int) -> None:
"""Axis source event
Source information for scroll and other axis.
:param axis_source:
source of the axis event
:type axis_source:
`ArgumentType.Uint`
"""
self._marshal(5, axis_source)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def axis_stop(self, time: int, axis: int) -> None:
"""Axis stop event
Stop notification for scroll and other axes.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param axis:
the axis stopped with this event
:type axis:
`ArgumentType.Uint`
"""
self._marshal(6, time, axis)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Int),
)
def axis_discrete(self, time: int, axis: int, value: float, discrete: int) -> None:
"""Axis click event
Discrete step information for scroll and other axes.
This event allows the client to extend data normally sent using the
axis event with discrete value.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param axis:
axis type
:type axis:
`ArgumentType.Uint`
:param value:
length of vector in touchpad coordinates
:type value:
`ArgumentType.Fixed`
:param discrete:
number of steps
:type discrete:
`ArgumentType.Int`
"""
self._marshal(7, time, axis, value, discrete)
@ZwlrVirtualPointerV1.request(version=1)
def destroy(self) -> None:
"""Destroy the virtual pointer object
"""
self._marshal(8)
self._destroy()
class ZwlrVirtualPointerV1Resource(Resource):
interface = ZwlrVirtualPointerV1
class ZwlrVirtualPointerV1Global(Global):
interface = ZwlrVirtualPointerV1
ZwlrVirtualPointerV1._gen_c()
ZwlrVirtualPointerV1.proxy_class = ZwlrVirtualPointerV1Proxy
ZwlrVirtualPointerV1.resource_class = ZwlrVirtualPointerV1Resource
ZwlrVirtualPointerV1.global_class = ZwlrVirtualPointerV1Global
+278
View File
@@ -0,0 +1,278 @@
"""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
+48
View File
@@ -0,0 +1,48 @@
"""Button names on the wire, evdev codes on the protocol.
``zwlr_virtual_pointer_v1.button`` takes a Linux input event code, not a name,
so the mapping has to live somewhere. It lives here, spelled out, rather than
being computed from ``BTN_LEFT + n``: the evdev block is not contiguous in any
meaningful order and a reader should be able to check a value against
``linux/input-event-codes.h`` without arithmetic.
Only the buttons an agent can ask for are listed. Adding a name here is the
whole of adding a button; nothing else switches on these.
"""
from __future__ import annotations
#: Agent-facing name -> ``BTN_*`` code from ``linux/input-event-codes.h``.
CODES: dict[str, int] = {
"left": 0x110, # BTN_LEFT
"right": 0x111, # BTN_RIGHT
"middle": 0x112, # BTN_MIDDLE
"side": 0x113, # BTN_SIDE
"extra": 0x114, # BTN_EXTRA
"forward": 0x115, # BTN_FORWARD
"back": 0x116, # BTN_BACK
"task": 0x117, # BTN_TASK
}
#: ``wl_pointer.button_state``. Named on the wire so a log line reads.
STATES: dict[str, int] = {"up": 0, "down": 1}
NAMES = tuple(CODES)
def code_for(name: str) -> int:
"""The evdev code for a button name, or :class:`ValueError` naming the set."""
try:
return CODES[name]
except KeyError:
raise ValueError(f"unknown button {name!r} (known: {', '.join(NAMES)})") from None
def state_for(state: str) -> int:
"""``"down"``/``"up"`` to ``wl_pointer.button_state``."""
try:
return STATES[state]
except KeyError:
raise ValueError(f"unknown button state {state!r} (expected 'down' or 'up')") from None
+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
+90
View File
@@ -0,0 +1,90 @@
"""The private socket: one connection at a time, newline-delimited JSON.
Deliberately sequential. There is one cursor, so concurrency here would buy
nothing but a way to interleave two warps; the broker is the only client and it
holds the lease that makes its calls ordered already. A second connection
simply waits in the listen backlog.
Framing matches the broker's own control socket (``hhstreamd/protocol.py``): a
line per message, a bounded line length so a confused peer cannot grow our read
buffer, and a reply for every request including the rejected ones.
"""
from __future__ import annotations
import json
import logging
import os
import socket
from pathlib import Path
from typing import Any, Callable
log = logging.getLogger("hhstream_pointer.server")
#: Matches ``hhstreamd.protocol.MAX_LINE_BYTES``. Pointer requests are tiny;
#: this is a ceiling, not a budget.
MAX_LINE_BYTES = 1 << 20
LISTEN_BACKLOG = 8
class PointerServer:
def __init__(
self,
socket_path: Path | str,
handle: Callable[[Any], dict[str, Any]],
*,
socket_mode: int = 0o660,
) -> None:
self.socket_path = Path(socket_path)
self.handle = handle
self.socket_mode = socket_mode
self._sock: socket.socket | None = None
def listen(self) -> None:
"""Bind and listen. A stale socket file is replaced, not refused:
a crashed driver leaves one behind and the unit must still start."""
self.socket_path.parent.mkdir(parents=True, exist_ok=True)
if self.socket_path.is_socket():
self.socket_path.unlink()
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(str(self.socket_path))
os.chmod(self.socket_path, self.socket_mode)
sock.listen(LISTEN_BACKLOG)
self._sock = sock
log.info("listening on %s", self.socket_path)
def serve_forever(self) -> None:
assert self._sock is not None, "listen() first"
while True:
conn, _ = self._sock.accept()
with conn:
self._serve_connection(conn)
def close(self) -> None:
if self._sock is not None:
self._sock.close()
self._sock = None
self.socket_path.unlink(missing_ok=True)
def _serve_connection(self, conn: socket.socket) -> None:
with conn.makefile("rwb") as stream:
while True:
line = stream.readline(MAX_LINE_BYTES + 1)
if not line:
return
if len(line) > MAX_LINE_BYTES:
_write(stream, {"ok": False, "error": "request line too long"})
return
try:
request = json.loads(line)
except json.JSONDecodeError as exc:
_write(stream, {"ok": False, "error": f"malformed JSON: {exc}"})
continue
_write(stream, self.handle(request))
def _write(stream, response: dict[str, Any]) -> None:
stream.write(json.dumps(response, separators=(",", ":")).encode() + b"\n")
stream.flush()