Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d414d76bc |
No files matched your search
+15
-1
@@ -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";
|
||||
};
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -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"]
|
||||
@@ -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.
|
||||
"""
|
||||
@@ -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())
|
||||
@@ -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
|
||||
+117
@@ -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
|
||||
+267
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -1,304 +0,0 @@
|
||||
"""Spatial containers: one headless output and one workspace per session.
|
||||
|
||||
A session used to be a process group and nothing more, so every application
|
||||
landed on whichever workspace the compositor happened to be showing. Two
|
||||
sessions then shared a screen: a capture of one caught the other's windows, and
|
||||
a pointer aimed at one could land in the other. A container fixes that by
|
||||
giving the session a place of its own — a dedicated headless output, a numbered
|
||||
workspace bound to that output as its default and marked persistent so it
|
||||
survives the window closing, and a window rule that pins anything the session
|
||||
spawns there.
|
||||
|
||||
**This module computes command lines and nothing else.** It does not run them,
|
||||
does not talk to a socket, does not read a file, does not look at a clock and
|
||||
does not import :mod:`hhstreamd.ipc`. That separation is deliberate: the
|
||||
compositor is the part that cannot be tested without a compositor, so every
|
||||
decision that *can* be made in a pure function is made here, where a unit test
|
||||
can assert the exact argv list. The broker executes what comes back.
|
||||
|
||||
Three properties the callers depend on:
|
||||
|
||||
**Byte-identical output for identical arguments.** The ``create`` list is
|
||||
emitted in a fixed order — create the output, bind the workspace, pin the
|
||||
window, then set the mode — that does not depend on the inputs, and no set or
|
||||
dict is ever iterated to build a command. The only thing a caller can vary is
|
||||
what it passes in, in the order the signature names: nothing else here is a
|
||||
source of order. So ``container_plan`` is safe to call twice and diff, which is
|
||||
how ``container.reconcile`` decides whether a live container matches its plan.
|
||||
|
||||
**Argv lists, never strings.** These values reach a compositor that will act on
|
||||
them, so there is no shell, no quoting and no interpolation of a caller's string
|
||||
into a command *word*. The one place caller data lands inside a word is a rule
|
||||
body (``workspace 1000, monitor:hh-x``), where a comma or a newline would end
|
||||
one field and begin another — which is why the validation below is a control and
|
||||
not a style preference.
|
||||
|
||||
**Validation raises, and names the value.** A session id that is not
|
||||
``[a-z0-9-]``, a non-positive size, an empty app id: all :class:`ValueError`.
|
||||
The broker mints its own ids and sizes, so a rejection here means a bug upstream
|
||||
of us, and a message that quotes the offending value is what makes that bug
|
||||
findable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
#: Every output this broker creates carries it. A start-up scan uses the prefix
|
||||
#: to tell its own orphans — outputs left behind by a crash — from the outputs a
|
||||
#: human or another tool made, which it must not remove.
|
||||
OUTPUT_PREFIX = "hh-"
|
||||
|
||||
#: Session ids as the broker mints them. Deliberately narrower than "a safe
|
||||
#: command word": lowercase, digits and the dash, so the name is also a legal
|
||||
#: Hyprland output name and a regex literal with nothing to escape.
|
||||
SESSION_ID_RE = re.compile(r"\A[a-z0-9-]+\Z")
|
||||
|
||||
#: An application's window class, which we do not mint — it is whatever the
|
||||
#: toolkit reports, so it has to allow the shapes real classes take
|
||||
#: (``org.gnome.Nautilus``, ``Alacritty``, ``firefox-esr``). It still excludes
|
||||
#: every character that could end a field in a rule body or a line in the
|
||||
#: request: comma, space, quote, newline, ``$``, ``^``.
|
||||
APP_ID_RE = re.compile(r"\A[A-Za-z0-9._+-]+\Z")
|
||||
|
||||
|
||||
class NoSlots(Exception):
|
||||
"""The workspace band is full. The caller refuses the session; it never reuses."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ContainerPlan:
|
||||
"""What a session's container is, and the two command lists that realise it.
|
||||
|
||||
``create`` and ``teardown`` are complete argv lists in the order they must
|
||||
run. ``teardown`` is not the reverse of ``create``: removing the output is
|
||||
enough, because the workspace and window rules are keywords that die with
|
||||
the compositor's configuration and name an output that no longer exists.
|
||||
"""
|
||||
|
||||
output: str
|
||||
workspace: int
|
||||
mode: tuple[int, int]
|
||||
create: list[list[str]]
|
||||
teardown: list[list[str]]
|
||||
|
||||
|
||||
def output_name(session_id: str) -> str:
|
||||
"""``hh-<session-id>`` — the name of the session's headless output."""
|
||||
|
||||
return OUTPUT_PREFIX + _checked_session_id(session_id)
|
||||
|
||||
|
||||
def contains_output(name: str) -> bool:
|
||||
"""True only for an output name this broker could have created.
|
||||
|
||||
Used by the start-up scan, which removes what it recognises. So it is
|
||||
strict in the direction that matters: a bare ``hh-``, a trailing newline or
|
||||
an upper-case suffix is *not* one of ours, and a scan that answered True
|
||||
would delete someone else's output.
|
||||
"""
|
||||
|
||||
if not name.startswith(OUTPUT_PREFIX):
|
||||
return False
|
||||
return SESSION_ID_RE.match(name[len(OUTPUT_PREFIX) :]) is not None
|
||||
|
||||
|
||||
def app_id_for(session_id: str) -> str:
|
||||
"""The bare ``hh-<session-id>`` the launcher sets as the app's class.
|
||||
|
||||
Same string as the output name, and that is the point: the launcher stamps
|
||||
it on the application (``--class``, ``app_id``) and
|
||||
:func:`container_plan` anchors it into the window rule, so the window finds
|
||||
its own workspace with no lookup and no race against the window appearing.
|
||||
"""
|
||||
|
||||
return OUTPUT_PREFIX + _checked_session_id(session_id)
|
||||
|
||||
|
||||
def container_plan(
|
||||
session_id: str,
|
||||
workspace: int,
|
||||
width: int,
|
||||
height: int,
|
||||
app_id: str,
|
||||
) -> ContainerPlan:
|
||||
"""The commands that create and tear down one session's container.
|
||||
|
||||
``app_id`` is passed in rather than derived from ``session_id`` because the
|
||||
rule has to match whatever class the application actually reports: it is
|
||||
:func:`app_id_for` for a well-behaved app the launcher could stamp, and the
|
||||
app's own class for one that ignores the stamp.
|
||||
"""
|
||||
|
||||
name = output_name(session_id)
|
||||
slot = _checked_int(workspace, "workspace", minimum=1)
|
||||
w = _checked_int(width, "width", minimum=1)
|
||||
h = _checked_int(height, "height", minimum=1)
|
||||
match = _checked_app_id(app_id)
|
||||
return ContainerPlan(
|
||||
output=name,
|
||||
workspace=slot,
|
||||
mode=(w, h),
|
||||
create=[
|
||||
# The output first: the workspace rule below names it, and a rule
|
||||
# for an output that does not exist yet binds to nothing.
|
||||
["hyprctl", "output", "create", "headless", name],
|
||||
# `default:true` makes this the workspace the output shows, and
|
||||
# `persistent:true` keeps it alive when the last window closes — a
|
||||
# container that evaporated between two applications would send the
|
||||
# next window back to the shared screen.
|
||||
[
|
||||
"hyprctl",
|
||||
"keyword",
|
||||
"workspace",
|
||||
f"{slot}, monitor:{name}, default:true, persistent:true",
|
||||
],
|
||||
# Anchored (`^...$`) so a class that merely contains the app id
|
||||
# cannot claim another session's workspace. `initial_class` rather
|
||||
# than the live class: applications rename their window, and the
|
||||
# placement has to be decided when it is mapped.
|
||||
[
|
||||
"hyprctl",
|
||||
"keyword",
|
||||
"windowrule",
|
||||
f"match:initial_class ^{match}$, workspace {slot}, monitor {name}",
|
||||
],
|
||||
# Last, because the mode applies to an output that now exists and
|
||||
# already has its workspace; setting it earlier would resize a
|
||||
# screen that is about to be replaced.
|
||||
["hyprctl", "keyword", "monitor", f"{name},{w}x{h},auto,1"],
|
||||
],
|
||||
teardown=[["hyprctl", "output", "remove", name]],
|
||||
)
|
||||
|
||||
|
||||
def quarantine_plan(quarantine_workspace: str) -> ContainerPlan | None:
|
||||
"""The backstop rule: a window that matched no container goes here.
|
||||
|
||||
Without it, a window with an unexpected class — a dialog spawned by a
|
||||
helper process, a toolkit that rewrites its class — lands on whatever
|
||||
workspace is in front, which is the leak containers exist to prevent. The
|
||||
rule matches every class and is therefore emitted *before* the per-session
|
||||
rules, which are anchored and more specific.
|
||||
|
||||
``quarantine_workspace`` is a workspace *name* (``special:quarantine``), not
|
||||
a slot out of the allocator's band, so the returned plan carries no output
|
||||
and no mode: it is a rule, not a container. An empty or blank name means
|
||||
the operator turned the backstop off, and the answer is ``None`` rather than
|
||||
a plan with an empty command list — a caller that gets a plan should always
|
||||
have something to run.
|
||||
"""
|
||||
|
||||
target = quarantine_workspace.strip()
|
||||
if not target:
|
||||
return None
|
||||
_checked_rule_value(target, "quarantine_workspace")
|
||||
return ContainerPlan(
|
||||
output="",
|
||||
workspace=0,
|
||||
mode=(0, 0),
|
||||
create=[
|
||||
[
|
||||
"hyprctl",
|
||||
"keyword",
|
||||
"windowrule",
|
||||
f"match:initial_class .*, workspace {target}",
|
||||
]
|
||||
],
|
||||
# A keyword rule cannot be unset one at a time, and this one is not
|
||||
# per-session anyway: it is installed once at start-up and goes away
|
||||
# with the compositor.
|
||||
teardown=[],
|
||||
)
|
||||
|
||||
|
||||
class WorkspaceAllocator:
|
||||
"""Hands out workspace slots from a fixed band, lowest free first.
|
||||
|
||||
Lowest-free rather than monotonic so a long-lived broker's numbers stay
|
||||
small and readable (``hyprctl workspaces`` is something a human reads), and
|
||||
so the band is a real bound: ``count`` slots means at most ``count``
|
||||
containers, with exhaustion surfacing as :class:`NoSlots` at allocation
|
||||
rather than as a collision later.
|
||||
"""
|
||||
|
||||
def __init__(self, base: int, count: int) -> None:
|
||||
self._base = _checked_int(base, "base", minimum=1)
|
||||
self._count = _checked_int(count, "count", minimum=1)
|
||||
self._used: set[int] = set()
|
||||
|
||||
def allocate(self) -> int:
|
||||
"""The lowest free slot in ``[base, base + count)``. Raises :class:`NoSlots`."""
|
||||
|
||||
for slot in range(self._base, self._base + self._count):
|
||||
if slot not in self._used:
|
||||
self._used.add(slot)
|
||||
return slot
|
||||
raise NoSlots(
|
||||
f"workspace band {self._base}..{self._base + self._count - 1} is full "
|
||||
f"({self._count} in use)"
|
||||
)
|
||||
|
||||
def release(self, workspace: int) -> None:
|
||||
"""Give a slot back. A slot we never handed out raises :class:`KeyError`.
|
||||
|
||||
Loudly, because the two ways to get here are a double release and a
|
||||
caller releasing someone else's slot, and both mean the registry and
|
||||
this allocator have drifted. Swallowing it would hand the same
|
||||
workspace to two sessions a few minutes later, which is the leak that is
|
||||
hard to trace back.
|
||||
"""
|
||||
|
||||
if workspace not in self._used:
|
||||
raise KeyError(
|
||||
f"workspace {workspace} was not allocated by this allocator "
|
||||
f"(in use: {sorted(self._used)})"
|
||||
)
|
||||
self._used.discard(workspace)
|
||||
|
||||
def in_use(self) -> list[int]:
|
||||
"""Allocated slots, ascending. Sorted because callers log and diff it."""
|
||||
|
||||
return sorted(self._used)
|
||||
|
||||
|
||||
def _checked_session_id(session_id: str) -> str:
|
||||
if not isinstance(session_id, str) or not SESSION_ID_RE.match(session_id):
|
||||
raise ValueError(
|
||||
f"session id {session_id!r} is not [a-z0-9-]+; it names an output and "
|
||||
"goes into a compositor command"
|
||||
)
|
||||
return session_id
|
||||
|
||||
|
||||
def _checked_app_id(app_id: str) -> str:
|
||||
if not isinstance(app_id, str) or not app_id:
|
||||
raise ValueError(f"app id {app_id!r} is empty; a window rule needs a class to match")
|
||||
if not APP_ID_RE.match(app_id):
|
||||
raise ValueError(
|
||||
f"app id {app_id!r} is not [A-Za-z0-9._+-]+; a window rule body is "
|
||||
"comma-separated, so anything else could forge a rule field"
|
||||
)
|
||||
return app_id
|
||||
|
||||
|
||||
def _checked_rule_value(value: str, label: str) -> str:
|
||||
# Same reasoning as an app id, one rule field over: this ends up inside a
|
||||
# `workspace <value>` field, where a comma starts the next field. The colon
|
||||
# is allowed because `special:quarantine` needs it.
|
||||
if not re.match(r"\A[A-Za-z0-9._:+-]+\Z", value):
|
||||
raise ValueError(
|
||||
f"{label} {value!r} is not [A-Za-z0-9._:+-]+; it is interpolated into "
|
||||
"a comma-separated rule body"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def _checked_int(value: int, label: str, *, minimum: int) -> int:
|
||||
# bool is an int in Python, and `True` would silently become workspace 1.
|
||||
if not isinstance(value, int) or isinstance(value, bool):
|
||||
raise ValueError(f"{label} {value!r} is not an int")
|
||||
if value < minimum:
|
||||
raise ValueError(f"{label} {value!r} is not >= {minimum}")
|
||||
return value
|
||||
@@ -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)))
|
||||
@@ -1,106 +0,0 @@
|
||||
"""The workspace allocator: lowest free, reuse after release, and loud bugs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstreamd.containers import NoSlots, WorkspaceAllocator
|
||||
|
||||
|
||||
def test_allocates_the_band_from_its_base_upwards() -> None:
|
||||
alloc = WorkspaceAllocator(1000, 4)
|
||||
|
||||
assert [alloc.allocate() for _ in range(4)] == [1000, 1001, 1002, 1003]
|
||||
assert alloc.in_use() == [1000, 1001, 1002, 1003]
|
||||
|
||||
|
||||
def test_a_released_slot_is_reused_before_a_higher_free_one() -> None:
|
||||
alloc = WorkspaceAllocator(1000, 4)
|
||||
for _ in range(3):
|
||||
alloc.allocate()
|
||||
|
||||
alloc.release(1001)
|
||||
|
||||
assert alloc.in_use() == [1000, 1002]
|
||||
assert alloc.allocate() == 1001
|
||||
assert alloc.allocate() == 1003
|
||||
assert alloc.in_use() == [1000, 1001, 1002, 1003]
|
||||
|
||||
|
||||
def test_a_full_band_raises_no_slots_and_stays_unchanged() -> None:
|
||||
alloc = WorkspaceAllocator(1000, 2)
|
||||
alloc.allocate()
|
||||
alloc.allocate()
|
||||
|
||||
with pytest.raises(NoSlots) as exc:
|
||||
alloc.allocate()
|
||||
assert "1000..1001" in str(exc.value)
|
||||
assert alloc.in_use() == [1000, 1001]
|
||||
|
||||
# Exhaustion is not terminal: a release makes the slot available again.
|
||||
alloc.release(1000)
|
||||
assert alloc.allocate() == 1000
|
||||
|
||||
|
||||
def test_releasing_a_slot_we_never_handed_out_is_a_key_error() -> None:
|
||||
alloc = WorkspaceAllocator(1000, 2)
|
||||
alloc.allocate()
|
||||
|
||||
# Inside the band but free, and outside the band: both are caller bugs, and
|
||||
# a silent no-op would let two sessions share a workspace later.
|
||||
with pytest.raises(KeyError) as free_slot:
|
||||
alloc.release(1001)
|
||||
assert "1001" in str(free_slot.value)
|
||||
|
||||
with pytest.raises(KeyError):
|
||||
alloc.release(7)
|
||||
|
||||
assert alloc.in_use() == [1000]
|
||||
|
||||
|
||||
def test_a_double_release_raises() -> None:
|
||||
alloc = WorkspaceAllocator(1000, 2)
|
||||
slot = alloc.allocate()
|
||||
alloc.release(slot)
|
||||
|
||||
with pytest.raises(KeyError):
|
||||
alloc.release(slot)
|
||||
assert alloc.in_use() == []
|
||||
|
||||
|
||||
def test_in_use_is_ascending_whatever_the_allocation_order() -> None:
|
||||
alloc = WorkspaceAllocator(1000, 3)
|
||||
a, b, c = alloc.allocate(), alloc.allocate(), alloc.allocate()
|
||||
alloc.release(b)
|
||||
alloc.release(a)
|
||||
alloc.allocate()
|
||||
alloc.allocate()
|
||||
|
||||
assert alloc.in_use() == [1000, 1001, 1002]
|
||||
assert c == 1002
|
||||
|
||||
|
||||
def test_a_band_must_be_a_real_band() -> None:
|
||||
with pytest.raises(ValueError) as count:
|
||||
WorkspaceAllocator(1000, 0)
|
||||
assert "count" in str(count.value)
|
||||
|
||||
with pytest.raises(ValueError) as base:
|
||||
WorkspaceAllocator(0, 4)
|
||||
assert "base" in str(base.value)
|
||||
|
||||
with pytest.raises(ValueError) as kind:
|
||||
WorkspaceAllocator(1000, 2.5) # type: ignore[arg-type]
|
||||
assert "count" in str(kind.value)
|
||||
assert "is not an int" in str(kind.value)
|
||||
|
||||
|
||||
def test_two_allocators_do_not_share_state() -> None:
|
||||
# The set is per-instance; a class attribute here would hand the same
|
||||
# workspace to two brokers' containers.
|
||||
first = WorkspaceAllocator(1000, 2)
|
||||
second = WorkspaceAllocator(1000, 2)
|
||||
|
||||
assert first.allocate() == 1000
|
||||
assert second.allocate() == 1000
|
||||
assert first.in_use() == second.in_use() == [1000]
|
||||
@@ -1,223 +0,0 @@
|
||||
"""Container plans: the exact argv lists, and the validation that guards them.
|
||||
|
||||
The argv lists are asserted whole rather than probed for substrings. These
|
||||
commands are the only thing this module produces, nobody here runs them, and a
|
||||
test that accepted "contains the output name" would pass on a command that
|
||||
silently changed shape under a refactor.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstreamd.containers import (
|
||||
ContainerPlan,
|
||||
app_id_for,
|
||||
contains_output,
|
||||
container_plan,
|
||||
output_name,
|
||||
quarantine_plan,
|
||||
)
|
||||
|
||||
|
||||
def test_create_is_the_four_commands_in_order() -> None:
|
||||
plan = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa")
|
||||
|
||||
assert plan.create == [
|
||||
["hyprctl", "output", "create", "headless", "hh-foot-aaaaaa"],
|
||||
[
|
||||
"hyprctl",
|
||||
"keyword",
|
||||
"workspace",
|
||||
"1000, monitor:hh-foot-aaaaaa, default:true, persistent:true",
|
||||
],
|
||||
[
|
||||
"hyprctl",
|
||||
"keyword",
|
||||
"windowrule",
|
||||
"match:initial_class ^hh-foot-aaaaaa$, workspace 1000, monitor hh-foot-aaaaaa",
|
||||
],
|
||||
["hyprctl", "keyword", "monitor", "hh-foot-aaaaaa,1280x720,auto,1"],
|
||||
]
|
||||
|
||||
|
||||
def test_teardown_removes_the_output_and_nothing_else() -> None:
|
||||
plan = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa")
|
||||
|
||||
assert plan.teardown == [["hyprctl", "output", "remove", "hh-foot-aaaaaa"]]
|
||||
|
||||
|
||||
def test_plan_describes_what_it_built() -> None:
|
||||
plan = container_plan("x1", 1007, 1920, 1080, "org.gnome.Nautilus")
|
||||
|
||||
assert isinstance(plan, ContainerPlan)
|
||||
assert (plan.output, plan.workspace, plan.mode) == ("hh-x1", 1007, (1920, 1080))
|
||||
|
||||
|
||||
def test_a_foreign_class_is_matched_as_given() -> None:
|
||||
# The rule has to match what the toolkit reports, which is not always the
|
||||
# id the launcher stamped.
|
||||
plan = container_plan("x1", 1001, 800, 600, "org.gnome.Nautilus")
|
||||
|
||||
assert plan.create[2] == [
|
||||
"hyprctl",
|
||||
"keyword",
|
||||
"windowrule",
|
||||
"match:initial_class ^org.gnome.Nautilus$, workspace 1001, monitor hh-x1",
|
||||
]
|
||||
|
||||
|
||||
def test_identical_arguments_give_byte_identical_commands() -> None:
|
||||
first = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa")
|
||||
second = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa")
|
||||
|
||||
assert first == second
|
||||
assert first.create == second.create
|
||||
assert first.teardown == second.teardown
|
||||
|
||||
|
||||
def test_output_name_and_app_id_are_the_same_string() -> None:
|
||||
assert output_name("foot-aaaaaa") == "hh-foot-aaaaaa"
|
||||
assert app_id_for("foot-aaaaaa") == "hh-foot-aaaaaa"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
[
|
||||
"hh-foot-aaaaaa",
|
||||
"hh-x",
|
||||
"hh-1000",
|
||||
],
|
||||
)
|
||||
def test_contains_output_claims_our_own_names(name: str) -> None:
|
||||
assert contains_output(name) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
[
|
||||
"HEADLESS-1", # the compositor's own
|
||||
"eDP-1",
|
||||
"hh",
|
||||
"hh-", # no session id: not something the broker ever created
|
||||
"hh-Foot", # upper case is outside the minted alphabet
|
||||
"hh-foot\n", # a trailing newline is not a name, it is two lines
|
||||
"hh-foot aaaa",
|
||||
" hh-foot",
|
||||
"xhh-foot",
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_contains_output_refuses_everything_else(name: str) -> None:
|
||||
# A scan removes what this says is ours, so a false positive deletes an
|
||||
# output the broker did not create.
|
||||
assert contains_output(name) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad",
|
||||
["", "Foot", "foot_aaaa", "foot aaaa", "hh-foot;rm", "foot\n", "../x", "é"],
|
||||
)
|
||||
def test_a_session_id_outside_the_alphabet_is_refused(bad: str) -> None:
|
||||
with pytest.raises(ValueError) as exc:
|
||||
output_name(bad)
|
||||
assert repr(bad) in str(exc.value)
|
||||
assert "[a-z0-9-]" in str(exc.value)
|
||||
|
||||
with pytest.raises(ValueError) as app_exc:
|
||||
app_id_for(bad)
|
||||
assert repr(bad) in str(app_exc.value)
|
||||
|
||||
with pytest.raises(ValueError) as plan_exc:
|
||||
container_plan(bad, 1000, 1280, 720, "hh-x")
|
||||
assert repr(bad) in str(plan_exc.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("width,height", [(0, 720), (1280, 0), (-1, 720), (1280, -720)])
|
||||
def test_a_non_positive_mode_is_refused(width: int, height: int) -> None:
|
||||
with pytest.raises(ValueError) as exc:
|
||||
container_plan("x1", 1000, width, height, "hh-x1")
|
||||
message = str(exc.value)
|
||||
offender = width if width < 1 else height
|
||||
assert repr(offender) in message
|
||||
assert ("width" in message) or ("height" in message)
|
||||
assert ">= 1" in message
|
||||
|
||||
|
||||
def test_a_fractional_mode_is_refused() -> None:
|
||||
# 1280.5 would reach the compositor as "1280.5x720"; a mode is pixels.
|
||||
with pytest.raises(ValueError) as exc:
|
||||
container_plan("x1", 1000, 1280.5, 720, "hh-x1") # type: ignore[arg-type]
|
||||
assert "width" in str(exc.value)
|
||||
assert "is not an int" in str(exc.value)
|
||||
|
||||
|
||||
def test_a_boolean_workspace_is_refused() -> None:
|
||||
# True is an int in Python and would quietly become workspace 1.
|
||||
with pytest.raises(ValueError) as exc:
|
||||
container_plan("x1", True, 1280, 720, "hh-x1") # type: ignore[arg-type]
|
||||
assert "workspace" in str(exc.value)
|
||||
assert "is not an int" in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workspace", [0, -1])
|
||||
def test_a_non_positive_workspace_is_refused(workspace: int) -> None:
|
||||
with pytest.raises(ValueError) as exc:
|
||||
container_plan("x1", workspace, 1280, 720, "hh-x1")
|
||||
assert "workspace" in str(exc.value)
|
||||
assert repr(workspace) in str(exc.value)
|
||||
|
||||
|
||||
def test_an_empty_app_id_is_refused() -> None:
|
||||
with pytest.raises(ValueError) as exc:
|
||||
container_plan("x1", 1000, 1280, 720, "")
|
||||
assert "app id" in str(exc.value)
|
||||
assert "''" in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad",
|
||||
[
|
||||
"hh-x1, workspace 1001", # a forged second rule field
|
||||
"hh-x1$, monitor eDP-1",
|
||||
"hh x1",
|
||||
"hh-x1\nkeyword monitor eDP-1,disable",
|
||||
"^hh-x1$",
|
||||
"hh-x1'",
|
||||
],
|
||||
)
|
||||
def test_an_app_id_that_could_forge_a_rule_field_is_refused(bad: str) -> None:
|
||||
with pytest.raises(ValueError) as exc:
|
||||
container_plan("x1", 1000, 1280, 720, bad)
|
||||
assert repr(bad) in str(exc.value)
|
||||
assert "[A-Za-z0-9._+-]" in str(exc.value)
|
||||
|
||||
|
||||
def test_quarantine_plan_is_the_catch_all_keyword() -> None:
|
||||
plan = quarantine_plan("special:quarantine")
|
||||
|
||||
assert plan is not None
|
||||
assert plan.create == [
|
||||
[
|
||||
"hyprctl",
|
||||
"keyword",
|
||||
"windowrule",
|
||||
"match:initial_class .*, workspace special:quarantine",
|
||||
]
|
||||
]
|
||||
# A rule, not a container: nothing to remove, no output, no mode.
|
||||
assert plan.teardown == []
|
||||
assert (plan.output, plan.workspace, plan.mode) == ("", 0, (0, 0))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("disabled", ["", " ", "\n"])
|
||||
def test_quarantine_plan_is_none_when_disabled(disabled: str) -> None:
|
||||
assert quarantine_plan(disabled) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["special:quarantine, monitor eDP-1", "a b", "q\n1", "q'"])
|
||||
def test_a_quarantine_workspace_that_could_forge_a_field_is_refused(bad: str) -> None:
|
||||
with pytest.raises(ValueError) as exc:
|
||||
quarantine_plan(bad)
|
||||
assert "quarantine_workspace" in str(exc.value)
|
||||
assert repr(bad.strip()) in str(exc.value)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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"}
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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))
|
||||
Reference in new issue
Block a user