Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20b2aee109 | ||
|
|
e8b3855a05 | ||
|
|
d45219994e | ||
|
|
8c180ec938 | ||
|
|
28b4b4b2cd | ||
|
|
798ca1a4c1 | ||
|
|
eb2aec99e7 | ||
|
|
9b77c77ee8 | ||
|
|
06041030b0 | ||
|
|
01460016e7 |
No files matched your search
+1
-1
@@ -152,7 +152,7 @@ What the dump contains, and where it comes from in the guest:
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `units` | `systemctl list-units --all 'hyprland*'` |
|
| `units` | `systemctl list-units --all 'hyprland*'` |
|
||||||
| per-unit `status` / `journalctl` | `hyprland-headless.service` and `hyprland-headless-stream.service`, 200 lines each |
|
| per-unit `status` / `journalctl` | `hyprland-headless.service` and `hyprland-headless-stream.service`, 200 lines each |
|
||||||
| `socket and runtime directories` | `/run/hyprland-headless-stream`, `/run/user/*` |
|
| `socket and runtime directories` | `/run/hypr-stream`, `/run/user/*` |
|
||||||
| `hyprland logs` | every `hyprland*.log` found under `/run`, `/var/log`, `/tmp`, `/home` |
|
| `hyprland logs` | every `hyprland*.log` found under `/run`, `/var/log`, `/tmp`, `/home` |
|
||||||
| `hyprctl monitors` | run once per instance found, with the right `XDG_RUNTIME_DIR` and `HYPRLAND_INSTANCE_SIGNATURE` |
|
| `hyprctl monitors` | run once per instance found, with the right `XDG_RUNTIME_DIR` and `HYPRLAND_INSTANCE_SIGNATURE` |
|
||||||
| `processes` | `ps aux` filtered to `hypr`, `hhstream`, `grim` |
|
| `processes` | `ps aux` filtered to `hypr`, `hhstream`, `grim` |
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ Two parts:
|
|||||||
Then any consumer:
|
Then any consumer:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
hhstream-client --socket /run/hyprland-headless-stream/stream.sock --count 1 --out frame.png
|
hhstream-client --socket /run/hypr-stream/stream.sock --count 1 --out frame.png
|
||||||
```
|
```
|
||||||
|
|
||||||
The socket is a plain file descriptor: the server serves every client that
|
The socket is a plain file descriptor: the server serves every client that
|
||||||
|
|||||||
+21
-4
@@ -1,6 +1,14 @@
|
|||||||
# checks.<system>.unit -- the Python unit suite from tests/unit/, run against the
|
# checks.<system>.unit -- the Python unit suite from tests/, run against the
|
||||||
# package built by nix/package.nix, inside the build sandbox.
|
# package built by nix/package.nix, inside the build sandbox.
|
||||||
#
|
#
|
||||||
|
# The whole tree, not one directory: it used to take tests/unit alone, which
|
||||||
|
# meant the broker's and the pointer driver's suites (and the sessions one) were
|
||||||
|
# never collected by any check -- a gate that could not see 432 of 551 tests.
|
||||||
|
#
|
||||||
|
# pywayland is in the test environment because the pointer driver imports it;
|
||||||
|
# without it those tests fail as an import error rather than as the thing they
|
||||||
|
# test.
|
||||||
|
#
|
||||||
# nix/package.nix sets doCheck = false deliberately, so this is the only place
|
# nix/package.nix sets doCheck = false deliberately, so this is the only place
|
||||||
# the suite runs in a build.
|
# the suite runs in a build.
|
||||||
{
|
{
|
||||||
@@ -10,13 +18,13 @@
|
|||||||
hhstream,
|
hhstream,
|
||||||
}:
|
}:
|
||||||
let
|
let
|
||||||
pytestEnv = python3.withPackages (ps: [ ps.pytest ]);
|
pytestEnv = python3.withPackages (ps: [ ps.pytest ps.pywayland ]);
|
||||||
|
|
||||||
# Only the suite itself, so an editor's droppings or a local .pytest_cache
|
# Only the suite itself, so an editor's droppings or a local .pytest_cache
|
||||||
# cannot change the derivation's hash.
|
# cannot change the derivation's hash.
|
||||||
testSrc = lib.cleanSourceWith {
|
testSrc = lib.cleanSourceWith {
|
||||||
name = "hhstream-unit-tests";
|
name = "hhstream-tests";
|
||||||
src = ../tests/unit;
|
src = ../tests;
|
||||||
filter =
|
filter =
|
||||||
path: type:
|
path: type:
|
||||||
let
|
let
|
||||||
@@ -35,6 +43,14 @@ runCommand "hhstream-unit"
|
|||||||
cp -r ${testSrc} suite
|
cp -r ${testSrc} suite
|
||||||
chmod -R u+w suite
|
chmod -R u+w suite
|
||||||
|
|
||||||
|
# `tests/sessions/integration/test_lifecycle.py` locates the repository by
|
||||||
|
# looking upward for a `pyproject.toml` (it needs the root for `src/` on
|
||||||
|
# PYTHONPATH and as a cwd for the subprocesses it spawns). In a build there is
|
||||||
|
# no repository above the copied suite, so it raises at import time and takes
|
||||||
|
# the whole run down as a collection error. Giving it the marker it documents
|
||||||
|
# is the fix; the test itself is hermetic -- no compositor, no network.
|
||||||
|
cp ${../pyproject.toml} suite/pyproject.toml
|
||||||
|
|
||||||
# The package is an application, so its library is not on the default path:
|
# The package is an application, so its library is not on the default path:
|
||||||
# point PYTHONPATH at what nix/package.nix installed. Importing it here rather
|
# point PYTHONPATH at what nix/package.nix installed. Importing it here rather
|
||||||
# than letting pytest do it makes a packaging problem distinguishable from a
|
# than letting pytest do it makes a packaging problem distinguishable from a
|
||||||
@@ -43,6 +59,7 @@ runCommand "hhstream-unit"
|
|||||||
export PYTHONDONTWRITEBYTECODE=1
|
export PYTHONDONTWRITEBYTECODE=1
|
||||||
export HOME=$PWD
|
export HOME=$PWD
|
||||||
python3 -c 'import hhstream; print("testing hhstream", hhstream.__version__, "from", hhstream.__file__)'
|
python3 -c 'import hhstream; print("testing hhstream", hhstream.__version__, "from", hhstream.__file__)'
|
||||||
|
python3 -c 'import hhstreamd.ipc, hhstream_pointer; print("broker ipc client + pointer driver import")'
|
||||||
|
|
||||||
set +e
|
set +e
|
||||||
pytest suite \
|
pytest suite \
|
||||||
|
|||||||
+1
-1
@@ -13,7 +13,7 @@
|
|||||||
width ? 1280,
|
width ? 1280,
|
||||||
height ? 720,
|
height ? 720,
|
||||||
fps ? 30,
|
fps ? 30,
|
||||||
socketPath ? "/run/hyprland-headless-stream/stream.sock",
|
socketPath ? "/run/hypr-stream/stream.sock",
|
||||||
}:
|
}:
|
||||||
testers.runNixOSTest {
|
testers.runNixOSTest {
|
||||||
name = "hhstream-vm-basic";
|
name = "hhstream-vm-basic";
|
||||||
|
|||||||
@@ -20,7 +20,7 @@
|
|||||||
width ? 1280,
|
width ? 1280,
|
||||||
height ? 720,
|
height ? 720,
|
||||||
fps ? 30,
|
fps ? 30,
|
||||||
socketPath ? "/run/hyprland-headless-stream/stream.sock",
|
socketPath ? "/run/hypr-stream/stream.sock",
|
||||||
}:
|
}:
|
||||||
testers.runNixOSTest {
|
testers.runNixOSTest {
|
||||||
name = "hhstream-vm-hyprland";
|
name = "hhstream-vm-hyprland";
|
||||||
@@ -111,8 +111,8 @@ testers.runNixOSTest {
|
|||||||
# compositor's IPC socket even though it belongs to `hhstream`.
|
# compositor's IPC socket even though it belongs to `hhstream`.
|
||||||
HYPRCTL_MONITORS = (
|
HYPRCTL_MONITORS = (
|
||||||
"set -eu; "
|
"set -eu; "
|
||||||
"sig=$(ls -1 /run/hyprland-headless-stream/hypr | head -n1); "
|
"sig=$(ls -1 /run/hypr-stream/hypr | head -n1); "
|
||||||
"XDG_RUNTIME_DIR=/run/hyprland-headless-stream"
|
"XDG_RUNTIME_DIR=/run/hypr-stream"
|
||||||
" HYPRLAND_INSTANCE_SIGNATURE=$sig hyprctl -j monitors"
|
" HYPRLAND_INSTANCE_SIGNATURE=$sig hyprctl -j monitors"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -177,8 +177,8 @@ testers.runNixOSTest {
|
|||||||
# minimal PATH, not the guest's environment.systemPackages.
|
# minimal PATH, not the guest's environment.systemPackages.
|
||||||
status, out = machine.execute(
|
status, out = machine.execute(
|
||||||
"systemd-run --pipe --wait --uid=hhstream"
|
"systemd-run --pipe --wait --uid=hhstream"
|
||||||
" --setenv=XDG_RUNTIME_DIR=/run/hyprland-headless-stream"
|
" --setenv=XDG_RUNTIME_DIR=/run/hypr-stream"
|
||||||
" --setenv=WAYLAND_DISPLAY=$(cd /run/hyprland-headless-stream"
|
" --setenv=WAYLAND_DISPLAY=$(cd /run/hypr-stream"
|
||||||
" && ls -1 wayland-* | grep -v '\.lock$' | head -n1)"
|
" && ls -1 wayland-* | grep -v '\.lock$' | head -n1)"
|
||||||
" sh -c '${grim}/bin/grim -t png - > /tmp/direct.png' 2>&1",
|
" sh -c '${grim}/bin/grim -t png - > /tmp/direct.png' 2>&1",
|
||||||
timeout=120,
|
timeout=120,
|
||||||
|
|||||||
@@ -214,7 +214,7 @@ testers.runNixOSTest {
|
|||||||
CONTROL = "${controlSocket}"
|
CONTROL = "${controlSocket}"
|
||||||
CONTROL_DIR = "/run/hhstream"
|
CONTROL_DIR = "/run/hhstream"
|
||||||
IDLE_TIMEOUT = ${toString idleTimeout}.0
|
IDLE_TIMEOUT = ${toString idleTimeout}.0
|
||||||
COMPOSITOR_RUNTIME = "/run/hyprland-headless-stream"
|
COMPOSITOR_RUNTIME = "/run/hypr-stream"
|
||||||
|
|
||||||
# The module pins the compositor's XDG_RUNTIME_DIR; the instance signature
|
# The module pins the compositor's XDG_RUNTIME_DIR; the instance signature
|
||||||
# under it is the only part not known ahead of time. Root may connect to
|
# under it is the only part not known ahead of time. Root may connect to
|
||||||
|
|||||||
+66
-10
@@ -9,7 +9,20 @@ else. If something here is wrong or missing, **stop and report it in your final
|
|||||||
message** — the parent edits this file, not you. Do not widen your slice to work
|
message** — the parent edits this file, not you. Do not widen your slice to work
|
||||||
around a gap.
|
around a gap.
|
||||||
|
|
||||||
Version: sessions-v1 (2026-10-01).
|
Version: sessions-v2 (2026-10-02). v1 was the freeze the four slices built against;
|
||||||
|
v2 records the decisions their reports asked for. Every v2 change is either a
|
||||||
|
clarification or an addition — **no v1 signature changed meaning** — so v1 code
|
||||||
|
stays valid except where noted. Changes:
|
||||||
|
|
||||||
|
| § | Change | Why |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| §3.1 | `Monitor` gains `id: int` | `clients -j` reports a client's monitor as a numeric **index**, `Workspace.monitor` as a **name**, so without an id there is no way to join a client to its output. Slice D's aiming is output-local. |
|
||||||
|
| §3.1 | `Client.stable_id` defined as `"<initial_class>:<pid>"` (fallback `address`); absent `pid` becomes `-1`; `Event.data` is a per-event field table plus always-present `raw`/`args`; `request_timeout_s` is an overridable class attribute (2 s); `version()` returns the compositor's banner verbatim | What slice B had to decide, now written down instead of re-derived. |
|
||||||
|
| §3.2 | `quarantine_argv()` replaces `quarantine_plan()`, returning `list[list[str]] \| None` | A quarantine rule is not a container: no output, no numbered workspace, no mode, and `container_plan` refuses a zero size. **Integration updates `containers.py` and its tests to this shape.** |
|
||||||
|
| §3.3 | `mark()` added; `expire()` precedence documented | §3.3 gave no way to record a position, so `LeaseOutcome.bookmark` could only ever be `None` and `pointer.acquire … restore?` had nothing to restore. |
|
||||||
|
| §3.4 | Vendored protocol is permitted, and the XML path is corrected | The v1 path was wrong (`share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml`). |
|
||||||
|
| §5 | The broker state dir is stated as an *option default* with this machine's override; the frame socket is named | §5's value was the deployed one, not the default, and the frame socket was missing while `docs/CONTRACT.md` still documents the old one. |
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -57,7 +70,7 @@ class CompositorUnavailable(Exception):
|
|||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class Monitor:
|
class Monitor:
|
||||||
name: str; x: int; y: int; width: int; height: int; scale: float
|
id: int; name: str; x: int; y: int; width: int; height: int; scale: float
|
||||||
active_workspace_id: int | None
|
active_workspace_id: int | None
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -103,6 +116,24 @@ Rules: every method raises `CompositorUnavailable` rather than returning a
|
|||||||
guess. `clients()` parses `clients -j`; `monitors()` parses `monitors -j`;
|
guess. `clients()` parses `clients -j`; `monitors()` parses `monitors -j`;
|
||||||
`workspaces()` parses `workspaces -j`. Stdlib only.
|
`workspaces()` parses `workspaces -j`. Stdlib only.
|
||||||
|
|
||||||
|
Decisions, so they are not re-derived per caller:
|
||||||
|
|
||||||
|
- **A client's monitor is an index, an output's name is a name.** `Client.monitor`
|
||||||
|
is the numeric index rendered as text (or `None` when the reply said nothing);
|
||||||
|
join it to a `Monitor` through `Monitor.id`. `Workspace.monitor` is a name.
|
||||||
|
- **`Client.stable_id`** is `"<initial_class>:<pid>"`, falling back to
|
||||||
|
`address`. Hyprland publishes no such key; this is the identity that survives a
|
||||||
|
remap, and the launcher sets the class per session.
|
||||||
|
- **An absent `pid` becomes `-1`**, not `0` — no process has pid `-1`.
|
||||||
|
- **Events are positional on the wire** (`name>>a,b,c`). `Event.data` is built
|
||||||
|
from a per-event field table, with the last named field absorbing the remaining
|
||||||
|
commas (titles contain them); `raw` and `args` are always present so an unknown
|
||||||
|
event is still usable. An event that carries fewer fields than the table names
|
||||||
|
only what arrived — never invented empties.
|
||||||
|
- **`request_timeout_s`** is a class attribute (2 s) on `HyprlandIPC` because
|
||||||
|
`__init__` is frozen.
|
||||||
|
- **`version()` returns the compositor's banner verbatim**, not a parsed number.
|
||||||
|
|
||||||
### 3.2 `hhstreamd/containers.py` (C)
|
### 3.2 `hhstreamd/containers.py` (C)
|
||||||
|
|
||||||
**Pure logic. No I/O, no subprocess, no socket, no import of `ipc.py`.** It
|
**Pure logic. No I/O, no subprocess, no socket, no import of `ipc.py`.** It
|
||||||
@@ -139,9 +170,18 @@ def app_id_for(session_id: str) -> str: ...
|
|||||||
# the bare "hh-<session-id>" the launcher sets on the app; "^hh-<session-id>$"
|
# the bare "hh-<session-id>" the launcher sets on the app; "^hh-<session-id>$"
|
||||||
# is built in container_plan.
|
# is built in container_plan.
|
||||||
|
|
||||||
def quarantine_plan(quarantine_workspace: str) -> ContainerPlan | None: ...
|
def quarantine_argv(quarantine_workspace: str) -> list[list[str]] | None: ...
|
||||||
# the backstop: every window matching no container goes to
|
# the backstop: every window matching no container goes to
|
||||||
# special:quarantine. Returns the keyword argv, or None if disabled.
|
# special:quarantine. Returns the keyword argv, or None when the target is
|
||||||
|
# blank/whitespace (which is how "disabled" is spelled).
|
||||||
|
#
|
||||||
|
# Deliberately NOT a ContainerPlan: a quarantine rule has no output, no
|
||||||
|
# numbered workspace and no mode. The argv shape mirrors the per-session
|
||||||
|
# rule, with a catch-all class:
|
||||||
|
# ["hyprctl","keyword","windowrule",
|
||||||
|
# f"match:initial_class .*, workspace {target}"]
|
||||||
|
# It must be installed BEFORE any per-session rule, or the catch-all wins.
|
||||||
|
# That ordering is the caller's, and this module cannot enforce it.
|
||||||
|
|
||||||
class WorkspaceAllocator:
|
class WorkspaceAllocator:
|
||||||
def __init__(self, base: int, count: int) -> None: ...
|
def __init__(self, base: int, count: int) -> None: ...
|
||||||
@@ -183,6 +223,11 @@ class PointerLease:
|
|||||||
def acquire(self, session_id: str) -> str: ... # -> lease_id; raises LeaseBusy
|
def acquire(self, session_id: str) -> str: ... # -> lease_id; raises LeaseBusy
|
||||||
def refresh(self, session_id: str, lease_id: str) -> None: ... # raises LeaseInvalid
|
def refresh(self, session_id: str, lease_id: str) -> None: ... # raises LeaseInvalid
|
||||||
def release(self, session_id: str, lease_id: str, reason: str) -> LeaseOutcome: ...
|
def release(self, session_id: str, lease_id: str, reason: str) -> LeaseOutcome: ...
|
||||||
|
def mark(self, session_id: str, lease_id: str, bookmark: Bookmark) -> None: ...
|
||||||
|
# records where the cursor was left, called on every move and before
|
||||||
|
# release. Added in v2: without it LeaseOutcome.bookmark could only ever
|
||||||
|
# be None, so `pointer.acquire --restore` had nothing to restore.
|
||||||
|
# raises LeaseInvalid for a non-holder.
|
||||||
def state(self) -> dict: ... # {"holder": str|None, "since": float|None,
|
def state(self) -> dict: ... # {"holder": str|None, "since": float|None,
|
||||||
# "lease_id": str|None, "expires_at": float|None}
|
# "lease_id": str|None, "expires_at": float|None}
|
||||||
def expire(self) -> LeaseInfo | None: ...
|
def expire(self) -> LeaseInfo | None: ...
|
||||||
@@ -192,6 +237,13 @@ class PointerLease:
|
|||||||
def unpress(self, session_id: str, button: str) -> list[str]: ...
|
def unpress(self, session_id: str, button: str) -> list[str]: ...
|
||||||
def pressed(self) -> list[str]: ...
|
def pressed(self) -> list[str]: ...
|
||||||
|
|
||||||
|
**`expire()` carries no bookmark and no lifted buttons** — it returns the lease
|
||||||
|
that was released, nothing more. The broker therefore has two duties on expiry:
|
||||||
|
read `pressed()` *before* calling `expire()` if it wants the lease's view of what
|
||||||
|
was down, and lift those buttons on the driver (`release_all`), because the lease
|
||||||
|
cannot lift them itself. The bookmark is not `expire()`'s to keep: the broker
|
||||||
|
already stores it with the session (§1), which is where it belongs.
|
||||||
|
|
||||||
def window_to_absolute(point: tuple[int, int], window: tuple[int, int, int, int],
|
def window_to_absolute(point: tuple[int, int], window: tuple[int, int, int, int],
|
||||||
monitor: tuple[int, int, int, int]) -> tuple[float, float]:
|
monitor: tuple[int, int, int, int]) -> tuple[float, float]:
|
||||||
# point is window-local pixels; window is (x, y, w, h) global; monitor is
|
# point is window-local pixels; window is (x, y, w, h) global; monitor is
|
||||||
@@ -209,11 +261,14 @@ blocked driver must not stall the broker.
|
|||||||
- Command line the module will pass, exactly:
|
- Command line the module will pass, exactly:
|
||||||
`hhstream-pointer --socket /run/hhstream/pointer.sock --compositor-runtime-dir /run/hypr-stream`
|
`hhstream-pointer --socket /run/hhstream/pointer.sock --compositor-runtime-dir /run/hypr-stream`
|
||||||
- Uses **pywayland** (packaged as `python3Packages.pywayland`) and the **wlr
|
- Uses **pywayland** (packaged as `python3Packages.pywayland`) and the **wlr
|
||||||
virtual pointer XML** from `pkgs.wlr-protocols`
|
virtual pointer XML** from `pkgs.wlr-protocols`, which lives at
|
||||||
(`share/wayland-protocols/wlr-unstable/zwlr-virtual-pointer-unstable-v1.xml`).
|
`share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml` (the v1
|
||||||
Compile the protocol at build time or vendor the generated module under your
|
contract had this path wrong: different middle directory, and no `z` prefix on
|
||||||
directory — your choice, stated in your report. `pyproject.toml` and
|
the filename). **Vendoring the generated module is explicitly permitted** (v2):
|
||||||
`nix/package.nix` are yours precisely so this is possible.
|
generating at build time puts a code generator between a checkout and a runnable
|
||||||
|
driver, and the dev shell has neither the XML nor a scanner. State which you
|
||||||
|
did. `pyproject.toml` and `nix/package.nix` are yours precisely so this is
|
||||||
|
possible.
|
||||||
- Binds `zwlr_virtual_pointer_manager_v1` **version 2** and uses
|
- Binds `zwlr_virtual_pointer_manager_v1` **version 2** and uses
|
||||||
`create_virtual_pointer_with_output(seat, output, id)` so coordinates are
|
`create_virtual_pointer_with_output(seat, output, id)` so coordinates are
|
||||||
output-local. If only version 1 is offered, **report it — never silently fall
|
output-local. If only version 1 is offered, **report it — never silently fall
|
||||||
@@ -269,9 +324,10 @@ reset the idle clock.
|
|||||||
| Compositor runtime dir | `/run/hypr-stream` — **must be ≤ 25 chars** (socket paths must stay under `sun_path`'s 108-byte limit) |
|
| Compositor runtime dir | `/run/hypr-stream` — **must be ≤ 25 chars** (socket paths must stay under `sun_path`'s 108-byte limit) |
|
||||||
| Compositor request socket | `<runtime dir>/hypr/<signature>/.socket.sock` |
|
| Compositor request socket | `<runtime dir>/hypr/<signature>/.socket.sock` |
|
||||||
| Compositor event socket | `<runtime dir>/hypr/<signature>/.socket2.sock` |
|
| Compositor event socket | `<runtime dir>/hypr/<signature>/.socket2.sock` |
|
||||||
|
| Frame socket (published) | `<runtime dir>/stream.sock` — default `/run/hypr-stream/stream.sock`. Also frozen in `docs/CONTRACT.md`, which v1 of this file left disagreeing with it. |
|
||||||
| Broker control socket | `/run/hhstream/control.sock` |
|
| Broker control socket | `/run/hhstream/control.sock` |
|
||||||
| Broker↔driver socket | `/run/hhstream/pointer.sock` |
|
| Broker↔driver socket | `/run/hhstream/pointer.sock` |
|
||||||
| Broker state dir | `/var/lib/hermes/hhstream-sessions` |
|
| Broker state dir | **option default** `/var/lib/hhstream`; this machine sets `/var/lib/hermes/hhstream-sessions` (`sessions.stateDir`). v1 listed the deployed value, which read as a contradiction of the module. |
|
||||||
| Session runtime dir | `/run/hhstream/sessions/<session-id>` |
|
| Session runtime dir | `/run/hhstream/sessions/<session-id>` |
|
||||||
| Container output name | `hh-<session-id>` |
|
| Container output name | `hh-<session-id>` |
|
||||||
| Container workspace band | `1000 + slot`, allocated from the registry's free list |
|
| Container workspace band | `1000 + slot`, allocated from the registry's free list |
|
||||||
|
|||||||
+10
-3
@@ -1,4 +1,11 @@
|
|||||||
# Wire contract (v1)
|
# Wire contract (v2)
|
||||||
|
|
||||||
|
**v2 changes nothing on the wire.** The published socket's documented *default*
|
||||||
|
moved from `/run/hyprland-headless-stream/stream.sock` to
|
||||||
|
`/run/hypr-stream/stream.sock`: the old runtime directory pushed the compositor's
|
||||||
|
own IPC *event* socket past `sun_path`'s 108-byte limit, so it never bound (see
|
||||||
|
`docs/CONTRACT-sessions.md` §5). Message sequence, framing and failure semantics
|
||||||
|
are unchanged, so a v1 reader is still a correct reader.
|
||||||
|
|
||||||
This file is the interface. Code on either side may change freely; **this
|
This file is the interface. Code on either side may change freely; **this
|
||||||
document may not**, without bumping the version.
|
document may not**, without bumping the version.
|
||||||
@@ -7,7 +14,7 @@ document may not**, without bumping the version.
|
|||||||
|
|
||||||
- Transport: `AF_UNIX`, `SOCK_STREAM`.
|
- Transport: `AF_UNIX`, `SOCK_STREAM`.
|
||||||
- Path: whatever `services.hyprland-headless-stream.socketPath` says.
|
- Path: whatever `services.hyprland-headless-stream.socketPath` says.
|
||||||
Default `/run/hyprland-headless-stream/stream.sock`.
|
Default `/run/hypr-stream/stream.sock`.
|
||||||
- Ownership: the service user (`user` option, default `hhstream`), mode `0660`.
|
- Ownership: the service user (`user` option, default `hhstream`), mode `0660`.
|
||||||
- The server accepts **any number of concurrent clients**. Each client gets its
|
- The server accepts **any number of concurrent clients**. Each client gets its
|
||||||
own copy of the header and of every subsequent frame. A client disconnecting
|
own copy of the header and of every subsequent frame. A client disconnecting
|
||||||
@@ -78,7 +85,7 @@ Namespace: `services.hyprland-headless-stream`
|
|||||||
| Option | Type | Default | Meaning |
|
| Option | Type | Default | Meaning |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `enable` | bool | `false` | turn everything on |
|
| `enable` | bool | `false` | turn everything on |
|
||||||
| `socketPath` | str | `/run/hyprland-headless-stream/stream.sock` | published socket |
|
| `socketPath` | str | `/run/hypr-stream/stream.sock` | published socket |
|
||||||
| `user` / `group` | str | `hhstream` | owner of the session and the socket |
|
| `user` / `group` | str | `hhstream` | owner of the session and the socket |
|
||||||
| `frameRate` | int | `30` | capture target, becomes `fps` in Hello |
|
| `frameRate` | int | `30` | capture target, becomes `fps` in Hello |
|
||||||
| `format` | enum `png`/`jpeg` | `png` | frame encoding |
|
| `format` | enum `png`/`jpeg` | `png` | frame encoding |
|
||||||
|
|||||||
+8
-4
@@ -93,10 +93,14 @@ Two notes for anyone editing that file:
|
|||||||
Hyprland draws the error *across the screen*, which lands in the recording.
|
Hyprland draws the error *across the screen*, which lands in the recording.
|
||||||
Always check an edit with `Hyprland --verify-config --config <file>` — it does
|
Always check an edit with `Hyprland --verify-config --config <file>` — it does
|
||||||
not need a display, so it costs seconds instead of a rebuild.
|
not need a display, so it costs seconds instead of a rebuild.
|
||||||
- `hyprctl` **cannot connect** to this session: the compositor names its IPC
|
- `hyprctl` **works** against this session; an older note here claimed the
|
||||||
socket `.socket.so`/`.socket.s` instead of `.socket.sock`, so nothing using the
|
compositor misnames its IPC socket, which was wrong. The real defect was path
|
||||||
documented path works. Do not plan on `hyprctl` for window control — measure
|
length: `$XDG_RUNTIME_DIR` was `/run/hyprland-headless-stream` (29 chars) and
|
||||||
what you need from the frames instead.
|
the event socket `hypr/<signature>/.socket2.sock` did not fit in `sun_path`, so
|
||||||
|
the compositor logged `ERR ]: Socket2 path is too long. (2) IPC will not work.`
|
||||||
|
while the request socket kept answering — which is why the wrong diagnosis
|
||||||
|
survived. The runtime directory is now `/run/hypr-stream`, and `nix/module.nix`
|
||||||
|
asserts it stays ≤ 25 characters.
|
||||||
|
|
||||||
### Posting the result to a chat
|
### Posting the result to a chat
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -16,7 +16,7 @@
|
|||||||
# predates the group membership.
|
# predates the group membership.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
SOCKET=${AGENT_EYES_SOCKET:-/run/hyprland-headless-stream/stream.sock}
|
SOCKET=${AGENT_EYES_SOCKET:-/run/hypr-stream/stream.sock}
|
||||||
RUNDIR=$(dirname "$SOCKET")
|
RUNDIR=$(dirname "$SOCKET")
|
||||||
GROUP=${AGENT_EYES_GROUP:-hhstream}
|
GROUP=${AGENT_EYES_GROUP:-hhstream}
|
||||||
CLIENT=${AGENT_EYES_CLIENT:-hhstream-client}
|
CLIENT=${AGENT_EYES_CLIENT:-hhstream-client}
|
||||||
|
|||||||
@@ -50,8 +50,8 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "src"))
|
|||||||
|
|
||||||
from hhstream import protocol # noqa: E402 (path set above)
|
from hhstream import protocol # noqa: E402 (path set above)
|
||||||
|
|
||||||
DEFAULT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
|
DEFAULT_SOCKET = "/run/hypr-stream/stream.sock"
|
||||||
DEFAULT_RUNTIME_DIR = "/run/hyprland-headless-stream"
|
DEFAULT_RUNTIME_DIR = "/run/hypr-stream"
|
||||||
|
|
||||||
|
|
||||||
def log(message: str) -> None:
|
def log(message: str) -> None:
|
||||||
|
|||||||
+47
-2
@@ -14,8 +14,28 @@ let
|
|||||||
# socket of the session and, by default, the published frame socket too.
|
# socket of the session and, by default, the published frame socket too.
|
||||||
# `RuntimeDirectoryPreserve` keeps it (and the Wayland socket) alive across a
|
# `RuntimeDirectoryPreserve` keeps it (and the Wayland socket) alive across a
|
||||||
# restart of either unit.
|
# restart of either unit.
|
||||||
runtimeDirName = "hyprland-headless-stream";
|
#
|
||||||
|
# The name is short on purpose, and the assertion below is what keeps it that
|
||||||
|
# way. A Unix socket address carries its path inside `sun_path`, which is 108
|
||||||
|
# bytes including the terminating NUL (linux/un.h), and the compositor puts
|
||||||
|
# its IPC sockets under this directory:
|
||||||
|
#
|
||||||
|
# <runtimeDir>/hypr/<HYPRLAND_INSTANCE_SIGNATURE>/.socket.sock requests
|
||||||
|
# <runtimeDir>/hypr/<HYPRLAND_INSTANCE_SIGNATURE>/.socket2.sock events
|
||||||
|
#
|
||||||
|
# Of that budget, 20 characters are fixed and the instance signature (~30) is
|
||||||
|
# Hyprland's to choose; this directory's name is the only part we control. At
|
||||||
|
# the previous name -- `/run/hyprland-headless-stream`, 29 characters -- the
|
||||||
|
# event socket did not fit and the compositor refused to bind it:
|
||||||
|
#
|
||||||
|
# ERR ]: Socket2 path is too long. (2) IPC will not work.
|
||||||
|
#
|
||||||
|
# The *request* socket kept answering `hyprctl` anyway (both ends agreed on a
|
||||||
|
# residual truncated path), which is why the broken event socket went
|
||||||
|
# unnoticed. docs/CONTRACT-sessions.md §5 freezes the ceiling at 25.
|
||||||
|
runtimeDirName = "hypr-stream";
|
||||||
runtimeDir = "/run/${runtimeDirName}";
|
runtimeDir = "/run/${runtimeDirName}";
|
||||||
|
runtimeDirMaxLength = 25;
|
||||||
|
|
||||||
socketDir = builtins.dirOf cfg.socketPath;
|
socketDir = builtins.dirOf cfg.socketPath;
|
||||||
|
|
||||||
@@ -160,7 +180,7 @@ in {
|
|||||||
|
|
||||||
socketPath = lib.mkOption {
|
socketPath = lib.mkOption {
|
||||||
type = lib.types.str;
|
type = lib.types.str;
|
||||||
default = "/run/hyprland-headless-stream/stream.sock";
|
default = "/run/hypr-stream/stream.sock";
|
||||||
description = "Where the frame server publishes frames.";
|
description = "Where the frame server publishes frames.";
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -414,6 +434,31 @@ in {
|
|||||||
assertion = lib.hasPrefix "/" cfg.socketPath;
|
assertion = lib.hasPrefix "/" cfg.socketPath;
|
||||||
message = "services.hyprland-headless-stream.socketPath must be an absolute path.";
|
message = "services.hyprland-headless-stream.socketPath must be an absolute path.";
|
||||||
}
|
}
|
||||||
|
# Structural, not cosmetic: see the `runtimeDirName` comment above. The
|
||||||
|
# ceiling exists so the compositor's *event* socket still fits in
|
||||||
|
# `sun_path`, and the symptom of breaking it is silent -- the request
|
||||||
|
# socket keeps answering, so `hyprctl` looks fine while every event-driven
|
||||||
|
# feature is dead.
|
||||||
|
{
|
||||||
|
assertion = builtins.stringLength runtimeDir <= runtimeDirMaxLength;
|
||||||
|
message = ''
|
||||||
|
The compositor runtime directory "${runtimeDir}" is ${
|
||||||
|
toString (builtins.stringLength runtimeDir)
|
||||||
|
} characters; it must be at most ${toString runtimeDirMaxLength}.
|
||||||
|
|
||||||
|
Hyprland's event socket is <runtime dir>/hypr/<instance signature>/.socket2.sock.
|
||||||
|
A longer directory pushes that path past the 108 bytes a Unix socket address
|
||||||
|
has for `sun_path`, and the compositor then refuses to bind it:
|
||||||
|
|
||||||
|
ERR ]: Socket2 path is too long. (2) IPC will not work.
|
||||||
|
|
||||||
|
Nothing appears broken when that happens -- the shorter request socket still
|
||||||
|
answers `hyprctl` -- but the event stream never arrives, so every feature that
|
||||||
|
watches the compositor (window and workspace tracking, session containers)
|
||||||
|
stops working. docs/CONTRACT-sessions.md §5 freezes this limit; shorten the
|
||||||
|
directory rather than raising it.
|
||||||
|
'';
|
||||||
|
}
|
||||||
{
|
{
|
||||||
assertion = !cfg.sessions.enable || lib.hasAttr cfg.sessions.user config.users.users;
|
assertion = !cfg.sessions.enable || lib.hasAttr cfg.sessions.user config.users.users;
|
||||||
message = ''
|
message = ''
|
||||||
|
|||||||
+1
-1
@@ -26,4 +26,4 @@ hhstreamd = "hhstreamd.__main__:main"
|
|||||||
hhstream-pointer = "hhstream_pointer.__main__:main"
|
hhstream-pointer = "hhstream_pointer.__main__:main"
|
||||||
|
|
||||||
[tool.setuptools.packages.find]
|
[tool.setuptools.packages.find]
|
||||||
where = ["src"]
|
where = ["src"]
|
||||||
+7
-2
@@ -37,8 +37,13 @@ from typing import Iterator
|
|||||||
from . import client as frames
|
from . import client as frames
|
||||||
from . import protocol
|
from . import protocol
|
||||||
|
|
||||||
#: The frame socket the compositor's publisher serves.
|
#: The frame socket the compositor's publisher serves, under the compositor's
|
||||||
DEFAULT_FRAME_SOCKET = frames.DEFAULT_SOCKET
|
#: runtime directory `/run/hypr-stream` (short because the compositor's event
|
||||||
|
#: socket has to fit in `sun_path` -- see the assertion in `nix/module.nix`).
|
||||||
|
#: Spelled out rather than taken from `frames.DEFAULT_SOCKET`, which still names
|
||||||
|
#: the old `/run/hyprland-headless-stream` and is not this slice's file to
|
||||||
|
#: change; the module's `socketPath` default is the authority and it says this.
|
||||||
|
DEFAULT_FRAME_SOCKET = "/run/hypr-stream/stream.sock"
|
||||||
ENV_FRAME_SOCKET = "HHSTREAM_FRAME_SOCKET"
|
ENV_FRAME_SOCKET = "HHSTREAM_FRAME_SOCKET"
|
||||||
#: The group that owns the session's runtime directory.
|
#: The group that owns the session's runtime directory.
|
||||||
DEFAULT_GROUP = "hhstream"
|
DEFAULT_GROUP = "hhstream"
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from typing import Iterable
|
|||||||
|
|
||||||
from . import protocol
|
from . import protocol
|
||||||
|
|
||||||
DEFAULT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
|
DEFAULT_SOCKET = "/run/hypr-stream/stream.sock"
|
||||||
|
|
||||||
|
|
||||||
def fetch(socket_path: str, count: int = 1, timeout: float = 10.0) -> list[bytes]:
|
def fetch(socket_path: str, count: int = 1, timeout: float = 10.0) -> list[bytes]:
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ from typing import Iterable
|
|||||||
from . import protocol
|
from . import protocol
|
||||||
from .capture import CaptureBackend, CommandCapture
|
from .capture import CaptureBackend, CommandCapture
|
||||||
|
|
||||||
DEFAULT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
|
DEFAULT_SOCKET = "/run/hypr-stream/stream.sock"
|
||||||
#: Contract: the published socket is mode 0660 (ownership is the unit's job).
|
#: Contract: the published socket is mode 0660 (ownership is the unit's job).
|
||||||
SOCKET_MODE = 0o660
|
SOCKET_MODE = 0o660
|
||||||
#: Contract default for `services.hyprland-headless-stream.captureCommand`.
|
#: Contract default for `services.hyprland-headless-stream.captureCommand`.
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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()
|
||||||
@@ -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)
|
||||||
@@ -42,7 +42,7 @@ ls -l /dev/dri 2>&1 || echo "[no /dev/dri: this machine has no DRM device at all
|
|||||||
run cat /proc/fb
|
run cat /proc/fb
|
||||||
|
|
||||||
say "socket and runtime directories"
|
say "socket and runtime directories"
|
||||||
ls -la /run/hyprland-headless-stream 2>&1 || echo "[no /run/hyprland-headless-stream]"
|
ls -la /run/hypr-stream 2>&1 || echo "[no /run/hypr-stream]"
|
||||||
ls -la /run/user 2>&1 || echo "[no /run/user]"
|
ls -la /run/user 2>&1 || echo "[no /run/user]"
|
||||||
for d in /run/user/*; do
|
for d in /run/user/*; do
|
||||||
[ -d "$d" ] && ls -la "$d" 2>&1
|
[ -d "$d" ] && ls -la "$d" 2>&1
|
||||||
@@ -56,7 +56,7 @@ say "wayland socket vs WAYLAND_DISPLAY"
|
|||||||
systemctl show -p Environment --value "$SERVICE_UNIT" 2>&1 \
|
systemctl show -p Environment --value "$SERVICE_UNIT" 2>&1 \
|
||||||
| tr ' ' '\n' | grep -E '^(WAYLAND_DISPLAY|XDG_RUNTIME_DIR)=' \
|
| tr ' ' '\n' | grep -E '^(WAYLAND_DISPLAY|XDG_RUNTIME_DIR)=' \
|
||||||
|| echo "[no WAYLAND_DISPLAY/XDG_RUNTIME_DIR in the unit environment]"
|
|| echo "[no WAYLAND_DISPLAY/XDG_RUNTIME_DIR in the unit environment]"
|
||||||
for d in /run/hyprland-headless-stream /run/user/*; do
|
for d in /run/hypr-stream /run/user/*; do
|
||||||
[ -d "$d" ] || continue
|
[ -d "$d" ] || continue
|
||||||
found_sock=$(find "$d" -xdev -maxdepth 1 -name 'wayland-*' ! -name '*.lock' 2>/dev/null)
|
found_sock=$(find "$d" -xdev -maxdepth 1 -name 'wayland-*' ! -name '*.lock' 2>/dev/null)
|
||||||
if [ -n "$found_sock" ]; then
|
if [ -n "$found_sock" ]; then
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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"
|
||||||
@@ -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()
|
||||||
@@ -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")]
|
||||||
File renamed without changes.
@@ -52,7 +52,17 @@ def _repo_root() -> Path:
|
|||||||
|
|
||||||
REPO_ROOT = _repo_root()
|
REPO_ROOT = _repo_root()
|
||||||
#: The package lives under `src/` here. Keep the root too, so a flat checkout works.
|
#: The package lives under `src/` here. Keep the root too, so a flat checkout works.
|
||||||
IMPORT_PATH = os.pathsep.join([str(REPO_ROOT / "src"), str(REPO_ROOT)])
|
#:
|
||||||
|
#: These are PREPENDED to whatever PYTHONPATH we inherited rather than replacing
|
||||||
|
#: it. Clobbering it works in a checkout, where `src/` is the package, but under
|
||||||
|
#: a build (checks/unit.nix) the package under test is what the inherited path
|
||||||
|
#: points at -- so replacing it made `python -m hhstreamd` die at startup with an
|
||||||
|
#: ImportError, and every test in this file error out in its setup, which reads
|
||||||
|
#: as a daemon bug rather than a harness one.
|
||||||
|
_CHECKOUT_PATH = os.pathsep.join([str(REPO_ROOT / "src"), str(REPO_ROOT)])
|
||||||
|
IMPORT_PATH = os.pathsep.join(
|
||||||
|
p for p in (_CHECKOUT_PATH, os.environ.get("PYTHONPATH", "")) if p
|
||||||
|
)
|
||||||
|
|
||||||
# The brief's dummy app, verbatim.
|
# The brief's dummy app, verbatim.
|
||||||
SLEEP_600 = "import time; time.sleep(600)"
|
SLEEP_600 = "import time; time.sleep(600)"
|
||||||
|
|||||||
File renamed without changes.
@@ -31,7 +31,7 @@ for _path in (str(_HERE), str(_SRC)):
|
|||||||
from hhstream.server import FrameServer # noqa: E402 (needs sys.path above)
|
from hhstream.server import FrameServer # noqa: E402 (needs sys.path above)
|
||||||
|
|
||||||
#: The path named in docs/CONTRACT.md and in the module's option default.
|
#: The path named in docs/CONTRACT.md and in the module's option default.
|
||||||
CONTRACT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
|
CONTRACT_SOCKET = "/run/hypr-stream/stream.sock"
|
||||||
|
|
||||||
# AF_UNIX addresses are capped near 108 bytes; a long tmp_path would fail with a
|
# AF_UNIX addresses are capped near 108 bytes; a long tmp_path would fail with a
|
||||||
# confusing OSError instead of the assertion the test is about.
|
# confusing OSError instead of the assertion the test is about.
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ def wait_for_socket(path: str, proc: subprocess.Popen, timeout: float = 10.0) ->
|
|||||||
|
|
||||||
def test_server_defaults_match_the_contract():
|
def test_server_defaults_match_the_contract():
|
||||||
args = server.build_parser().parse_args([])
|
args = server.build_parser().parse_args([])
|
||||||
assert args.socket == "/run/hyprland-headless-stream/stream.sock"
|
assert args.socket == "/run/hypr-stream/stream.sock"
|
||||||
assert (args.fps, args.format, args.capture_command) == (30, "png", None)
|
assert (args.fps, args.format, args.capture_command) == (30, "png", None)
|
||||||
assert server.DEFAULT_CAPTURE_COMMAND == ["grim", "-t", "png", "-"]
|
assert server.DEFAULT_CAPTURE_COMMAND == ["grim", "-t", "png", "-"]
|
||||||
|
|
||||||
|
|||||||
@@ -134,7 +134,7 @@ def test_main_rejects_a_negative_count(sock_path, capsys):
|
|||||||
|
|
||||||
|
|
||||||
def test_default_socket_matches_the_contract():
|
def test_default_socket_matches_the_contract():
|
||||||
assert client.DEFAULT_SOCKET == "/run/hyprland-headless-stream/stream.sock"
|
assert client.DEFAULT_SOCKET == "/run/hypr-stream/stream.sock"
|
||||||
assert client.build_parser().parse_args([]).socket == client.DEFAULT_SOCKET
|
assert client.build_parser().parse_args([]).socket == client.DEFAULT_SOCKET
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user