Files
hyprland-headless-stream-pl…/tests/unit/fake_capture.py
HermenixandClaude Opus 5 4af6f7072a server, client: implement the v1 frame protocol end to end
Fill in the bodies the skeleton left as NotImplementedError, to docs/CONTRACT.md:

- protocol: the `\n`-terminated JSON Hello and the `<ascii length>\n<payload>`
  frame, both directions. Malformed input raises (ValueError for a bad length
  prefix, EOFError for a truncated payload), never hangs on endless garbage and
  never silently truncates; a huge length prefix is not pre-allocated.
- capture: CommandCapture runs the configured command and reports a missing
  binary, a non-zero exit, a timeout and empty output as CaptureError, with the
  helper's stderr folded into the message so nothing leaks to the server's own
  stdio. The Hello's pixel size is read from the frame's PNG/JPEG header, so no
  compositor query is needed and an injected fake command behaves the same.
- server: one capture thread holding only the newest frame plus one thread per
  client, which is what drops frames for a slow client instead of queueing
  them. Survives a client dying mid-write, keeps the socket up across capture
  failures, withholds the Hello until a size is known, replaces a stale socket
  file (but never a non-socket one) and publishes it mode 0660.
- client: fetch()/read_stream() and the CLI, with --out suffixing per frame.

--capture-command folds its separated form into `--flag=value` before argparse
sees it, so the contract's default `grim -t png -` can actually be passed: its
tokens start with a dash.

Unit tests under tests/unit cover framing round-trips (including a payload
containing `\n` and a zero-length frame), truncated and garbage prefixes, a
stalled client not blocking a second one, a client dying mid-frame, frames being
dropped rather than queued, and every capture failure mode. A fake capture
command stands in for grim, so nothing needs a compositor or a GPU. They are
deliberately not wired into flake.nix: `checks` belongs to another workstream.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FYJ8ZQ5AZaDErYTwXZe7N9
2026-09-28 05:35:17 +00:00

103 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""A stand-in for `grim`: writes one fake PNG frame to stdout.
Injected through `captureCommand` (see docs/CONTRACT.md) so no unit test needs a
compositor or a GPU. One script plays every part the server has to cope with: a
healthy backend, a broken one, a silent one, a slow one, and one that only
starts working later.
"""
from __future__ import annotations
import argparse
import os
import struct
import sys
import time
import zlib
def png_bytes(width: int = 16, height: int = 8, color: tuple[int, int, int] = (0, 0, 0),
level: int = 6) -> bytes:
"""A real, decodable RGB PNG of a solid colour.
`level` 0 stores the pixels uncompressed, which is how the tests get a frame
big enough to fill a socket buffer.
"""
def chunk(tag: bytes, data: bytes) -> bytes:
return (struct.pack(">I", len(data)) + tag + data
+ struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
row = bytes(color) * width
raw = b"".join(b"\x00" + row for _ in range(height))
return (b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", ihdr)
+ chunk(b"IDAT", zlib.compress(raw, level))
+ chunk(b"IEND", b""))
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--width", type=int, default=16)
parser.add_argument("--height", type=int, default=8)
parser.add_argument("--counter", metavar="PATH",
help="file holding a call count; each frame's colour "
"differs so frames are distinguishable")
parser.add_argument("--gate", metavar="PATH",
help="fail until this path exists (a compositor that "
"is not up yet)")
parser.add_argument("--fail", action="store_true", help="exit non-zero")
parser.add_argument("--empty", action="store_true",
help="exit 0 having written nothing")
parser.add_argument("--garbage", action="store_true",
help="write output that is not an image")
parser.add_argument("--delay", type=float, default=0.0,
help="sleep this long before answering")
parser.add_argument("--big", action="store_true",
help="store the pixels uncompressed (a large frame)")
parser.add_argument("--message", default="fake_capture: simulated failure")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
if args.delay:
time.sleep(args.delay)
if args.gate and not os.path.exists(args.gate):
sys.stderr.write(f"fake_capture: gate {args.gate} is missing\n")
return 4
if args.fail:
sys.stderr.write(args.message + "\n")
return 3
if args.empty:
sys.stderr.write("fake_capture: nothing to capture\n")
return 0
count = 0
if args.counter:
try:
with open(args.counter) as handle:
count = int(handle.read() or 0)
except FileNotFoundError:
count = 0
count += 1
with open(args.counter, "w") as handle:
handle.write(str(count))
if args.garbage:
sys.stdout.buffer.write(b"fake_capture: not an image, sorry\n")
sys.stdout.buffer.flush()
return 0
colour = (count % 251, (count * 7) % 251, (count * 13) % 251)
sys.stdout.buffer.write(
png_bytes(args.width, args.height, colour, 0 if args.big else 6)
)
sys.stdout.buffer.flush()
return 0
if __name__ == "__main__":
raise SystemExit(main())