Compare commits

..
Author SHA1 Message Date
HermenixandClaude Opus 5 9b77c77ee8 ipc: a client that asks the compositor instead of guessing
The broker reported `workspace: null` and `window: null` for every session
because nothing in it could talk to Hyprland.  This is that voice, and the
only place that knows the compositor's wire format: one connection per
request on `.socket.sock` (leading `/` so an argument containing a slash is
never read as output flags, `j/` where JSON is wanted), and a held, blocking
stream on `.socket2.sock`.

Every failure is CompositorUnavailable -- no instance directory, two of them
and no signature, a socket that is gone, a peer that refuses or closes
mid-reply, a reply that is not the JSON it promised, an event stream that
ends.  Nothing returns an empty list or a None to stand in for "I could not
ask", because a caller that cannot tell those apart writes a guess into a
session record.  Inside the defined shape the parse is forgiving instead:
Hyprland's JSON has changed keys across releases, so a missing key is a
defined value and never a KeyError reaching the broker.

Tests bind real AF_UNIX sockets in a temporary directory laid out the way
Hyprland lays one out and serve canned bytes, so they drive the actual
connect, half-close, read-to-EOF and timeout paths rather than a mock that
would pass while the sockets broke.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLiQAZCmJf66CEcLx8siYF
2026-10-02 00:12:44 +00:00
26 changed files with 1423 additions and 2417 deletions

No files matched your search

