diff --git a/nix/package.nix b/nix/package.nix index db38247..fb402ca 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -12,13 +12,27 @@ python3.pkgs.buildPythonApplication { build-system = [ python3.pkgs.setuptools ]; + # `hhstream-pointer` is a Wayland client, so it needs libwayland's marshalling. + # The wlr virtual-pointer protocol itself is *not* a build input: the generated + # module is vendored under src/hhstream_pointer/_protocol, so a checkout builds + # without a code generator. See that package's docstring for why, and + # hhstream_pointer._protocol.regenerate for how to refresh it. + dependencies = [ python3.pkgs.pywayland ]; + # Unit tests are wired up in the flake's `checks` so they can run without # installing the package; see docs/CONTRACT.md. doCheck = false; + # Cheap proof that the vendored protocol still binds against this pywayland: + # importing it runs the scanner-generated `_gen_c()` for both interfaces. + pythonImportsCheck = [ + "hhstream_pointer.ops" + "hhstream_pointer._protocol.wlr_virtual_pointer_unstable_v1" + ]; + meta = { description = "Publish a headless Hyprland session's frames on a Unix socket"; license = lib.licenses.mit; mainProgram = "hhstream-server"; }; -} \ No newline at end of file +} diff --git a/pyproject.toml b/pyproject.toml index 8532cae..95b3ead 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,12 @@ name = "hhstream" version = "0.1.0" description = "Publish a headless Hyprland session's frames on a Unix socket" requires-python = ">=3.11" -dependencies = [] +# The frame socket, the CLI and the broker are stdlib-only by policy +# (docs/CONTRACT-sessions.md §6, rule 3). The pointer driver is the one +# exception: talking Wayland means speaking the wire protocol, and +# re-implementing libwayland's marshalling here would be a worse idea than +# a dependency. +dependencies = ["pywayland>=0.4"] [project.scripts] hhstream-server = "hhstream.server:main" @@ -16,6 +21,9 @@ hhstream-client = "hhstream.client:main" hhstream = "hhstream.cli:main" # The session daemon. A separate process on purpose: it outlives every CLI call. hhstreamd = "hhstreamd.__main__:main" +# The pointer driver. Its own process because a Wayland client needs its own +# connection, and a blocked one must not stall the broker. +hhstream-pointer = "hhstream_pointer.__main__:main" [tool.setuptools.packages.find] where = ["src"] \ No newline at end of file diff --git a/src/hhstream_pointer/__init__.py b/src/hhstream_pointer/__init__.py new file mode 100644 index 0000000..d3ed119 --- /dev/null +++ b/src/hhstream_pointer/__init__.py @@ -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. +""" diff --git a/src/hhstream_pointer/__main__.py b/src/hhstream_pointer/__main__.py new file mode 100644 index 0000000..fd99c32 --- /dev/null +++ b/src/hhstream_pointer/__main__.py @@ -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()) diff --git a/src/hhstream_pointer/_protocol/__init__.py b/src/hhstream_pointer/_protocol/__init__.py new file mode 100644 index 0000000..0a07ab7 --- /dev/null +++ b/src/hhstream_pointer/_protocol/__init__.py @@ -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. +""" diff --git a/src/hhstream_pointer/_protocol/regenerate.py b/src/hhstream_pointer/_protocol/regenerate.py new file mode 100644 index 0000000..dbcd99d --- /dev/null +++ b/src/hhstream_pointer/_protocol/regenerate.py @@ -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()) diff --git a/src/hhstream_pointer/_protocol/wayland.py b/src/hhstream_pointer/_protocol/wayland.py new file mode 100644 index 0000000..5c5d2cb --- /dev/null +++ b/src/hhstream_pointer/_protocol/wayland.py @@ -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 diff --git a/src/hhstream_pointer/_protocol/wlr_virtual_pointer_unstable_v1/__init__.py b/src/hhstream_pointer/_protocol/wlr_virtual_pointer_unstable_v1/__init__.py new file mode 100644 index 0000000..1304f39 --- /dev/null +++ b/src/hhstream_pointer/_protocol/wlr_virtual_pointer_unstable_v1/__init__.py @@ -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 diff --git a/src/hhstream_pointer/_protocol/wlr_virtual_pointer_unstable_v1/zwlr_virtual_pointer_manager_v1.py b/src/hhstream_pointer/_protocol/wlr_virtual_pointer_unstable_v1/zwlr_virtual_pointer_manager_v1.py new file mode 100644 index 0000000..6fb23d5 --- /dev/null +++ b/src/hhstream_pointer/_protocol/wlr_virtual_pointer_unstable_v1/zwlr_virtual_pointer_manager_v1.py @@ -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 diff --git a/src/hhstream_pointer/_protocol/wlr_virtual_pointer_unstable_v1/zwlr_virtual_pointer_v1.py b/src/hhstream_pointer/_protocol/wlr_virtual_pointer_unstable_v1/zwlr_virtual_pointer_v1.py new file mode 100644 index 0000000..247fa36 --- /dev/null +++ b/src/hhstream_pointer/_protocol/wlr_virtual_pointer_unstable_v1/zwlr_virtual_pointer_v1.py @@ -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 diff --git a/src/hhstream_pointer/backend.py b/src/hhstream_pointer/backend.py new file mode 100644 index 0000000..c1fce8b --- /dev/null +++ b/src/hhstream_pointer/backend.py @@ -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-`` 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 diff --git a/src/hhstream_pointer/buttons.py b/src/hhstream_pointer/buttons.py new file mode 100644 index 0000000..6dd5f99 --- /dev/null +++ b/src/hhstream_pointer/buttons.py @@ -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 diff --git a/src/hhstream_pointer/ops.py b/src/hhstream_pointer/ops.py new file mode 100644 index 0000000..03c6c6b --- /dev/null +++ b/src/hhstream_pointer/ops.py @@ -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": ""}``; +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 diff --git a/src/hhstream_pointer/server.py b/src/hhstream_pointer/server.py new file mode 100644 index 0000000..df87e4c --- /dev/null +++ b/src/hhstream_pointer/server.py @@ -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() diff --git a/src/hhstreamd/pointer.py b/src/hhstreamd/pointer.py new file mode 100644 index 0000000..e293587 --- /dev/null +++ b/src/hhstreamd/pointer.py @@ -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))) diff --git a/tests/pointer/conftest.py b/tests/pointer/conftest.py new file mode 100644 index 0000000..75f740d --- /dev/null +++ b/tests/pointer/conftest.py @@ -0,0 +1,42 @@ +"""Fixtures for the pointer tests. Nothing here sleeps and nothing connects. + +``src`` goes on the path because these tests run straight out of a checkout +(``nix develop -c python -m pytest tests/pointer -q``) rather than against an +installed package. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src")) + +from hhstreamd.pointer import PointerLease # noqa: E402 + + +class FakeClock: + """The injected clock. Tests move time; time never moves on its own.""" + + def __init__(self, now: float = 1000.0) -> None: + self.now = float(now) + + def __call__(self) -> float: + return self.now + + def advance(self, seconds: float) -> None: + self.now += float(seconds) + + +@pytest.fixture +def clock() -> FakeClock: + return FakeClock() + + +@pytest.fixture +def lease(clock: FakeClock) -> PointerLease: + """Short deadlines so the arithmetic in a failing test is readable.""" + + return PointerLease(ttl_s=30.0, max_s=300.0, clock=clock) diff --git a/tests/pointer/test_lease.py b/tests/pointer/test_lease.py new file mode 100644 index 0000000..ccda2fe --- /dev/null +++ b/tests/pointer/test_lease.py @@ -0,0 +1,245 @@ +"""The lease state machine (CONTRACT-sessions.md §3.3). + +There is one cursor on this compositor and every virtual pointer writes to it, +so the lease is the only thing standing between two agents and a mouse that +jumps between their windows. These tests are therefore about refusal as much as +about success: who is turned away, and with what name attached. +""" + +from __future__ import annotations + +import pytest + +from hhstreamd.pointer import Bookmark, LeaseBusy, LeaseInvalid, PointerLease + + +def test_unheld_lease_reports_nothing_held(lease): + assert lease.state() == { + "holder": None, + "since": None, + "lease_id": None, + "expires_at": None, + } + assert lease.pressed() == [] + assert lease.expire() is None + + +def test_acquire_then_release_is_a_full_cycle(lease, clock): + lease_id = lease.acquire("alpha") + assert lease.state() == { + "holder": "alpha", + "since": 1000.0, + "lease_id": lease_id, + "expires_at": 1030.0, + } + + outcome = lease.release("alpha", lease_id, "done") + assert outcome.reason == "done" + assert outcome.bookmark is None + assert outcome.buttons_lifted == [] + assert lease.state()["holder"] is None + + # And the pointer is free again, to a different session. + assert lease.acquire("beta") != lease_id + + +def test_second_holder_is_rejected_by_name(lease): + lease.acquire("alpha") + with pytest.raises(LeaseBusy) as caught: + lease.acquire("beta") + assert caught.value.holder == "alpha" + assert "alpha" in str(caught.value) + + +def test_reacquiring_as_the_same_session_is_also_busy(lease): + """A second lease_id for one session would invalidate the first mid-drag.""" + + lease.acquire("alpha") + with pytest.raises(LeaseBusy) as caught: + lease.acquire("alpha") + assert caught.value.holder == "alpha" + + +def test_a_verb_from_a_non_holder_is_invalid(lease): + lease_id = lease.acquire("alpha") + with pytest.raises(LeaseInvalid, match="held by alpha"): + lease.refresh("beta", lease_id) + with pytest.raises(LeaseInvalid, match="held by alpha"): + lease.release("beta", lease_id, "theft") + with pytest.raises(LeaseInvalid, match="held by alpha"): + lease.press("beta", "left") + with pytest.raises(LeaseInvalid, match="held by alpha"): + lease.unpress("beta", "left") + + +def test_a_verb_on_an_unheld_lease_is_invalid(lease): + with pytest.raises(LeaseInvalid, match="no pointer lease"): + lease.refresh("alpha", "whatever") + with pytest.raises(LeaseInvalid, match="no pointer lease"): + lease.press("alpha", "left") + + +def test_a_stale_lease_id_is_rejected(lease, clock): + """The session is right and the id is not: the classic retry-after-expiry.""" + + first = lease.acquire("alpha") + lease.release("alpha", first, "done") + second = lease.acquire("alpha") + assert second != first + + with pytest.raises(LeaseInvalid, match="stale lease_id"): + lease.refresh("alpha", first) + with pytest.raises(LeaseInvalid, match="stale lease_id"): + lease.release("alpha", first, "late") + with pytest.raises(LeaseInvalid, match="stale lease_id"): + lease.mark("alpha", first, Bookmark(0.5, 0.5, "hh-a", "2026-10-01T00:00:00Z")) + + # The real holder is untouched by the stale caller's attempts. + lease.refresh("alpha", second) + + +def test_refresh_pushes_the_idle_deadline_but_not_the_hard_cap(lease, clock): + lease_id = lease.acquire("alpha") + clock.advance(20.0) + lease.refresh("alpha", lease_id) + assert lease.state()["expires_at"] == 1050.0 + assert lease.expire() is None + + # Keep refreshing inside the idle window, right up to the hard cap. + while clock.now < 1299.0: + clock.advance(min(20.0, 1299.0 - clock.now)) + lease.refresh("alpha", lease_id) + assert lease.expire() is None + assert lease.state()["expires_at"] == 1329.0 + + clock.advance(1.0) # t = 1300, the hard deadline, which did not move + info = lease.expire() + assert info is not None + assert info.hard_deadline == 1300.0 + + +def test_ttl_expiry_releases_the_lease(lease, clock): + lease_id = lease.acquire("alpha") + clock.advance(29.9) + assert lease.expire() is None + + clock.advance(0.1) # exactly at the deadline, which is inclusive + info = lease.expire() + assert info is not None + assert info.session_id == "alpha" + assert info.lease_id == lease_id + assert info.acquired_at == 1000.0 + assert info.expires_at == 1030.0 + assert info.hard_deadline == 1300.0 + + assert lease.state()["holder"] is None + assert lease.expire() is None # idempotent: nothing left to reap + + +def test_hard_cap_expiry_beats_an_endless_refresh_loop(clock): + lease = PointerLease(ttl_s=30.0, max_s=100.0, clock=clock) + lease_id = lease.acquire("alpha") + for _ in range(9): + clock.advance(10.0) + lease.refresh("alpha", lease_id) + assert lease.expire() is None, "the idle clock keeps being pushed out" + + clock.advance(10.0) # t = 1100, the hard deadline + info = lease.expire() + assert info is not None + assert info.hard_deadline == 1100.0 + # The idle deadline was still in the future; the cap is what fired. + assert info.expires_at > info.hard_deadline + + +def test_an_expired_lease_cannot_be_refreshed_back_to_life(lease, clock): + lease_id = lease.acquire("alpha") + clock.advance(31.0) + with pytest.raises(LeaseInvalid, match="expired"): + lease.refresh("alpha", lease_id) + # Still held, because only expire() releases: the broker has to be told so + # it can lift buttons on the driver. + assert lease.state()["holder"] == "alpha" + assert lease.expire() is not None + + +def test_expire_does_nothing_when_nothing_is_due(lease, clock): + lease.acquire("alpha") + clock.advance(29.0) + assert lease.expire() is None + assert lease.state()["holder"] == "alpha" + + +def test_press_and_lift_one_button(lease): + lease_id = lease.acquire("alpha") + lease.press("alpha", "left") + assert lease.pressed() == ["left"] + assert lease.unpress("alpha", "left") == ["left"] + assert lease.pressed() == [] + assert lease.release("alpha", lease_id, "done").buttons_lifted == [] + + +def test_lifting_a_button_that_is_not_down_reports_nothing(lease): + lease.acquire("alpha") + assert lease.unpress("alpha", "left") == [] + lease.press("alpha", "left") + lease.unpress("alpha", "left") + assert lease.unpress("alpha", "left") == [] + + +def test_multiple_buttons_are_tracked_and_lifted_independently(lease): + lease_id = lease.acquire("alpha") + lease.press("alpha", "left") + lease.press("alpha", "right") + lease.press("alpha", "middle") + assert lease.pressed() == ["left", "right", "middle"] + + assert lease.unpress("alpha", "right") == ["right"] + assert lease.pressed() == ["left", "middle"] + + # A release lifts whatever is still down, oldest first. + outcome = lease.release("alpha", lease_id, "timeout") + assert outcome.buttons_lifted == ["left", "middle"] + assert outcome.reason == "timeout" + assert lease.pressed() == [] + + +def test_pressing_twice_leaves_one_button_down(lease): + lease.acquire("alpha") + lease.press("alpha", "left") + lease.press("alpha", "left") + assert lease.pressed() == ["left"] + assert lease.unpress("alpha", "left") == ["left"] + assert lease.pressed() == [] + + +def test_expiry_does_not_leak_buttons_to_the_next_holder(lease, clock): + lease.acquire("alpha") + lease.press("alpha", "left") + clock.advance(31.0) + assert lease.expire() is not None + assert lease.pressed() == [] + + lease.acquire("beta") + assert lease.pressed() == [] + + +def test_bookmark_survives_to_the_release_outcome(lease): + lease_id = lease.acquire("alpha") + mark = Bookmark(x=0.25, y=0.75, output="hh-alpha", at="2026-10-01T12:00:00Z") + lease.mark("alpha", lease_id, mark) + assert lease.release("alpha", lease_id, "done").bookmark == mark + + +def test_a_new_lease_starts_without_the_previous_bookmark(lease): + first = lease.acquire("alpha") + lease.mark("alpha", first, Bookmark(0.25, 0.75, "hh-alpha", "2026-10-01T12:00:00Z")) + lease.release("alpha", first, "done") + + second = lease.acquire("beta") + assert lease.release("beta", second, "done").bookmark is None + + +def test_defaults_match_the_contract(): + lease = PointerLease() + assert (lease.ttl_s, lease.max_s) == (30.0, 300.0) diff --git a/tests/pointer/test_ops.py b/tests/pointer/test_ops.py new file mode 100644 index 0000000..ecbe3f0 --- /dev/null +++ b/tests/pointer/test_ops.py @@ -0,0 +1,244 @@ +"""The driver's protocol (CONTRACT-sessions.md §3.4). + +The dispatcher is tested against a recording sink rather than a compositor, so +these assertions are about the exact events that would go on the wire: which +pointer they go to, in what order, and which requests are refused instead. + +The driver is an executor. It is *not* tested for serialisation, authority, or +any notion of who may ask — none of that is here, on purpose. The lease is in +``hhstreamd.pointer`` and the broker owns it. +""" + +from __future__ import annotations + +import pytest + +from hhstream_pointer import buttons +from hhstream_pointer.ops import Dispatcher + +LEFT = buttons.CODES["left"] +RIGHT = buttons.CODES["right"] +DOWN = buttons.STATES["down"] +UP = buttons.STATES["up"] + + +class RecordingSink: + """Every call, in order, as a tuple. Nothing else.""" + + def __init__(self) -> None: + self.calls: list[tuple] = [] + + def motion_absolute(self, output, x, y): + self.calls.append(("motion", output, x, y)) + + def button(self, output, code, state): + self.calls.append(("button", output, code, state)) + + def frame(self, output): + self.calls.append(("frame", output)) + + +class FailingSink(RecordingSink): + """A sink whose motion raises, standing in for an output that vanished.""" + + class Boom(Exception): + pass + + def motion_absolute(self, output, x, y): + raise FailingSink.Boom(output) + + +@pytest.fixture +def sink() -> RecordingSink: + return RecordingSink() + + +@pytest.fixture +def driver(sink) -> Dispatcher: + return Dispatcher(sink) + + +def warp(driver, output="hh-alpha", x=0.5, y=0.5): + return driver.handle({"op": "warp", "output": output, "x": x, "y": y}) + + +# -- happy paths ------------------------------------------------------------ + + +def test_warp_sends_one_motion_and_no_implicit_frame(driver, sink): + assert warp(driver, x=0.42, y=0.61) == {"ok": True} + assert sink.calls == [("motion", "hh-alpha", 0.42, 0.61)] + + +def test_frame_is_a_separate_op(driver, sink): + warp(driver) + assert driver.handle({"op": "frame"}) == {"ok": True} + assert sink.calls[-1] == ("frame", "hh-alpha") + + +def test_a_click_is_warp_button_frame(driver, sink): + warp(driver, x=0.25, y=0.75) + driver.handle({"op": "button", "button": "left", "state": "down"}) + driver.handle({"op": "button", "button": "left", "state": "up"}) + driver.handle({"op": "frame"}) + assert sink.calls == [ + ("motion", "hh-alpha", 0.25, 0.75), + ("button", "hh-alpha", LEFT, DOWN), + ("button", "hh-alpha", LEFT, UP), + ("frame", "hh-alpha"), + ] + assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []} + + +def test_the_boundary_coordinates_are_accepted(driver, sink): + assert warp(driver, x=0.0, y=0.0) == {"ok": True} + assert warp(driver, x=1.0, y=1.0) == {"ok": True} + # Integers are numbers too; 0 and 1 are the corners. + assert warp(driver, x=0, y=1) == {"ok": True} + assert [c[2:] for c in sink.calls] == [(0.0, 0.0), (1.0, 1.0), (0.0, 1.0)] + + +def test_buttons_follow_the_last_warp_not_the_first(driver, sink): + warp(driver, output="hh-alpha") + warp(driver, output="hh-beta") + driver.handle({"op": "button", "button": "left", "state": "down"}) + assert sink.calls[-1] == ("button", "hh-beta", LEFT, DOWN) + + +# -- pressed / release_all -------------------------------------------------- + + +def test_pressed_reports_what_is_down_oldest_first(driver): + warp(driver) + driver.handle({"op": "button", "button": "right", "state": "down"}) + driver.handle({"op": "button", "button": "left", "state": "down"}) + assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": ["right", "left"]} + + +def test_release_all_lifts_everything_and_frames_once(driver, sink): + warp(driver) + driver.handle({"op": "button", "button": "left", "state": "down"}) + driver.handle({"op": "button", "button": "right", "state": "down"}) + sink.calls.clear() + + assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]} + assert sink.calls == [ + ("button", "hh-alpha", LEFT, UP), + ("button", "hh-alpha", RIGHT, UP), + ("frame", "hh-alpha"), + ] + assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []} + + +def test_release_all_on_a_quiet_driver_lifts_nothing(driver, sink): + assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []} + assert sink.calls == [] + + +def test_release_all_lifts_through_the_pointer_the_press_went_to(driver, sink): + """The expiry path: the broker lifts after the cursor has moved on. + + A button pressed on one output must come up on that output's pointer, not + on whatever is aimed now, or the first session keeps a stuck drag. + """ + + warp(driver, output="hh-alpha") + driver.handle({"op": "button", "button": "left", "state": "down"}) + warp(driver, output="hh-beta") + driver.handle({"op": "button", "button": "right", "state": "down"}) + sink.calls.clear() + + assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]} + assert sink.calls == [ + ("button", "hh-alpha", LEFT, UP), + ("button", "hh-beta", RIGHT, UP), + ("frame", "hh-alpha"), + ("frame", "hh-beta"), + ] + + +def test_a_lifted_button_is_forgotten(driver): + warp(driver) + driver.handle({"op": "button", "button": "left", "state": "down"}) + driver.handle({"op": "button", "button": "left", "state": "up"}) + assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []} + + +def test_every_known_button_name_round_trips(driver, sink): + warp(driver) + for name in buttons.NAMES: + assert driver.handle({"op": "button", "button": name, "state": "down"}) == {"ok": True} + assert driver.handle({"op": "pressed"})["buttons"] == list(buttons.NAMES) + assert driver.handle({"op": "release_all"})["lifted"] == list(buttons.NAMES) + + +# -- refusals --------------------------------------------------------------- + + +def test_button_before_any_warp_is_refused(driver, sink): + assert driver.handle({"op": "button", "button": "left", "state": "down"}) == { + "ok": False, + "error": "no output is aimed; warp before button or frame", + } + assert sink.calls == [] + + +def test_frame_before_any_warp_is_refused(driver, sink): + assert driver.handle({"op": "frame"})["ok"] is False + assert sink.calls == [] + + +def test_a_failed_warp_does_not_change_the_aim(): + """Otherwise the next button lands on a session we never reached.""" + + driver = Dispatcher(RecordingSink()) + warp(driver, output="hh-alpha") + + driver._sink = FailingSink() + with pytest.raises(FailingSink.Boom): + warp(driver, output="hh-beta") + + driver._sink = sink = RecordingSink() + driver.handle({"op": "button", "button": "left", "state": "down"}) + assert sink.calls == [("button", "hh-alpha", LEFT, DOWN)] + + +@pytest.mark.parametrize( + "request_, fragment", + [ + ({}, "no 'op'"), + ({"op": 7}, "no 'op'"), + ({"op": "nonsense"}, "unknown op 'nonsense'"), + ({"op": "warp", "x": 0.5, "y": 0.5}, "'output' must be"), + ({"op": "warp", "output": "", "x": 0.5, "y": 0.5}, "'output' must be"), + ({"op": "warp", "output": "hh-a", "y": 0.5}, "'x' must be a number"), + ({"op": "warp", "output": "hh-a", "x": "0.5", "y": 0.5}, "'x' must be a number"), + ({"op": "warp", "output": "hh-a", "x": True, "y": 0.5}, "'x' must be a number"), + ({"op": "warp", "output": "hh-a", "x": 1.5, "y": 0.5}, "outside 0..1"), + ({"op": "warp", "output": "hh-a", "x": 0.5, "y": -0.1}, "outside 0..1"), + ({"op": "button", "state": "down"}, "'button' must be a string"), + ({"op": "button", "button": "left"}, "'state' must be"), + ({"op": "button", "button": "pinky", "state": "down"}, "unknown button 'pinky'"), + ({"op": "button", "button": "left", "state": "sideways"}, "unknown button state"), + ], +) +def test_malformed_requests_are_answered_not_fatal(sink, request_, fragment): + driver = Dispatcher(sink) + # Aim first, so a refusal is about the field under test rather than the aim. + warp(driver) + sink.calls.clear() + + response = driver.handle(request_) + assert response["ok"] is False + assert fragment in response["error"] + assert sink.calls == [], "a refused request must emit nothing" + + +@pytest.mark.parametrize("request_", [[], "warp", None, 7]) +def test_a_non_object_request_is_refused(driver, request_): + assert driver.handle(request_)["ok"] is False + assert "must be a JSON object" in driver.handle(request_)["error"] + + +def test_the_contracts_five_ops_are_exactly_what_is_implemented(): + assert set(Dispatcher._ops) == {"warp", "button", "frame", "pressed", "release_all"} diff --git a/tests/pointer/test_server.py b/tests/pointer/test_server.py new file mode 100644 index 0000000..767b095 --- /dev/null +++ b/tests/pointer/test_server.py @@ -0,0 +1,136 @@ +"""The driver's socket: framing, not logic. + +The dispatcher is tested next door; what is proved here is that a real +``AF_UNIX`` connection carrying newline-delimited JSON gets one response object +per request line, that a garbled line is answered rather than fatal, and that +the connection stays open for the next request — which matters because the +broker holds one connection for the life of a lease. +""" + +from __future__ import annotations + +import json +import shutil +import socket +import tempfile +import threading +from pathlib import Path + +import pytest + +from hhstream_pointer.ops import Dispatcher +from hhstream_pointer.server import PointerServer + +from test_ops import RecordingSink + +#: Linux's sun_path is 108 bytes including the NUL, and pytest's tmp_path can +#: exceed it, so the socket lives in a shallow directory of its own. +SUN_PATH_MAX = 107 + + +@pytest.fixture +def connection(): + """A listening driver and a connected client, torn down together.""" + + directory = Path(tempfile.mkdtemp(prefix="hhp")) + path = directory / "p.sock" + if len(str(path).encode()) > SUN_PATH_MAX: + pytest.skip(f"socket path too long for AF_UNIX: {path}") + + sink = RecordingSink() + server = PointerServer(path, Dispatcher(sink).handle) + server.listen() + thread = threading.Thread(target=_serve_once, args=(server,), daemon=True) + thread.start() + + client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + client.settimeout(5.0) + client.connect(str(path)) + try: + yield _Client(client), sink + finally: + client.close() + thread.join(timeout=5.0) + server.close() + shutil.rmtree(directory, ignore_errors=True) + + +def _serve_once(server: PointerServer) -> None: + conn, _ = server._sock.accept() + with conn: + server._serve_connection(conn) + + +class _Client: + def __init__(self, sock: socket.socket) -> None: + self._stream = sock.makefile("rwb") + + def call(self, request: dict) -> dict: + self._stream.write(json.dumps(request).encode() + b"\n") + self._stream.flush() + return json.loads(self._stream.readline()) + + def send_raw(self, line: bytes) -> dict: + self._stream.write(line) + self._stream.flush() + return json.loads(self._stream.readline()) + + +def test_one_request_gets_one_response(connection): + client, _ = connection + assert client.call({"op": "pressed"}) == {"ok": True, "buttons": []} + + +def test_many_requests_share_one_connection(connection): + client, sink = connection + assert client.call({"op": "warp", "output": "hh-a", "x": 0.5, "y": 0.5}) == {"ok": True} + assert client.call({"op": "button", "button": "left", "state": "down"}) == {"ok": True} + assert client.call({"op": "frame"}) == {"ok": True} + assert client.call({"op": "pressed"}) == {"ok": True, "buttons": ["left"]} + assert client.call({"op": "release_all"}) == {"ok": True, "lifted": ["left"]} + assert [c[0] for c in sink.calls] == ["motion", "button", "frame", "button", "frame"] + + +def test_a_rejected_request_leaves_the_connection_usable(connection): + client, _ = connection + assert client.call({"op": "nonsense"})["ok"] is False + assert client.call({"op": "pressed"})["ok"] is True + + +def test_malformed_json_is_answered_not_fatal(connection): + client, _ = connection + response = client.send_raw(b"{not json\n") + assert response["ok"] is False + assert "malformed JSON" in response["error"] + # Still talking. + assert client.call({"op": "pressed"})["ok"] is True + + +def test_an_oversized_line_is_refused(connection): + from hhstream_pointer.server import MAX_LINE_BYTES + + client, _ = connection + response = client.send_raw(b'{"op":"' + b"x" * MAX_LINE_BYTES + b'"}\n') + assert response == {"ok": False, "error": "request line too long"} + + +def test_listen_replaces_a_stale_socket_file(): + """A crashed driver leaves the file behind; the unit must still start.""" + + directory = Path(tempfile.mkdtemp(prefix="hhp")) + path = directory / "p.sock" + if len(str(path).encode()) > SUN_PATH_MAX: + pytest.skip("socket path too long for AF_UNIX") + try: + first = PointerServer(path, Dispatcher(RecordingSink()).handle) + first.listen() + first._sock.close() # the file survives; the listener does not + + second = PointerServer(path, Dispatcher(RecordingSink()).handle) + second.listen() + assert path.is_socket() + assert path.stat().st_mode & 0o777 == 0o660 + second.close() + assert not path.exists() + finally: + shutil.rmtree(directory, ignore_errors=True) diff --git a/tests/pointer/test_vendored_protocol.py b/tests/pointer/test_vendored_protocol.py new file mode 100644 index 0000000..5d4c143 --- /dev/null +++ b/tests/pointer/test_vendored_protocol.py @@ -0,0 +1,94 @@ +"""The vendored protocol and the packaging around it. + +The whole point of slice D is that coordinates are *output-local*, and the only +thing that makes them so is ``create_virtual_pointer_with_output``, which exists +at version 2 of ``zwlr_virtual_pointer_manager_v1`` and not at version 1. So +the version is asserted here, cheaply, on the generated source — a regeneration +against an older XML would otherwise be a silent downgrade of the one guarantee +the slice exists to provide. + +The pywayland import is checked when pywayland is present and skipped when it is +not: the dev shell has no pywayland, the built package does, and this file is +run in both. +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest + +HAVE_PYWAYLAND = importlib.util.find_spec("pywayland") is not None + +# Located through the import system, not through a path relative to this file, +# so the suite is the same whether it runs in a checkout or against the +# installed package in a build sandbox. +_spec = importlib.util.find_spec("hhstream_pointer") +assert _spec is not None and _spec.origin, "hhstream_pointer is not importable" +PACKAGE = Path(_spec.origin).parent +PROTOCOL_DIR = PACKAGE / "_protocol/wlr_virtual_pointer_unstable_v1" +MANAGER = PROTOCOL_DIR / "zwlr_virtual_pointer_manager_v1.py" + +#: Only present in a checkout; a build sandbox gets the test directory alone. +PYPROJECT = Path(__file__).resolve().parents[2] / "pyproject.toml" + + +def test_the_generated_protocol_is_vendored(): + assert (PROTOCOL_DIR / "__init__.py").is_file() + assert MANAGER.is_file() + assert (PROTOCOL_DIR / "zwlr_virtual_pointer_v1.py").is_file() + # Every vendored file is scanner output; a hand-edit should be noticed. + for path in PROTOCOL_DIR.glob("*.py"): + assert path.read_text().startswith("# This file has been autogenerated") + + +def test_the_manager_is_version_2_with_the_output_request(): + source = MANAGER.read_text() + assert " version = 2\n" in source + assert "def create_virtual_pointer_with_output(self, seat" in source + assert "output: WlOutput | None" in source + + +def test_the_shim_resolves_the_generated_relative_import(): + assert "from ..wayland import WlOutput" in MANAGER.read_text() + shim = (PROTOCOL_DIR.parent / "wayland.py").read_text() + assert "from pywayland.protocol.wayland import WlOutput, WlSeat" in shim + + +@pytest.mark.skipif(not PYPROJECT.is_file(), reason="not running from a checkout") +def test_pyproject_declares_the_entry_point_and_the_dependency(): + pyproject = PYPROJECT.read_text() + assert 'hhstream-pointer = "hhstream_pointer.__main__:main"' in pyproject + assert "pywayland" in pyproject + + +@pytest.mark.skipif( + not HAVE_PYWAYLAND, + reason="pywayland is not in this environment (it is in the built package)", +) +def test_the_protocol_binds_against_the_installed_pywayland(): + from hhstream_pointer._protocol.wlr_virtual_pointer_unstable_v1 import ( + ZwlrVirtualPointerManagerV1, + ZwlrVirtualPointerV1, + ) + + assert ZwlrVirtualPointerManagerV1.version == 2 + assert ZwlrVirtualPointerV1.version == 2 + assert hasattr( + ZwlrVirtualPointerManagerV1.proxy_class, "create_virtual_pointer_with_output" + ) + + +@pytest.mark.skipif( + not HAVE_PYWAYLAND, + reason="pywayland is not in this environment (it is in the built package)", +) +def test_the_backend_refuses_a_version_1_manager(): + from hhstream_pointer.backend import MANAGER_VERSION, ManagerTooOld + + assert MANAGER_VERSION == 2 + message = str(ManagerTooOld(1)) + assert "version 1" in message + assert "create_virtual_pointer_with_output" in message + assert "Refusing to start" in message diff --git a/tests/pointer/test_window_to_absolute.py b/tests/pointer/test_window_to_absolute.py new file mode 100644 index 0000000..f11b6af --- /dev/null +++ b/tests/pointer/test_window_to_absolute.py @@ -0,0 +1,93 @@ +"""Aiming arithmetic (CONTRACT-sessions.md §3.3). + +An agent says "click 40 pixels into this window"; the virtual pointer wants a +fraction of its output. Everything between is this one function, and the case +that breaks in the field is the last one: a window on an output that is not at +the layout origin. +""" + +from __future__ import annotations + +import pytest + +from hhstreamd.pointer import window_to_absolute + +#: A 1280x720 output at the origin, and a 640x480 window centred in it. +ORIGIN_MONITOR = (0, 0, 1280, 720) +CENTRED_WINDOW = (320, 120, 640, 480) + + +def test_window_centre_is_the_window_centre_not_the_monitor_centre(): + # (320 + 320) / 1280 = 0.5 and (120 + 240) / 720 = 0.5 — the window happens + # to be centred, so this also pins down the easy reading of the maths. + assert window_to_absolute((320, 240), CENTRED_WINDOW, ORIGIN_MONITOR) == (0.5, 0.5) + + +def test_an_off_centre_window_centre_is_not_the_monitor_centre(): + window = (0, 0, 640, 480) + assert window_to_absolute((320, 240), window, ORIGIN_MONITOR) == (0.25, 1 / 3) + + +@pytest.mark.parametrize( + "corner, expected", + [ + ((0, 0), (320 / 1280, 120 / 720)), # top-left + ((640, 0), (960 / 1280, 120 / 720)), # top-right + ((0, 480), (320 / 1280, 600 / 720)), # bottom-left + ((640, 480), (960 / 1280, 600 / 720)), # bottom-right + ], +) +def test_all_four_window_corners(corner, expected): + assert window_to_absolute(corner, CENTRED_WINDOW, ORIGIN_MONITOR) == expected + + +def test_the_far_edge_is_inside(): + """``(w, h)`` is the bottom-right corner; rejecting it makes it unaimable.""" + + assert window_to_absolute((640, 480), CENTRED_WINDOW, ORIGIN_MONITOR) == (0.75, 600 / 720) + + +@pytest.mark.parametrize("point", [(-1, 0), (0, -1), (641, 0), (0, 481), (641, 481)]) +def test_a_point_outside_the_window_raises(point): + with pytest.raises(ValueError, match="outside window"): + window_to_absolute(point, CENTRED_WINDOW, ORIGIN_MONITOR) + + +def test_a_window_on_the_second_monitor_uses_that_monitors_frame(): + """The offset case. + + Two 1280x720 outputs side by side; the window is on the right-hand one, so + its global x starts at 1280. Without subtracting the monitor origin every + coordinate would exceed 1.0, clamp, and quietly aim at the far right edge — + a click that happens, in the wrong place. + """ + + monitor = (1280, 0, 1280, 720) + window = (1280 + 320, 120, 640, 480) + assert window_to_absolute((320, 240), window, monitor) == (0.5, 0.5) + assert window_to_absolute((0, 0), window, monitor) == (320 / 1280, 120 / 720) + assert window_to_absolute((640, 480), window, monitor) == (960 / 1280, 600 / 720) + + +def test_a_vertically_stacked_monitor_uses_its_own_origin(): + monitor = (0, 720, 1280, 720) + window = (0, 720, 1280, 720) + assert window_to_absolute((640, 360), window, monitor) == (0.5, 0.5) + assert window_to_absolute((0, 0), window, monitor) == (0.0, 0.0) + + +def test_a_window_hanging_off_the_monitor_clamps_rather_than_overflowing(): + """Hyprland will place a window partly off-screen; 1.0 is the honest answer + for "as far as this output goes".""" + + window = (1000, 600, 640, 480) + assert window_to_absolute((640, 480), window, ORIGIN_MONITOR) == (1.0, 1.0) + # Negative global coordinates clamp at the other end. + assert window_to_absolute((0, 0), (-100, -50, 640, 480), ORIGIN_MONITOR) == (0.0, 0.0) + + +def test_a_degenerate_window_or_monitor_raises(): + with pytest.raises(ValueError, match="window has no area"): + window_to_absolute((0, 0), (0, 0, 0, 480), ORIGIN_MONITOR) + with pytest.raises(ValueError, match="monitor has no area"): + window_to_absolute((0, 0), CENTRED_WINDOW, (0, 0, 1280, 0))