#!/usr/bin/env python3 """A fake capture backend: writes one deterministic PNG to stdout and exits. Stands in for `grim` so `vm-basic` can exercise the socket, the Hello and the framing without a compositor. Two properties matter to the test: * the bytes are a *valid* PNG of exactly the requested size, so a server that derives the Hello's width/height from the captured image agrees with a server that derives them from the configured output; * the bytes are *byte-identical* on every invocation, so the test can assert that two frames off the wire are the same image rather than the same length. Pure standard library (zlib + struct), because the test VM has nothing else. """ from __future__ import annotations import argparse import struct import sys import zlib def chunk(kind: bytes, data: bytes) -> bytes: return ( struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) ) def encode_png(width: int, height: int) -> bytes: """A solid frame with one deterministic marker rectangle in the corner. The marker keeps the image from being uniform, which is what makes it a believable stand-in for a real capture; being fixed keeps it reproducible. """ bg = (0x20, 0x30, 0x40) fg = (0xE0, 0xC0, 0x10) mark_w = min(64, width) mark_h = min(32, height) plain = b"\x00" + bytes(bg) * width marked = b"\x00" + bytes(fg) * mark_w + bytes(bg) * (width - mark_w) raw = marked * mark_h + plain * (height - mark_h) ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) # 8-bit truecolour return ( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"") ) def build_parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--width", type=int, default=1280) p.add_argument("--height", type=int, default=720) # Accepted and ignored so the fake can be dropped in where a grim-shaped # argv is expected (`-t png -`). p.add_argument("-t", "--type", default="png") p.add_argument("output", nargs="?", default="-") return p def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) if args.type != "png": print(f"fake-capture: only png is supported, got {args.type!r}", file=sys.stderr) return 2 if args.width <= 0 or args.height <= 0: print("fake-capture: width and height must be positive", file=sys.stderr) return 2 data = encode_png(args.width, args.height) out = sys.stdout.buffer if args.output == "-" else open(args.output, "wb") try: out.write(data) out.flush() finally: if out is not sys.stdout.buffer: out.close() return 0 if __name__ == "__main__": sys.exit(main())