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