+1 -15
View File
@@ -12,27 +12,13 @@ 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";
};
}
}
+1 -9
View File
@@ -7,12 +7,7 @@ name = "hhstream"
version = "0.1.0"
description = "Publish a headless Hyprland session's frames on a Unix socket"
requires-python = ">=3.11"
# 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"]
dependencies = []
[project.scripts]
hhstream-server = "hhstream.server:main"
@@ -21,9 +16,6 @@ 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"]
-13
View File
@@ -1,13 +0,0 @@
"""The pointer driver: a Wayland client that moves one cursor on command.
Its own process, for two reasons that are not negotiable. A Wayland client
needs its own connection to the compositor, and the broker is not one. And a
Wayland round-trip can block indefinitely — on a compositor that is busy, or
wedged — so running it inside the broker would let a stuck cursor stall every
other session's lifecycle.
It holds **no lease state**. It is told what to do and does it; the broker owns
the lease. See ``docs/CONTRACT-sessions.md`` §3.4. A driver that could be
trusted to serialise would eventually be trusted to, and there is exactly one
cursor to get that wrong with.
"""
-155
View File
@@ -1,155 +0,0 @@
"""``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())
@@ -1,12 +0,0 @@
"""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.
"""
@@ -1,72 +0,0 @@
"""Regenerate the vendored protocol package. Run by hand after a bump.
nix shell --impure --expr 'with (builtins.getFlake "nixpkgs").legacyPackages.${builtins.currentSystem}; [ (python3.withPackages (p: [ p.pywayland ])) wlr-protocols ]' \\
--command python3 -m hhstream_pointer._protocol.regenerate
The XML lives at ``share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml``
in ``pkgs.wlr-protocols`` — note that this is *not* the path
``docs/CONTRACT-sessions.md`` §3.4 gives; see the slice report.
pywayland's own ``python -m pywayland.scanner`` is not usable here: it builds
its import map only from the files it was handed, so scanning the wlr XML alone
raises ``KeyError: 'wl_seat'``. We seed the map with the core interfaces
pywayland already ships, then let the scanner emit ``from ..wayland import ...``
against the shim next door.
"""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
#: Where ``pkgs.wlr-protocols`` puts it, relative to the package root.
XML_SUFFIX = "share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml"
def find_xml() -> Path | None:
"""Look for the protocol XML on ``XDG_DATA_DIRS`` and in the nix profile."""
roots = [Path(p).parent for p in os.environ.get("XDG_DATA_DIRS", "").split(":") if p]
roots += [Path("/run/current-system/sw"), Path.home() / ".nix-profile"]
for root in roots:
candidate = root / XML_SUFFIX
if candidate.is_file():
return candidate
return None
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--xml", type=Path, default=None, help=f"path to .../{XML_SUFFIX}")
parser.add_argument(
"--output-dir",
type=Path,
default=Path(__file__).resolve().parent,
help="where the protocol package is written (default: next to this file)",
)
args = parser.parse_args(argv)
xml = args.xml or find_xml()
if xml is None:
parser.error(f"could not find {XML_SUFFIX}; pass --xml (is wlr-protocols in the shell?)")
from pywayland.protocol import wayland as core
from pywayland.scanner.protocol import Protocol
protocol = Protocol.parse_file(str(xml))
module = protocol.name.replace("-", "_")
# Interface -> protocol module. The core interfaces resolve to the shim in
# this directory; ours resolve to themselves.
core_dir = Path(core.__file__).parent
imports = {p.stem: "wayland" for p in core_dir.glob("wl_*.py")}
imports.update({iface.name: module for iface in protocol.interface})
protocol.output(str(args.output_dir), imports)
print(f"generated {module} from {xml} into {args.output_dir}")
return 0
if __name__ == "__main__":
sys.exit(main())
-12
View File
@@ -1,12 +0,0 @@
"""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
@@ -1,25 +0,0 @@
# 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
@@ -1,117 +0,0 @@
# 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
@@ -1,267 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2019 Josef Gajdusek
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
class ZwlrVirtualPointerV1(Interface):
"""Virtual pointer
This protocol allows clients to emulate a physical pointer device. The
requests are mostly mirror opposites of those specified in
:class:`~pywayland.protocol.wayland.WlPointer`.
"""
name = "zwlr_virtual_pointer_v1"
version = 2
class error(enum.IntEnum):
invalid_axis = 0
invalid_axis_source = 1
class ZwlrVirtualPointerV1Proxy(Proxy[ZwlrVirtualPointerV1]):
interface = ZwlrVirtualPointerV1
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Fixed),
)
def motion(self, time: int, dx: float, dy: float) -> None:
"""Pointer relative motion event
The pointer has moved by a relative amount to the previous request.
Values are in the global compositor space.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param dx:
displacement on the x-axis
:type dx:
`ArgumentType.Fixed`
:param dy:
displacement on the y-axis
:type dy:
`ArgumentType.Fixed`
"""
self._marshal(0, time, dx, dy)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def motion_absolute(self, time: int, x: int, y: int, x_extent: int, y_extent: int) -> None:
"""Pointer absolute motion event
The pointer has moved in an absolute coordinate frame.
Value of x can range from 0 to x_extent, value of y can range from 0 to
y_extent.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param x:
position on the x-axis
:type x:
`ArgumentType.Uint`
:param y:
position on the y-axis
:type y:
`ArgumentType.Uint`
:param x_extent:
extent of the x-axis
:type x_extent:
`ArgumentType.Uint`
:param y_extent:
extent of the y-axis
:type y_extent:
`ArgumentType.Uint`
"""
self._marshal(1, time, x, y, x_extent, y_extent)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def button(self, time: int, button: int, state: int) -> None:
"""Button event
A button was pressed or released.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param button:
button that produced the event
:type button:
`ArgumentType.Uint`
:param state:
physical state of the button
:type state:
`ArgumentType.Uint`
"""
self._marshal(2, time, button, state)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Fixed),
)
def axis(self, time: int, axis: int, value: float) -> None:
"""Axis event
Scroll and other axis requests.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param axis:
axis type
:type axis:
`ArgumentType.Uint`
:param value:
length of vector in touchpad coordinates
:type value:
`ArgumentType.Fixed`
"""
self._marshal(3, time, axis, value)
@ZwlrVirtualPointerV1.request()
def frame(self) -> None:
"""End of a pointer event sequence
Indicates the set of events that logically belong together.
"""
self._marshal(4)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
)
def axis_source(self, axis_source: int) -> None:
"""Axis source event
Source information for scroll and other axis.
:param axis_source:
source of the axis event
:type axis_source:
`ArgumentType.Uint`
"""
self._marshal(5, axis_source)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def axis_stop(self, time: int, axis: int) -> None:
"""Axis stop event
Stop notification for scroll and other axes.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param axis:
the axis stopped with this event
:type axis:
`ArgumentType.Uint`
"""
self._marshal(6, time, axis)
@ZwlrVirtualPointerV1.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Int),
)
def axis_discrete(self, time: int, axis: int, value: float, discrete: int) -> None:
"""Axis click event
Discrete step information for scroll and other axes.
This event allows the client to extend data normally sent using the
axis event with discrete value.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param axis:
axis type
:type axis:
`ArgumentType.Uint`
:param value:
length of vector in touchpad coordinates
:type value:
`ArgumentType.Fixed`
:param discrete:
number of steps
:type discrete:
`ArgumentType.Int`
"""
self._marshal(7, time, axis, value, discrete)
@ZwlrVirtualPointerV1.request(version=1)
def destroy(self) -> None:
"""Destroy the virtual pointer object
"""
self._marshal(8)
self._destroy()
class ZwlrVirtualPointerV1Resource(Resource):
interface = ZwlrVirtualPointerV1
class ZwlrVirtualPointerV1Global(Global):
interface = ZwlrVirtualPointerV1
ZwlrVirtualPointerV1._gen_c()
ZwlrVirtualPointerV1.proxy_class = ZwlrVirtualPointerV1Proxy
ZwlrVirtualPointerV1.resource_class = ZwlrVirtualPointerV1Resource
ZwlrVirtualPointerV1.global_class = ZwlrVirtualPointerV1Global
-278
View File
@@ -1,278 +0,0 @@
"""The pywayland half: one virtual pointer per output, created on demand.
This is the only module that imports pywayland, so everything above it can be
tested without a compositor. It implements :class:`hhstream_pointer.ops.PointerSink`
and nothing else; the decisions are all next door.
Three things here are load-bearing:
* ``zwlr_virtual_pointer_manager_v1`` is bound at **version 2** and pointers are
created with :func:`create_virtual_pointer_with_output`. Version 1's
``create_virtual_pointer`` yields a pointer whose coordinates are the *global*
layout, so a warp to (0.5, 0.5) lands in the middle of the whole desktop
rather than the middle of the session's output. That is silently wrong — the
click happens, just somewhere else — so a version-1-only manager raises
:class:`ManagerTooOld` and the driver refuses to start. There is no fallback
on purpose.
* ``wl_output`` is bound at version 4, because the ``name`` event is the only
way to match the compositor's ``hh-<session-id>`` to a protocol object.
* Coordinates arrive normalised and ``motion_absolute`` takes integers, so they
are scaled by a fixed :data:`EXTENT` rather than by the output's mode. The
compositor divides by the extent we send, so the output can be resized
underneath us without changing what (0.5, 0.5) means.
"""
from __future__ import annotations
import logging
import os
import time
from pathlib import Path
from pywayland.client import Display
from pywayland.protocol.wayland import WlOutput, WlSeat
from ._protocol.wlr_virtual_pointer_unstable_v1 import ZwlrVirtualPointerManagerV1
log = logging.getLogger("hhstream_pointer.backend")
#: Denominator for normalised coordinates. 16 bits of resolution across an
#: output is ~0.02px on a 1280-wide one: far finer than anything can observe.
EXTENT = 0xFFFF
#: The ``wl_output`` version that first carried the ``name`` event.
OUTPUT_VERSION = 4
#: The manager version that first carried ``create_virtual_pointer_with_output``.
MANAGER_VERSION = 2
class CompositorUnavailable(Exception):
"""No display to connect to, or the connection died. Fatal; do not guess."""
class ManagerTooOld(Exception):
"""``zwlr_virtual_pointer_manager_v1`` is offered below version 2.
Reported, never worked around: see the module docstring.
"""
def __init__(self, offered: int) -> None:
super().__init__(
f"zwlr_virtual_pointer_manager_v1 is version {offered}, need "
f"{MANAGER_VERSION} for create_virtual_pointer_with_output; without it "
"coordinates would be global and every warp would aim at the wrong "
"output. Refusing to start."
)
self.offered = offered
class OutputUnknown(Exception):
"""The compositor advertises no output by that name."""
def find_wayland_display(runtime_dir: Path) -> str:
"""The name of the compositor's socket inside its runtime directory.
The broker hands us a directory, not a socket, because that is what the
compositor's unit is configured with. One socket is the normal case; more
than one means two compositors share the directory and guessing which is
the session one would be a coin flip, so we refuse.
"""
try:
candidates = sorted(
p.name
for p in runtime_dir.iterdir()
if p.name.startswith("wayland-") and not p.name.endswith(".lock")
)
except OSError as exc:
raise CompositorUnavailable(f"cannot read {runtime_dir}: {exc}") from None
if not candidates:
raise CompositorUnavailable(f"no wayland-* socket in {runtime_dir}")
if len(candidates) > 1:
raise CompositorUnavailable(
f"{len(candidates)} wayland sockets in {runtime_dir} ({', '.join(candidates)}); "
"pass --wayland-display to say which"
)
return candidates[0]
class _Output:
__slots__ = ("proxy", "name")
def __init__(self, proxy) -> None:
self.proxy = proxy
self.name: str | None = None
class WaylandSink:
"""A connection, a manager, and a lazily created pointer per output."""
def __init__(self, runtime_dir: Path, display_name: str | None = None) -> None:
self._runtime_dir = Path(runtime_dir)
self._display_name = display_name
self._display: Display | None = None
self._registry = None
self._seat = None
self._manager = None
self._manager_version = 0
self._output_version = 0
#: registry global id -> output
self._outputs: dict[int, _Output] = {}
#: output name -> virtual pointer proxy
self._pointers: dict[str, object] = {}
# -- lifecycle --------------------------------------------------------
def connect(self) -> None:
"""Connect, bind, and prove the manager is version 2.
``XDG_RUNTIME_DIR`` is set rather than passed because that is the only
way libwayland resolves a socket *name*; the alternative is opening the
socket ourselves and handing over an fd, which buys nothing.
"""
name = self._display_name or find_wayland_display(self._runtime_dir)
os.environ["XDG_RUNTIME_DIR"] = str(self._runtime_dir)
display = Display(name)
try:
display.connect()
except Exception as exc: # pywayland raises bare exceptions here
raise CompositorUnavailable(f"cannot connect to {self._runtime_dir}/{name}: {exc}") from None
self._display = display
self._registry = display.get_registry()
self._registry.dispatcher["global"] = self._on_global
self._registry.dispatcher["global_remove"] = self._on_global_remove
# Two round trips: the first delivers the globals, the second the
# `name` events the outputs emit once bound.
self._sync()
self._sync()
if self._manager is None:
if self._manager_version:
raise ManagerTooOld(self._manager_version)
raise CompositorUnavailable(
"compositor does not advertise zwlr_virtual_pointer_manager_v1"
)
if self._outputs and self._output_version < OUTPUT_VERSION:
raise CompositorUnavailable(
f"wl_output is version {self._output_version}, need {OUTPUT_VERSION} "
"to learn output names"
)
log.info(
"connected to %s: manager v%d, %d output(s)",
name,
self._manager_version,
len(self._outputs),
)
def close(self) -> None:
if self._display is None:
return
self._pointers.clear()
try:
self._display.disconnect()
finally:
self._display = None
def outputs(self) -> list[str]:
"""Output names currently advertised, for the log line on startup."""
return sorted(o.name for o in self._outputs.values() if o.name)
# -- PointerSink ------------------------------------------------------
def motion_absolute(self, output: str, x: float, y: float) -> None:
pointer = self._pointer(output)
pointer.motion_absolute(_now_ms(), round(x * EXTENT), round(y * EXTENT), EXTENT, EXTENT)
self._flush()
def button(self, output: str, code: int, state: int) -> None:
self._pointer(output).button(_now_ms(), code, state)
self._flush()
def frame(self, output: str) -> None:
self._pointer(output).frame()
self._flush()
# -- internals --------------------------------------------------------
def _pointer(self, output: str):
existing = self._pointers.get(output)
if existing is not None:
return existing
proxy = self._resolve(output)
pointer = self._manager.create_virtual_pointer_with_output(self._seat, proxy)
self._pointers[output] = pointer
log.debug("created virtual pointer for output %s", output)
return pointer
def _resolve(self, output: str):
"""Find an output by name, re-syncing once in case it is new.
Outputs come and go with sessions, so a miss is routine rather than an
error: the broker may have created the container microseconds ago.
"""
for attempt in (0, 1):
for entry in self._outputs.values():
if entry.name == output:
return entry.proxy
if attempt == 0:
self._sync()
self._sync()
known = ", ".join(self.outputs()) or "none"
raise OutputUnknown(f"no output named {output!r} (known: {known})")
def _sync(self) -> None:
try:
self._display.roundtrip()
except Exception as exc:
raise CompositorUnavailable(f"compositor connection lost: {exc}") from None
def _flush(self) -> None:
try:
self._display.flush()
except Exception as exc:
raise CompositorUnavailable(f"compositor connection lost: {exc}") from None
def _on_global(self, registry, global_id: int, interface: str, version: int) -> None:
if interface == ZwlrVirtualPointerManagerV1.name:
self._manager_version = version
if version >= MANAGER_VERSION:
self._manager = registry.bind(global_id, ZwlrVirtualPointerManagerV1, MANAGER_VERSION)
elif interface == WlSeat.name and self._seat is None:
self._seat = registry.bind(global_id, WlSeat, min(version, WlSeat.version))
elif interface == WlOutput.name:
self._output_version = max(self._output_version, version)
entry = _Output(registry.bind(global_id, WlOutput, min(version, OUTPUT_VERSION)))
entry.proxy.dispatcher["name"] = lambda _proxy, name, e=entry: self._name_output(e, name)
self._outputs[global_id] = entry
def _on_global_remove(self, registry, global_id: int) -> None:
entry = self._outputs.pop(global_id, None)
if entry is None or entry.name is None:
return
# The pointer was bound to an output that no longer exists; a warp
# through it would go nowhere, so drop it and let the next one be
# created against whatever replaced it.
pointer = self._pointers.pop(entry.name, None)
if pointer is not None:
pointer.destroy()
log.info("output %s went away", entry.name)
@staticmethod
def _name_output(entry: _Output, name: str) -> None:
entry.name = name
def _now_ms() -> int:
"""A millisecond timestamp for the protocol's ``time`` arguments.
The compositor only compares these to each other, so any monotonic source
will do; it is truncated to 32 bits because the wire field is a ``uint``.
"""
return int(time.monotonic() * 1000) & 0xFFFFFFFF
-48
View File
@@ -1,48 +0,0 @@
"""Button names on the wire, evdev codes on the protocol.
``zwlr_virtual_pointer_v1.button`` takes a Linux input event code, not a name,
so the mapping has to live somewhere. It lives here, spelled out, rather than
being computed from ``BTN_LEFT + n``: the evdev block is not contiguous in any
meaningful order and a reader should be able to check a value against
``linux/input-event-codes.h`` without arithmetic.
Only the buttons an agent can ask for are listed. Adding a name here is the
whole of adding a button; nothing else switches on these.
"""
from __future__ import annotations
#: Agent-facing name -> ``BTN_*`` code from ``linux/input-event-codes.h``.
CODES: dict[str, int] = {
"left": 0x110, # BTN_LEFT
"right": 0x111, # BTN_RIGHT
"middle": 0x112, # BTN_MIDDLE
"side": 0x113, # BTN_SIDE
"extra": 0x114, # BTN_EXTRA
"forward": 0x115, # BTN_FORWARD
"back": 0x116, # BTN_BACK
"task": 0x117, # BTN_TASK
}
#: ``wl_pointer.button_state``. Named on the wire so a log line reads.
STATES: dict[str, int] = {"up": 0, "down": 1}
NAMES = tuple(CODES)
def code_for(name: str) -> int:
"""The evdev code for a button name, or :class:`ValueError` naming the set."""
try:
return CODES[name]
except KeyError:
raise ValueError(f"unknown button {name!r} (known: {', '.join(NAMES)})") from None
def state_for(state: str) -> int:
"""``"down"``/``"up"`` to ``wl_pointer.button_state``."""
try:
return STATES[state]
except KeyError:
raise ValueError(f"unknown button state {state!r} (expected 'down' or 'up')") from None
-163
View File
@@ -1,163 +0,0 @@
"""The private broker↔driver protocol (CONTRACT-sessions.md §3.4).
Newline-delimited JSON, one request object per line, one response object back.
Every response is ``{"ok": true, ...}`` or ``{"ok": false, "error": "<text>"}``;
a rejected request is answered, never fatal, because the broker is a long-lived
peer and dropping its connection would cost it a cursor it still holds a lease
on.
This module is the whole of the driver's logic and it touches no Wayland. It
speaks to a :class:`PointerSink` — "send this to the virtual pointer bound to
*this* output" — which is the one thing pywayland is needed for. That seam is
why the dispatcher can be tested without a compositor, and the test suite does
exactly that.
The dispatcher keeps two pieces of *device* state, which is not lease state:
* the output of the last ``warp``, because ``button`` and ``frame`` carry no
output of their own and there is only one cursor to aim;
* which buttons are down and on which pointer, because ``release_all`` has to
report what it lifted and must lift it through the pointer it went down on.
It keeps no notion of who is allowed to ask. That is the lease, and the lease
lives in the broker.
"""
from __future__ import annotations
from typing import Any, Protocol
from . import buttons
class PointerSink(Protocol):
"""A virtual pointer per output. Implemented by :mod:`.backend`."""
def motion_absolute(self, output: str, x: float, y: float) -> None:
"""Warp to ``x``/``y``, each 0..1 in ``output``'s own frame."""
def button(self, output: str, code: int, state: int) -> None:
"""An evdev button code and a ``wl_pointer.button_state``."""
def frame(self, output: str) -> None:
"""Commit the queued events. Nothing is delivered until this."""
class Rejected(Exception):
"""The request was understood and refused; the text goes to the broker."""
class Dispatcher:
def __init__(self, sink: PointerSink) -> None:
self._sink = sink
self._output: str | None = None
#: button name -> the output its press was sent to. Insertion-ordered,
#: so a release_all lifts in the order things went down.
self._pressed: dict[str, str] = {}
def handle(self, request: Any) -> dict[str, Any]:
"""One request object to one response object. Never raises."""
try:
return self._handle(request)
except Rejected as exc:
return {"ok": False, "error": str(exc)}
def _handle(self, request: Any) -> dict[str, Any]:
if not isinstance(request, dict):
raise Rejected(f"request must be a JSON object, got {type(request).__name__}")
op = request.get("op")
if not isinstance(op, str):
raise Rejected("request has no 'op'")
handler = self._ops.get(op)
if handler is None:
raise Rejected(f"unknown op {op!r} (known: {', '.join(sorted(self._ops))})")
return handler(self, request)
# -- ops --------------------------------------------------------------
def _op_warp(self, request: dict) -> dict[str, Any]:
output = _require_output(request)
x = _require_unit(request, "x")
y = _require_unit(request, "y")
self._sink.motion_absolute(output, x, y)
# Only now: a sink that raised must not leave us aiming at an output we
# never reached, or the next `button` would land on the wrong session.
self._output = output
return {"ok": True}
def _op_button(self, request: dict) -> dict[str, Any]:
name = request.get("button")
if not isinstance(name, str):
raise Rejected("'button' must be a string")
state = request.get("state")
if not isinstance(state, str):
raise Rejected("'state' must be 'down' or 'up'")
try:
code = buttons.code_for(name)
value = buttons.state_for(state)
except ValueError as exc:
raise Rejected(str(exc)) from None
output = self._aimed()
self._sink.button(output, code, value)
if state == "down":
self._pressed[name] = output
else:
self._pressed.pop(name, None)
return {"ok": True}
def _op_frame(self, request: dict) -> dict[str, Any]:
self._sink.frame(self._aimed())
return {"ok": True}
def _op_pressed(self, request: dict) -> dict[str, Any]:
return {"ok": True, "buttons": list(self._pressed)}
def _op_release_all(self, request: dict) -> dict[str, Any]:
"""Lift everything. The broker calls this when a lease expires, so it
must not depend on an aim: each button is lifted through the pointer it
was pressed on, even if the cursor has since been warped elsewhere."""
lifted = list(self._pressed)
outputs = list(dict.fromkeys(self._pressed.values()))
for name in lifted:
self._sink.button(self._pressed[name], buttons.code_for(name), buttons.STATES["up"])
self._pressed.clear()
for output in outputs:
self._sink.frame(output)
return {"ok": True, "lifted": lifted}
_ops = {
"warp": _op_warp,
"button": _op_button,
"frame": _op_frame,
"pressed": _op_pressed,
"release_all": _op_release_all,
}
# -- internals --------------------------------------------------------
def _aimed(self) -> str:
if self._output is None:
raise Rejected("no output is aimed; warp before button or frame")
return self._output
def _require_output(request: dict) -> str:
output = request.get("output")
if not isinstance(output, str) or not output:
raise Rejected("'output' must be a non-empty string")
return output
def _require_unit(request: dict, key: str) -> float:
value = request.get(key)
# bool is an int in Python and would pass silently; a boolean coordinate is
# a bug in the caller, not a 0 or a 1.
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise Rejected(f"'{key}' must be a number in 0..1")
value = float(value)
if not 0.0 <= value <= 1.0:
raise Rejected(f"'{key}' is {value}, outside 0..1 — coordinates are normalised")
return value
-90
View File
@@ -1,90 +0,0 @@
"""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()
+589
View File
@@ -0,0 +1,589 @@
"""Asking the compositor what it actually has, instead of guessing.
The broker launches applications and then reports on them. Until now it had no
way to see the other side: every session's ``workspace`` and ``window`` were
``null`` because nothing in the daemon could talk to Hyprland. This module is
that voice. It is deliberately the *only* place that knows the compositor's
wire format, so a Hyprland upgrade is one file to re-read.
Three decisions shape everything here.
**Degrade, never guess.** Every failure — no instance directory, two instance
directories and no signature, a socket that is gone, a connection refused, a
reply that is not the JSON it claims to be — is :class:`CompositorUnavailable`.
Nothing returns an empty list, a ``None`` or a plausible-looking default to
stand in for "I could not ask", because a caller that cannot tell those apart
will write a guess into a session record and the operator will believe it.
**Parse defensively, inside the defined shape.** Hyprland's JSON has gained,
renamed and re-typed keys across releases, so a missing key is a *defined*
value (``None``, ``0``, ``-1``) and never a ``KeyError`` reaching the caller.
The exception is a key whose absence makes the record meaningless — a client
with no ``address`` — which is a malformed reply, not a degraded one.
**One connection per request, a held connection for events.** That is what
``hyprctl`` does and what Hyprland expects: it reads a request, writes the
reply and closes. The event socket is the opposite — a stream that must stay
open, blocking, for as long as the caller reads it. When it ends, it raises:
an event stream that stops is a failure the caller must see, because a broker
that quietly stops being told about closed windows looks identical to a broker
watching an idle desktop.
"""
from __future__ import annotations
import json
import os
import socket
import stat
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
#: Hyprland names its per-instance directory after this variable, and every
#: process it starts inherits it. It is the strongest hint available.
SIGNATURE_ENV = "HYPRLAND_INSTANCE_SIGNATURE"
#: ``<runtime dir>/hypr/<signature>/`` holds both sockets (CONTRACT §5).
INSTANCE_SUBDIR = "hypr"
REQUEST_SOCKET_NAME = ".socket.sock"
EVENT_SOCKET_NAME = ".socket2.sock"
#: Requests are local, synchronous and tiny. The compositor answers at once or
#: it is wedged; this only bounds the pathological case where it accepts the
#: connection and then stops. It is a class attribute so a test can shorten it
#: without widening ``__init__``, whose signature is frozen by the contract.
REQUEST_TIMEOUT_S = 2.0
#: Field names for the events a session broker joins on, in payload order. The
#: payload is positional and comma-separated, and the *last* named field keeps
#: any remaining commas — window titles contain them, which is precisely why a
#: naive ``split(",")`` loses the end of a title.
_EVENT_FIELDS: dict[str, tuple[str, ...]] = {
"openwindow": ("address", "workspace", "class", "title"),
"closewindow": ("address",),
"movewindow": ("address", "workspace"),
"movewindowv2": ("address", "workspace_id", "workspace"),
"windowtitle": ("address",),
"windowtitlev2": ("address", "title"),
"activewindow": ("class", "title"),
"activewindowv2": ("address",),
"changefloatingmode": ("address", "floating"),
"urgent": ("address",),
"pin": ("address", "pinned"),
"fullscreen": ("state",),
"workspace": ("name",),
"workspacev2": ("id", "name"),
"createworkspace": ("name",),
"createworkspacev2": ("id", "name"),
"destroyworkspace": ("name",),
"destroyworkspacev2": ("id", "name"),
"moveworkspace": ("name", "monitor"),
"moveworkspacev2": ("id", "name", "monitor"),
"renameworkspace": ("id", "name"),
"activespecial": ("name", "monitor"),
"focusedmon": ("monitor", "workspace"),
"monitoradded": ("name",),
"monitoraddedv2": ("id", "name", "description"),
"monitorremoved": ("name",),
}
class CompositorUnavailable(Exception):
"""No request socket, or the compositor refused. Callers degrade, never guess."""
@dataclass(frozen=True)
class Monitor:
name: str
x: int
y: int
width: int
height: int
scale: float
active_workspace_id: int | None
@dataclass(frozen=True)
class Workspace:
id: int
name: str
monitor: str | None
windows: int
is_special: bool
@dataclass(frozen=True)
class Client:
address: str
pid: int
workspace_id: int | None
monitor: str | None
class_: str
initial_class: str
title: str
stable_id: str
visible: bool
@dataclass(frozen=True)
class CursorPos:
x: int
y: int
@dataclass(frozen=True)
class Event:
name: str
data: dict
def _as_int(value: object, default: int) -> int:
"""An int, or ``default`` for anything that is not plainly one.
Hyprland has shipped ids as numbers and as numeric strings; ``bool`` is
excluded because ``True`` is not a workspace id.
"""
if isinstance(value, bool):
return default
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, str):
try:
return int(value.strip())
except ValueError:
return default
return default
def _as_float(value: object, default: float) -> float:
if isinstance(value, bool):
return default
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
try:
return float(value.strip())
except ValueError:
return default
return default
def _as_str(value: object) -> str:
"""A string, or "" — never ``None`` leaking into a field typed ``str``."""
if isinstance(value, str):
return value
if value is None:
return ""
return str(value)
def _optional_name(value: object) -> str | None:
"""A monitor name, or ``None`` when the reply did not carry one.
``clients -j`` reports ``monitor`` as a numeric *index* while
``workspaces -j`` reports it as a *name*; both are coerced to text so the
field means "what the compositor said" and ``None`` keeps its single
meaning of "the compositor said nothing".
"""
if value is None or value == "":
return None
if isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return str(int(value))
if isinstance(value, str):
return value
return None
def _nested_id(value: object) -> int | None:
"""``{"id": 3, "name": "3"}`` -> ``3``; anything else -> ``None``."""
if isinstance(value, dict):
raw = value.get("id")
if isinstance(raw, bool):
return None
if isinstance(raw, int):
return raw
if isinstance(raw, (float, str)):
parsed = _as_int(raw, -(2**62))
return None if parsed == -(2**62) else parsed
return None
def _entries(payload: object, what: str) -> list[dict]:
"""The list of objects a ``-j`` listing must be, or a malformed reply."""
if not isinstance(payload, list):
raise CompositorUnavailable(f"{what}: expected a JSON list, got {type(payload).__name__}")
out = []
for item in payload:
if not isinstance(item, dict):
raise CompositorUnavailable(
f"{what}: expected objects in the list, got {type(item).__name__}"
)
out.append(item)
return out
def _monitor(raw: dict) -> Monitor:
name = raw.get("name")
if not isinstance(name, str) or not name:
raise CompositorUnavailable("monitors: an entry has no name")
return Monitor(
name=name,
x=_as_int(raw.get("x"), 0),
y=_as_int(raw.get("y"), 0),
width=_as_int(raw.get("width"), 0),
height=_as_int(raw.get("height"), 0),
scale=_as_float(raw.get("scale"), 1.0),
# Older replies nest the active workspace; a monitor with none (an
# output just created and not yet populated) legitimately has no id.
active_workspace_id=_nested_id(raw.get("activeWorkspace")),
)
def _workspace(raw: dict) -> Workspace:
if "id" not in raw:
raise CompositorUnavailable("workspaces: an entry has no id")
ident = _as_int(raw.get("id"), -(2**62))
if ident == -(2**62):
raise CompositorUnavailable(f"workspaces: entry id is not a number ({raw.get('id')!r})")
name = _as_str(raw.get("name"))
special = raw.get("special")
return Workspace(
id=ident,
name=name,
monitor=_optional_name(raw.get("monitor")),
windows=_as_int(raw.get("windows"), 0),
# Hyprland did not always report ``special``. Where it does not, the
# two things that have always been true of a special workspace are
# its negative id and its ``special:`` name prefix.
is_special=(
bool(special)
if isinstance(special, bool)
else (ident < 0 or name.startswith("special"))
),
)
def _client(raw: dict) -> Client:
address = raw.get("address")
if not isinstance(address, str) or not address:
raise CompositorUnavailable("clients: an entry has no address")
initial_class = _as_str(raw.get("initialClass"))
pid = _as_int(raw.get("pid"), -1)
mapped = raw.get("mapped")
hidden = raw.get("hidden")
return Client(
address=address,
# -1, not 0: no process has it, so an unknown pid cannot be mistaken
# for a real one by code that only checks for falsiness.
pid=pid,
workspace_id=_nested_id(raw.get("workspace")),
monitor=_optional_name(raw.get("monitor")),
class_=_as_str(raw.get("class")),
initial_class=initial_class,
title=_as_str(raw.get("title")),
# The contract names a stable id but Hyprland publishes none. The
# initial class plus the pid is the closest honest thing: the launcher
# sets the class per session, the pid is the session's process, and
# unlike ``address`` the pair survives a window being remapped. It
# falls back to the address rather than ever being empty.
stable_id=f"{initial_class}:{pid}" if initial_class and pid > 0 else address,
# "Visible" is mapped-and-not-hidden; a missing key must not make a
# live window look gone, so absence reads as mapped.
visible=(True if mapped is None else bool(mapped)) and not bool(hidden),
)
def parse_event(line: str) -> Event:
"""``"name>>a,b,c"`` -> :class:`Event`.
The payload is positional, so :data:`_EVENT_FIELDS` names the fields for
the events the broker joins on and the last named field absorbs any
remaining commas (titles contain them). ``raw`` and ``args`` are always
present, so an event this module does not know is still usable rather than
discarded, and nothing is hidden behind the naming.
A line with no ``>>`` is a malformed reply, not an event with an odd name:
:class:`CompositorUnavailable`.
"""
text = line.rstrip("\r\n")
name, separator, payload = text.partition(">>")
if not separator or not name:
raise CompositorUnavailable(f"event line has no name>>payload separator: {text!r}")
data: dict = {"raw": payload}
if payload == "":
# An empty payload carried nothing; naming fields here would invent
# values ("" is not a window address) for an event like
# ``configreloaded>>`` that has no arguments at all.
data["args"] = []
return Event(name=name, data=data)
fields = _EVENT_FIELDS.get(name)
if fields:
parts = payload.split(",", len(fields) - 1)
data["args"] = list(parts)
data.update(zip(fields, parts))
else:
data["args"] = payload.split(",")
return Event(name=name, data=data)
class HyprlandIPC:
"""A client for one compositor instance's request and event sockets."""
#: Overridable per instance; ``__init__``'s signature is frozen, so this is
#: how a caller (or a test) bounds a wedged compositor differently.
request_timeout_s: float = REQUEST_TIMEOUT_S
def __init__(self, request_socket: Path, event_socket: Path | None = None) -> None:
self.request_socket = Path(request_socket)
self.event_socket = Path(event_socket) if event_socket is not None else None
self._event_sock: socket.socket | None = None
@classmethod
def discover(cls, runtime_dir: Path, signature: str | None = None) -> "HyprlandIPC":
"""Locate the instance under ``runtime_dir`` and return a client for it.
The signature comes from the argument, else the environment, else the
*single* directory under ``<runtime_dir>/hypr/``. Two instances and no
signature raises: picking one would silently aim the broker's queries,
and later its pointer, at the wrong desktop.
"""
hypr = Path(runtime_dir) / INSTANCE_SUBDIR
chosen = signature or os.environ.get(SIGNATURE_ENV) or None
if chosen is not None:
chosen = chosen.strip() or None
if chosen is not None and ("/" in chosen or chosen in (".", "..")):
raise CompositorUnavailable(
f"instance signature is not a directory name: {chosen!r}"
)
if chosen is None:
chosen = cls._sole_instance(hypr)
directory = hypr / chosen
request = directory / REQUEST_SOCKET_NAME
try:
mode = request.stat().st_mode
except OSError as exc:
raise CompositorUnavailable(
f"compositor request socket {request}: {exc.strerror or exc}"
) from exc
if not stat.S_ISSOCK(mode):
raise CompositorUnavailable(f"compositor request socket {request} is not a socket")
return cls(request, directory / EVENT_SOCKET_NAME)
@staticmethod
def _sole_instance(hypr: Path) -> str:
"""The one directory under ``<runtime_dir>/hypr``, or a refusal."""
try:
with os.scandir(hypr) as entries:
names = sorted(e.name for e in entries if e.is_dir())
except OSError as exc:
raise CompositorUnavailable(
f"compositor instance dir {hypr}: {exc.strerror or exc}; is the compositor running?"
) from exc
if not names:
raise CompositorUnavailable(
f"compositor instance dir {hypr} holds no instance; is the compositor running?"
)
if len(names) > 1:
raise CompositorUnavailable(
f"compositor instance dir {hypr} holds {len(names)} instances "
f"({', '.join(names)}); set {SIGNATURE_ENV} or pass a signature"
)
return names[0]
# -- the request socket ------------------------------------------------
def _wire(self, command: str) -> str:
"""The bytes Hyprland expects for ``command``.
Hyprland reads everything before the *first* ``/`` as output flags, so
a command is sent with a leading ``/`` — otherwise ``dispatch exec
/usr/bin/foo`` would be read as the flags ``dispatch exec `` followed
by a request of ``usr/bin/foo``. A command whose first word already
carries a prefix (``j/clients``) is passed through untouched, which is
what makes :meth:`query` able to reach anything this module does not
wrap.
"""
text = command.strip()
if not text:
raise CompositorUnavailable("empty request")
first = text.split(None, 1)[0]
return text if "/" in first else "/" + text
def _request(self, command: str) -> str:
"""Send one request, read the whole reply, close. Raises on any failure."""
wire = self._wire(command)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(self.request_timeout_s)
try:
sock.connect(str(self.request_socket))
except OSError as exc:
raise CompositorUnavailable(
f"compositor request socket {self.request_socket}: {exc.strerror or exc}"
) from exc
try:
sock.sendall(wire.encode())
# Half-close: the reply ends at EOF, and a compositor that
# waits for more input would otherwise deadlock against a
# client waiting for more output.
sock.shutdown(socket.SHUT_WR)
chunks = []
while True:
chunk = sock.recv(65536)
if not chunk:
break
chunks.append(chunk)
except socket.timeout as exc:
raise CompositorUnavailable(
f"compositor did not answer {command!r} within {self.request_timeout_s}s"
) from exc
except OSError as exc:
raise CompositorUnavailable(
f"compositor connection lost during {command!r}: {exc.strerror or exc}"
) from exc
finally:
sock.close()
# errors="replace" because a window title is arbitrary user data and a
# decoding accident must not masquerade as the compositor being down.
return b"".join(chunks).decode("utf-8", errors="replace")
def _json(self, command: str, what: str) -> object:
text = self._request(command)
if not text.strip():
raise CompositorUnavailable(f"{what}: empty reply")
try:
return json.loads(text)
except ValueError as exc:
# Hyprland answers an unknown or rejected request in plain text, so
# this is also where "that command does not exist here" lands.
raise CompositorUnavailable(
f"{what}: reply is not JSON ({exc}): {text[:120]!r}"
) from exc
def query(self, command: str) -> str:
"""The raw request socket, for anything this module does not wrap."""
return self._request(command)
def version(self) -> str:
"""The compositor's own version banner, verbatim.
Text, not ``version -j``: the banner is what every Hyprland has
answered, and parsing it into parts here would be this module guessing
at a shape that has changed.
"""
text = self._request("version").strip()
if not text:
raise CompositorUnavailable("version: empty reply")
return text
def monitors(self) -> list[Monitor]:
entries = _entries(self._json("j/monitors", "monitors"), "monitors")
return [_monitor(raw) for raw in entries]
def workspaces(self) -> list[Workspace]:
entries = _entries(self._json("j/workspaces", "workspaces"), "workspaces")
return [_workspace(raw) for raw in entries]
def clients(self) -> list[Client]:
return [_client(raw) for raw in _entries(self._json("j/clients", "clients"), "clients")]
def cursorpos(self) -> CursorPos:
payload = self._json("j/cursorpos", "cursorpos")
if not isinstance(payload, dict) or "x" not in payload or "y" not in payload:
raise CompositorUnavailable(
f"cursorpos: expected an object with x and y, got {payload!r}"
)
sentinel = -(2**62)
x = _as_int(payload.get("x"), sentinel)
y = _as_int(payload.get("y"), sentinel)
if x == sentinel or y == sentinel:
raise CompositorUnavailable(f"cursorpos: x and y are not numbers: {payload!r}")
return CursorPos(x=x, y=y)
# -- the event socket --------------------------------------------------
def events(self) -> Iterator[Event]:
"""Blocking iteration over the event stream.
The connection is made here rather than on the first ``next()``, so a
missing event socket is reported to the caller that asked for the
stream instead of to whatever later happens to iterate it. The
iterator never ends quietly: EOF raises :class:`CompositorUnavailable`,
because a compositor that stopped talking and a desktop where nothing
happens must not look the same.
"""
if self.event_socket is None:
raise CompositorUnavailable("no event socket was configured for this instance")
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(self.request_timeout_s)
sock.connect(str(self.event_socket))
except OSError as exc:
sock.close()
raise CompositorUnavailable(
f"compositor event socket {self.event_socket}: {exc.strerror or exc}"
) from exc
# Blocking from here on: an idle desktop sends nothing for hours and a
# read timeout would turn that into a false failure.
sock.settimeout(None)
self._close_event_sock()
self._event_sock = sock
return self._iter_events(sock)
def _iter_events(self, sock: socket.socket) -> Iterator[Event]:
buffer = b""
while True:
try:
chunk = sock.recv(65536)
except OSError as exc:
raise CompositorUnavailable(
f"compositor event socket {self.event_socket}: {exc.strerror or exc}"
) from exc
if not chunk:
# A trailing fragment is a truncated event, never an event.
raise CompositorUnavailable(
f"compositor event stream ended ({self.event_socket})"
+ (f"; {len(buffer)} bytes left unterminated" if buffer else "")
)
buffer += chunk
while b"\n" in buffer:
line, buffer = buffer.split(b"\n", 1)
yield parse_event(line.decode("utf-8", errors="replace"))
def _close_event_sock(self) -> None:
sock, self._event_sock = self._event_sock, None
if sock is None:
return
try:
# shutdown first: closing alone does not wake a thread already
# blocked in recv, and unblocking it is the point of close().
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
sock.close()
def close(self) -> None:
"""Drop the event stream. Idempotent; request sockets are per-call."""
self._close_event_sock()
-287
View File
@@ -1,287 +0,0 @@
"""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)))
+264
View File
@@ -0,0 +1,264 @@
"""A real compositor-shaped socket, because the sockets are what break.
Nothing here mocks :mod:`socket`. Each helper binds an actual ``AF_UNIX``
listener in a temporary directory laid out the way Hyprland lays one out
(``<runtime>/hypr/<signature>/.socket.sock``) and answers canned bytes, so the
tests drive the client's real connect, half-close, read-to-EOF and timeout
paths. A mocked socket would pass while the thing that actually fails in
production — a path that is gone, a peer that closes early, a reply that is
plain text where JSON was promised — went untested.
``AF_UNIX`` caps a path at 108 bytes, so the sockets live in a shallow
``mkdtemp`` rather than under ``tmp_path``, whose name encodes the test's.
"""
from __future__ import annotations
import shutil
import socket
import tempfile
import threading
from pathlib import Path
import pytest
#: Linux's sun_path is 108 bytes including the NUL.
SUN_PATH_MAX = 107
#: Returned by a handler that should keep the connection open and say nothing,
#: which is how a wedged compositor behaves and the only way to reach the
#: client's read timeout.
HANG = object()
#: Shapes taken from Hyprland's own ``-j`` output. Trimmed to the keys the
#: client reads, plus a few it must ignore.
MONITORS_JSON = """
[{"id": 0, "name": "HEADLESS-2", "description": "headless", "make": "", "model": "",
"x": 0, "y": 0, "width": 1280, "height": 720, "refreshRate": 60.0, "scale": 1.0,
"transform": 0, "focused": true, "activeWorkspace": {"id": 1000, "name": "1000"},
"specialWorkspace": {"id": 0, "name": ""}, "dpmsStatus": true},
{"id": 1, "name": "HEADLESS-3", "x": 1280, "y": 0, "width": 800, "height": 600,
"scale": 1.5, "focused": false}]
"""
WORKSPACES_JSON = """
[{"id": 1000, "name": "1000", "monitor": "HEADLESS-2", "monitorID": 0, "windows": 1,
"hasfullscreen": false, "lastwindow": "0x5d3d1c0", "lastwindowtitle": "foot"},
{"id": -99, "name": "special:quarantine", "monitor": "HEADLESS-2", "windows": 0}]
"""
CLIENTS_JSON = """
[{"address": "0x5d3d1c0", "mapped": true, "hidden": false, "at": [0, 0],
"size": [1280, 720], "workspace": {"id": 1000, "name": "1000"}, "floating": false,
"monitor": 0, "class": "foot", "initialClass": "hh-foot-v7r4li",
"title": "hermes: ~, build, and notes", "initialTitle": "foot", "pid": 4242,
"xwayland": false, "pinned": false, "fullscreen": 0},
{"address": "0x5d4aa10", "mapped": false, "hidden": true, "class": "chromium",
"initialClass": "", "title": "", "pid": 0, "monitor": null}]
"""
CURSORPOS_JSON = '{"x": 640, "y": 360}'
VERSION_TEXT = (
"Hyprland 0.41.2 built from branch at commit 0000000 (). Date: 2026-01-01\n"
"Tag: v0.41.2, commits: 5000\n\nflags: (if any)\ndebug\n"
)
#: What a well-behaved compositor answers, keyed by the bare command.
GOOD_REPLIES = {
"monitors": MONITORS_JSON,
"workspaces": WORKSPACES_JSON,
"clients": CLIENTS_JSON,
"cursorpos": CURSORPOS_JSON,
"version": VERSION_TEXT,
}
def check_path(path: Path) -> None:
if len(str(path).encode()) > SUN_PATH_MAX:
pytest.skip(f"socket path too long for AF_UNIX ({len(str(path))} bytes): {path}")
class RequestServer:
"""One listening request socket, answering through a handler.
The handler is called with ``(flags, command)`` split the way Hyprland
splits them — everything before the first ``/`` is flags — and returns the
reply, ``None`` to close without answering, or :data:`HANG`.
"""
def __init__(self, path: Path, handler) -> None:
check_path(path)
self.path = path
self.handler = handler
self.requests: list[tuple[str, str]] = []
self._stop = threading.Event()
self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._sock.bind(str(path))
self._sock.listen(8)
self._sock.settimeout(0.05)
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def _serve(self) -> None:
while not self._stop.is_set():
conn = self._accept()
if conn is None:
continue
try:
self._handle(conn)
finally:
conn.close()
def _accept(self):
"""``None`` on a poll timeout, so :meth:`stop` is not waited out.
Closing a listening socket does not reliably wake a thread blocked in
``accept``, which would make every test pay the join timeout.
"""
try:
conn, _ = self._sock.accept()
except (TimeoutError, socket.timeout):
return None
except OSError:
self._stop.set()
return None
return conn
def _handle(self, conn: socket.socket) -> None:
# The client half-closes after writing, so the request ends at EOF.
conn.settimeout(5.0)
received = b""
while True:
try:
chunk = conn.recv(4096)
except OSError:
return
if not chunk:
break
received += chunk
text = received.decode("utf-8", errors="replace")
flags, separator, command = text.partition("/")
if not separator:
flags, command = "", text
self.requests.append((flags, command))
reply = self.handler(flags, command)
if reply is HANG:
self._stop.wait(5.0)
return
if reply is None:
return
data = reply.encode() if isinstance(reply, str) else reply
try:
conn.sendall(data)
except OSError:
pass
def stop(self) -> None:
self._stop.set()
self._sock.close()
self._thread.join(timeout=5.0)
class EventServer:
"""One listening event socket that writes chunks, then closes or holds.
Chunks are written as given — not line by line — so a test can split an
event across two writes and prove the client reassembles it.
"""
def __init__(self, path: Path, chunks, close_after: bool = True) -> None:
check_path(path)
self.path = path
self.chunks = [c.encode() if isinstance(c, str) else c for c in chunks]
self.close_after = close_after
self.connections = 0
self._stop = threading.Event()
self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._sock.bind(str(path))
self._sock.listen(8)
self._sock.settimeout(0.05)
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def _serve(self) -> None:
while not self._stop.is_set():
try:
conn, _ = self._sock.accept()
except (TimeoutError, socket.timeout):
continue
except OSError:
return
self.connections += 1
try:
for chunk in self.chunks:
conn.sendall(chunk)
# Let the client see this write on its own, so a chunk
# boundary inside a line is a real boundary.
self._stop.wait(0.01)
if not self.close_after:
self._stop.wait(5.0)
except OSError:
pass
finally:
conn.close()
def stop(self) -> None:
self._stop.set()
self._sock.close()
self._thread.join(timeout=5.0)
@pytest.fixture
def runtime_dir():
"""A shallow temporary directory standing in for ``/run/hypr-stream``."""
path = Path(tempfile.mkdtemp(prefix="hhipc"))
try:
yield path
finally:
shutil.rmtree(path, ignore_errors=True)
@pytest.fixture
def instance(runtime_dir):
"""``<runtime_dir>/hypr/<signature>`` for one instance, created."""
directory = runtime_dir / "hypr" / "a1b2c3_1700000000"
directory.mkdir(parents=True)
return directory
@pytest.fixture
def servers(instance):
"""Factory for request/event servers on one instance, stopped at teardown."""
started: list = []
def start(handler=None, event_chunks=None, close_after=True):
request = None
events = None
if handler is not None:
request = RequestServer(instance / ".socket.sock", handler)
started.append(request)
if event_chunks is not None:
events = EventServer(instance / ".socket2.sock", event_chunks, close_after)
started.append(events)
return request, events
try:
yield start
finally:
for server in started:
server.stop()
@pytest.fixture
def good_handler():
"""Answers every wrapped command the way a live compositor does."""
def handler(flags, command):
return GOOD_REPLIES.get(command.strip(), "unknown request")
return handler
+131
View File
@@ -0,0 +1,131 @@
"""Finding the instance, and refusing to pick one when there is a choice.
Two instances and no signature is the dangerous case: a broker that guessed
would aim its queries — and later its pointer — at someone else's desktop.
"""
from __future__ import annotations
import socket
import pytest
from hhstreamd.ipc import SIGNATURE_ENV, CompositorUnavailable, HyprlandIPC
def bind(path):
"""A bound, listening socket at ``path``, so discovery sees a real one."""
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(str(path))
sock.listen(1)
return sock
def test_single_instance_is_discovered(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
sock = bind(instance / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir)
finally:
sock.close()
assert ipc.request_socket == instance / ".socket.sock"
assert ipc.event_socket == instance / ".socket2.sock"
def test_no_instance_directory_at_all(runtime_dir, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
with pytest.raises(CompositorUnavailable) as caught:
HyprlandIPC.discover(runtime_dir)
assert str(runtime_dir / "hypr") in str(caught.value)
def test_zero_instances_under_hypr(runtime_dir, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
(runtime_dir / "hypr").mkdir()
with pytest.raises(CompositorUnavailable, match="no instance"):
HyprlandIPC.discover(runtime_dir)
def test_two_instances_without_a_signature_refuses(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
other = runtime_dir / "hypr" / "deadbee_1700000001"
other.mkdir()
bind(instance / ".socket.sock").close()
with pytest.raises(CompositorUnavailable) as caught:
HyprlandIPC.discover(runtime_dir)
message = str(caught.value)
assert "2 instances" in message
assert instance.name in message and other.name in message
assert SIGNATURE_ENV in message
def test_two_instances_with_an_explicit_signature(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
other = runtime_dir / "hypr" / "deadbee_1700000001"
other.mkdir()
sock = bind(other / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir, signature=other.name)
finally:
sock.close()
assert ipc.request_socket == other / ".socket.sock"
def test_signature_from_the_environment(runtime_dir, instance, monkeypatch):
other = runtime_dir / "hypr" / "deadbee_1700000001"
other.mkdir()
monkeypatch.setenv(SIGNATURE_ENV, other.name)
sock = bind(other / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir)
finally:
sock.close()
assert ipc.request_socket == other / ".socket.sock"
def test_explicit_signature_beats_the_environment(runtime_dir, instance, monkeypatch):
monkeypatch.setenv(SIGNATURE_ENV, "not_this_one")
sock = bind(instance / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir, signature=instance.name)
finally:
sock.close()
assert ipc.request_socket == instance / ".socket.sock"
def test_signature_naming_a_missing_instance(runtime_dir, instance, monkeypatch):
monkeypatch.setenv(SIGNATURE_ENV, "gone_1700000002")
with pytest.raises(CompositorUnavailable, match="request socket"):
HyprlandIPC.discover(runtime_dir)
def test_instance_without_a_request_socket(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
with pytest.raises(CompositorUnavailable) as caught:
HyprlandIPC.discover(runtime_dir)
assert ".socket.sock" in str(caught.value)
def test_a_regular_file_is_not_a_socket(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
(instance / ".socket.sock").write_text("not a socket")
with pytest.raises(CompositorUnavailable, match="is not a socket"):
HyprlandIPC.discover(runtime_dir)
def test_a_signature_cannot_be_a_path(runtime_dir, instance):
with pytest.raises(CompositorUnavailable, match="not a directory name"):
HyprlandIPC.discover(runtime_dir, signature="../../elsewhere")
def test_an_empty_environment_signature_falls_through(runtime_dir, instance, monkeypatch):
"""An exported-but-empty variable is no signature, not a signature of ""."""
monkeypatch.setenv(SIGNATURE_ENV, "")
sock = bind(instance / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir)
finally:
sock.close()
assert ipc.request_socket == instance / ".socket.sock"
+197
View File
@@ -0,0 +1,197 @@
"""Event parsing, and a stream that must fail loudly when it stops.
The payload cases here are the ones that bite: a title full of commas (the
whole reason the last field absorbs the rest of the line), an event with no
payload at all, an event this module has never heard of, and a line delivered
in two pieces by the kernel.
"""
from __future__ import annotations
import threading
import time
import pytest
from hhstreamd.ipc import CompositorUnavailable, HyprlandIPC, parse_event
def test_openwindow_names_its_fields():
event = parse_event("openwindow>>0x5d3d1c0,1000,foot,hermes: ~")
assert event.name == "openwindow"
assert event.data["address"] == "0x5d3d1c0"
assert event.data["workspace"] == "1000"
assert event.data["class"] == "foot"
assert event.data["title"] == "hermes: ~"
assert event.data["args"] == ["0x5d3d1c0", "1000", "foot", "hermes: ~"]
assert event.data["raw"] == "0x5d3d1c0,1000,foot,hermes: ~"
def test_a_title_keeps_its_commas():
"""A naive split(",") loses the end of the title; this is that regression."""
event = parse_event("openwindow>>0x1,1000,foot,hermes: ~, build, and notes")
assert event.data["title"] == "hermes: ~, build, and notes"
assert len(event.data["args"]) == 4
def test_windowtitle_v2_absorbs_commas_too():
event = parse_event("windowtitlev2>>0x1,a,b,c")
assert event.data == {
"raw": "0x1,a,b,c",
"args": ["0x1", "a,b,c"],
"address": "0x1",
"title": "a,b,c",
}
def test_an_empty_payload_names_nothing():
"""``configreloaded>>`` carried no values; "" is not a value."""
event = parse_event("configreloaded>>")
assert event.name == "configreloaded"
assert event.data == {"raw": "", "args": []}
def test_a_single_field_event():
event = parse_event("monitorremoved>>HEADLESS-3")
assert event.data["name"] == "HEADLESS-3"
assert event.data["args"] == ["HEADLESS-3"]
def test_a_short_payload_names_only_what_arrived():
"""An older Hyprland sending fewer fields must not invent the rest."""
event = parse_event("openwindow>>0x1,1000")
assert event.data["address"] == "0x1"
assert event.data["workspace"] == "1000"
assert "class" not in event.data
assert "title" not in event.data
def test_an_unknown_event_is_still_usable():
event = parse_event("somethingnew>>a,b,c")
assert event.name == "somethingnew"
assert event.data == {"raw": "a,b,c", "args": ["a", "b", "c"]}
def test_trailing_newline_is_not_part_of_the_payload():
assert parse_event("workspace>>1000\n").data["name"] == "1000"
assert parse_event("workspace>>1000\r\n").data["name"] == "1000"
@pytest.mark.parametrize("line", ["workspace", "", " ", ">>1000", "workspace>1000"])
def test_a_line_with_no_separator_is_malformed(line):
with pytest.raises(CompositorUnavailable, match="name>>payload"):
parse_event(line)
@pytest.fixture
def ipc(instance):
client = HyprlandIPC(instance / ".socket.sock", instance / ".socket2.sock")
yield client
client.close()
def test_the_stream_yields_events_then_raises_at_eof(servers, ipc):
chunks = [
"openwindow>>0x1,1000,foot,hermes: ~, build\n",
# One line split across two writes: the client must reassemble it
# rather than parse half of it.
"closewin",
"dow>>0x1\nworkspacev2>>1000,1000\n",
]
servers(event_chunks=chunks)
stream = ipc.events()
first = next(stream)
assert first.name == "openwindow"
assert first.data["title"] == "hermes: ~, build"
assert next(stream).name == "closewindow"
third = next(stream)
assert (third.data["id"], third.data["name"]) == ("1000", "1000")
# The compositor closed. An iterator that merely stopped would be
# indistinguishable from an idle desktop.
with pytest.raises(CompositorUnavailable, match="event stream ended"):
next(stream)
def test_an_unterminated_tail_is_reported(servers, ipc):
servers(event_chunks=["openwindow>>0x1,1000,foot,t\nhalf-an-ev"])
stream = ipc.events()
assert next(stream).name == "openwindow"
with pytest.raises(CompositorUnavailable, match="unterminated"):
next(stream)
def test_a_malformed_line_in_the_stream(servers, ipc):
servers(event_chunks=["this is not an event\n"])
stream = ipc.events()
with pytest.raises(CompositorUnavailable, match="name>>payload"):
next(stream)
def test_a_missing_event_socket(instance, ipc):
with pytest.raises(CompositorUnavailable) as caught:
ipc.events()
assert ".socket2.sock" in str(caught.value)
def test_no_event_socket_configured(instance):
ipc = HyprlandIPC(instance / ".socket.sock")
with pytest.raises(CompositorUnavailable, match="no event socket"):
ipc.events()
def test_the_connection_is_made_by_events_not_by_the_first_next(servers, ipc):
"""So the caller that asked for the stream is the one told it failed."""
_, events = servers(event_chunks=["workspace>>1000\n"], close_after=False)
stream = ipc.events()
# ``connect`` returns as soon as the listen backlog takes it, so the
# server's own accept lags by a scheduling quantum; the claim is that the
# connection exists before anything iterates, not that it is instantaneous.
deadline = time.monotonic() + 5.0
while events.connections == 0 and time.monotonic() < deadline:
time.sleep(0.01)
assert events.connections == 1
assert next(stream).name == "workspace"
def test_close_unblocks_a_waiting_reader(servers, ipc):
"""A blocked reader must end when the broker shuts the client down.
``close()`` shuts the socket down rather than only closing it, because a
bare close does not wake a thread already sitting in ``recv``.
"""
servers(event_chunks=["workspace>>1000\n"], close_after=False)
stream = ipc.events()
assert next(stream).name == "workspace"
outcome = []
def read_until_it_fails():
try:
next(stream)
except BaseException as exc: # noqa: BLE001 - recorded, then asserted
outcome.append(exc)
reader = threading.Thread(target=read_until_it_fails, daemon=True)
reader.start()
# The reader is blocked in recv on an open, silent socket.
reader.join(timeout=0.2)
assert reader.is_alive()
ipc.close()
reader.join(timeout=5.0)
assert not reader.is_alive()
assert isinstance(outcome[0], CompositorUnavailable)
def test_close_is_idempotent(servers, ipc):
servers(event_chunks=["workspace>>1000\n"], close_after=False)
ipc.events()
ipc.close()
ipc.close()
+240
View File
@@ -0,0 +1,240 @@
"""The request socket, against a real listener.
Every test here connects over ``AF_UNIX`` to a socket the fixture bound, so the
failures that matter — a path that is gone, a peer that refuses, a peer that
closes mid-reply, a peer that never answers — are produced rather than
simulated.
"""
from __future__ import annotations
import socket
import pytest
from hhstreamd.ipc import CompositorUnavailable, CursorPos, HyprlandIPC
from conftest import HANG
@pytest.fixture
def ipc(instance):
client = HyprlandIPC(instance / ".socket.sock", instance / ".socket2.sock")
yield client
client.close()
def test_version_is_the_banner_verbatim(servers, good_handler, ipc):
request, _ = servers(good_handler)
assert ipc.version().startswith("Hyprland 0.41.2 built from branch")
assert "Tag: v0.41.2" in ipc.version()
# Text, not JSON, and the command carries a leading "/" so an argument
# containing a slash could never be read as output flags.
assert request.requests[0] == ("", "version")
def test_monitors(servers, good_handler, ipc):
request, _ = servers(good_handler)
monitors = ipc.monitors()
assert [m.name for m in monitors] == ["HEADLESS-2", "HEADLESS-3"]
first = monitors[0]
assert (first.x, first.y, first.width, first.height) == (0, 0, 1280, 720)
assert first.scale == 1.0
assert first.active_workspace_id == 1000
# The second monitor carries no activeWorkspace at all: a defined None.
assert monitors[1].active_workspace_id is None
assert monitors[1].scale == 1.5
assert request.requests == [("j", "monitors")]
def test_workspaces(servers, good_handler, ipc):
servers(good_handler)
workspaces = ipc.workspaces()
assert [w.id for w in workspaces] == [1000, -99]
assert workspaces[0].monitor == "HEADLESS-2"
assert workspaces[0].windows == 1
assert workspaces[0].is_special is False
# No "special" key in this reply: the negative id and the name prefix are
# what every Hyprland has agreed on.
assert workspaces[1].is_special is True
def test_clients(servers, good_handler, ipc):
request, _ = servers(good_handler)
clients = ipc.clients()
assert len(clients) == 2
foot, chromium = clients
assert foot.address == "0x5d3d1c0"
assert foot.pid == 4242
assert foot.workspace_id == 1000
assert foot.class_ == "foot"
assert foot.initial_class == "hh-foot-v7r4li"
# A title with commas in it survives whole; the broker shows this to a user.
assert foot.title == "hermes: ~, build, and notes"
assert foot.stable_id == "hh-foot-v7r4li:4242"
assert foot.visible is True
# clients -j reports the monitor as an index, not a name; the field is text
# so that None keeps its one meaning of "the reply said nothing".
assert foot.monitor == "0"
assert chromium.visible is False
assert chromium.monitor is None
assert chromium.workspace_id is None
assert chromium.stable_id == "0x5d4aa10"
assert request.requests == [("j", "clients")]
def test_cursorpos(servers, good_handler, ipc):
servers(good_handler)
assert ipc.cursorpos() == CursorPos(x=640, y=360)
def test_query_passes_a_command_through_untouched(servers, ipc):
seen = []
def handler(flags, command):
seen.append((flags, command))
return "ok"
servers(handler)
assert ipc.query("dispatch exec /usr/bin/true") == "ok"
# The slash in the argument must not be read as a flag separator.
assert seen == [("", "dispatch exec /usr/bin/true")]
def test_query_keeps_an_explicit_flag_prefix(servers, ipc):
seen = []
def handler(flags, command):
seen.append((flags, command))
return "[]"
servers(handler)
assert ipc.query("j/devices") == "[]"
assert seen == [("j", "devices")]
def test_an_empty_request_is_refused_before_connecting(ipc):
with pytest.raises(CompositorUnavailable, match="empty request"):
ipc.query(" ")
@pytest.mark.parametrize("method", ["monitors", "workspaces", "clients", "cursorpos"])
def test_plain_text_where_json_was_promised(servers, ipc, method):
"""What Hyprland answers for a command it does not know."""
servers(lambda flags, command: "unknown request")
with pytest.raises(CompositorUnavailable, match="not JSON"):
getattr(ipc, method)()
def test_a_json_object_where_a_list_belongs(servers, ipc):
servers(lambda flags, command: '{"monitors": []}')
with pytest.raises(CompositorUnavailable, match="expected a JSON list"):
ipc.monitors()
def test_a_list_of_scalars(servers, ipc):
servers(lambda flags, command: '["HEADLESS-2"]')
with pytest.raises(CompositorUnavailable, match="expected objects"):
ipc.monitors()
def test_a_client_without_an_address_is_malformed(servers, ipc):
"""The one key whose absence makes the record meaningless."""
servers(lambda flags, command: '[{"class": "foot", "pid": 1}]')
with pytest.raises(CompositorUnavailable, match="no address"):
ipc.clients()
def test_a_monitor_without_a_name_is_malformed(servers, ipc):
servers(lambda flags, command: '[{"width": 1280}]')
with pytest.raises(CompositorUnavailable, match="no name"):
ipc.monitors()
def test_a_workspace_without_an_id_is_malformed(servers, ipc):
servers(lambda flags, command: '[{"name": "1000"}]')
with pytest.raises(CompositorUnavailable, match="no id"):
ipc.workspaces()
def test_missing_keys_degrade_rather_than_raise_keyerror(servers, ipc):
"""A reply from a Hyprland that reports less than this one expects."""
servers(lambda flags, command: '[{"address": "0x1"}]')
(client,) = ipc.clients()
assert client.pid == -1
assert client.workspace_id is None
assert client.monitor is None
assert (client.class_, client.initial_class, client.title) == ("", "", "")
assert client.stable_id == "0x1"
# Nothing said it was unmapped, so it is not reported as gone.
assert client.visible is True
def test_cursorpos_without_coordinates(servers, ipc):
servers(lambda flags, command: '{"ok": true}')
with pytest.raises(CompositorUnavailable, match="x and y"):
ipc.cursorpos()
def test_cursorpos_with_non_numeric_coordinates(servers, ipc):
servers(lambda flags, command: '{"x": "left", "y": null}')
with pytest.raises(CompositorUnavailable, match="not numbers"):
ipc.cursorpos()
def test_connection_closed_mid_reply(servers, ipc):
"""The compositor dies while writing: a truncated reply, never a guess."""
servers(lambda flags, command: '[{"address": "0x5d3d1c0", "pid": 4242, "cla')
with pytest.raises(CompositorUnavailable, match="not JSON"):
ipc.clients()
def test_connection_closed_with_no_reply_at_all(servers, ipc):
servers(lambda flags, command: None)
with pytest.raises(CompositorUnavailable, match="empty reply"):
ipc.workspaces()
with pytest.raises(CompositorUnavailable, match="empty reply"):
ipc.version()
def test_missing_socket(instance):
ipc = HyprlandIPC(instance / ".socket.sock")
with pytest.raises(CompositorUnavailable) as caught:
ipc.clients()
assert str(instance / ".socket.sock") in str(caught.value)
def test_nothing_listening(instance, ipc):
"""A socket left behind by a compositor that is gone: ECONNREFUSED."""
stale = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
stale.bind(str(instance / ".socket.sock"))
try:
with pytest.raises(CompositorUnavailable, match="request socket"):
ipc.monitors()
finally:
stale.close()
def test_a_compositor_that_never_answers(servers, ipc):
"""Accepted, then silence: the read timeout, exercised for real."""
servers(lambda flags, command: HANG)
ipc.request_timeout_s = 0.3
with pytest.raises(CompositorUnavailable, match="did not answer"):
ipc.clients()
def test_each_request_is_its_own_connection(servers, good_handler, ipc):
"""What hyprctl does, and what the compositor expects: no session state."""
request, _ = servers(good_handler)
ipc.monitors()
ipc.clients()
ipc.clients()
assert request.requests == [("j", "monitors"), ("j", "clients"), ("j", "clients")]
-42
View File
@@ -1,42 +0,0 @@
"""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)
-245
View File
@@ -1,245 +0,0 @@
"""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)
-244
View File
@@ -1,244 +0,0 @@
"""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"}
-136
View File
@@ -1,136 +0,0 @@
"""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)
-94
View File
@@ -1,94 +0,0 @@
"""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
-93
View File
@@ -1,93 +0,0 @@
"""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))