|
| 1 | +"""Renders one frame through the web renderer's own page in a headless |
| 2 | +browser and saves it as a PNG, so screenshots look exactly like the live |
| 3 | +view. Needs Playwright (`pip install 'matrixbox-simulator[screenshot]'`). |
| 4 | +
|
| 5 | +Run as its own process by `matrixbox screenshot --style panel|device`, |
| 6 | +with the frame's raw RGB bytes on stdin: the screenshot process itself |
| 7 | +has file access patched into the app's sandbox, which a browser driver |
| 8 | +can't run under. |
| 9 | +""" |
| 10 | + |
| 11 | +import argparse |
| 12 | +import sys |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +from matrixbox_simulator.sizes import panel_count_for |
| 16 | +from matrixbox_simulator.term import wire |
| 17 | +from matrixbox_simulator.web.server import WebServer |
| 18 | + |
| 19 | +try: |
| 20 | + from playwright.sync_api import Error as PlaywrightError |
| 21 | + from playwright.sync_api import sync_playwright |
| 22 | +except ImportError: |
| 23 | + # Optional: only the panel and device screenshot styles need it. |
| 24 | + PlaywrightError = Exception # ty: ignore[invalid-assignment] |
| 25 | + sync_playwright = None |
| 26 | + |
| 27 | +STYLES = ("panel", "device") |
| 28 | +READY_TIMEOUT_MS = 15000 |
| 29 | + |
| 30 | +# Room around the panel or device; the page crops to it anyway, this |
| 31 | +# only has to be big enough to never cut into it. |
| 32 | +_VIEWPORT_MARGIN_LEDS = {"panel": 16, "device": 90} |
| 33 | + |
| 34 | + |
| 35 | +class WebCapture: |
| 36 | + def __init__(self, frame: wire.Frame, style: str, led_size: int) -> None: |
| 37 | + self.frame = frame |
| 38 | + self.style = style |
| 39 | + self.led_size = led_size |
| 40 | + |
| 41 | + def save(self, output: Path) -> None: |
| 42 | + server = WebServer("127.0.0.1", 0) |
| 43 | + server.start() |
| 44 | + server.publish(wire.encode_frame(self.frame)) |
| 45 | + server.publish_status(connected=True, message="screenshot") |
| 46 | + |
| 47 | + try: |
| 48 | + self._screenshot(f"http://127.0.0.1:{server.port}/", output) |
| 49 | + finally: |
| 50 | + server.stop() |
| 51 | + |
| 52 | + def viewport_size(self) -> tuple[int, int]: |
| 53 | + margin = _VIEWPORT_MARGIN_LEDS[self.style] |
| 54 | + |
| 55 | + return ( |
| 56 | + (self.frame.width + margin) * self.led_size, |
| 57 | + (self.frame.height + margin) * self.led_size, |
| 58 | + ) |
| 59 | + |
| 60 | + def _screenshot(self, base_url: str, output: Path) -> None: |
| 61 | + if sync_playwright is None: |
| 62 | + raise SystemExit( |
| 63 | + "--style panel/device needs Playwright: " |
| 64 | + "pip install 'matrixbox-simulator[screenshot]'" |
| 65 | + ) |
| 66 | + |
| 67 | + with sync_playwright() as playwright: |
| 68 | + try: |
| 69 | + # The installed Chrome first, so nothing extra has to be |
| 70 | + # downloaded, then Playwright's own Chromium. |
| 71 | + browser = playwright.chromium.launch(channel="chrome") |
| 72 | + except PlaywrightError: |
| 73 | + try: |
| 74 | + browser = playwright.chromium.launch() |
| 75 | + except PlaywrightError as err: |
| 76 | + raise SystemExit( |
| 77 | + "no browser for --style panel/device: install Chrome, " |
| 78 | + "or run `playwright install chromium`" |
| 79 | + ) from err |
| 80 | + |
| 81 | + try: |
| 82 | + width, height = self.viewport_size() |
| 83 | + page = browser.new_page( |
| 84 | + viewport={"width": width, "height": height}, color_scheme="dark" |
| 85 | + ) |
| 86 | + page.goto(f"{base_url}?view={self.style}&capture=1&led={self.led_size}") |
| 87 | + page.wait_for_selector("body[data-ready]", timeout=READY_TIMEOUT_MS) |
| 88 | + clip = page.evaluate("window.matrixboxCaptureBounds()") |
| 89 | + output.parent.mkdir(parents=True, exist_ok=True) |
| 90 | + page.screenshot( |
| 91 | + path=str(output), |
| 92 | + clip=clip, |
| 93 | + omit_background=self.style == "panel", |
| 94 | + ) |
| 95 | + finally: |
| 96 | + browser.close() |
| 97 | + |
| 98 | + |
| 99 | +def build_parser() -> argparse.ArgumentParser: |
| 100 | + parser = argparse.ArgumentParser(description=__doc__) |
| 101 | + parser.add_argument("--style", choices=STYLES, required=True) |
| 102 | + parser.add_argument("--width", type=int, required=True) |
| 103 | + parser.add_argument("--height", type=int, required=True) |
| 104 | + parser.add_argument("--led-size", type=int, default=8) |
| 105 | + parser.add_argument("-o", "--output", required=True) |
| 106 | + |
| 107 | + return parser |
| 108 | + |
| 109 | + |
| 110 | +def main() -> None: |
| 111 | + args = build_parser().parse_args() |
| 112 | + rgb = sys.stdin.buffer.read() |
| 113 | + if len(rgb) != args.width * args.height * 3: |
| 114 | + raise SystemExit( |
| 115 | + f"expected {args.width * args.height * 3} bytes of RGB, got {len(rgb)}" |
| 116 | + ) |
| 117 | + |
| 118 | + frame = wire.Frame( |
| 119 | + width=args.width, |
| 120 | + height=args.height, |
| 121 | + pixels=rgb, |
| 122 | + tiles=panel_count_for(args.width, args.height), |
| 123 | + ) |
| 124 | + WebCapture(frame, args.style, args.led_size).save(Path(args.output)) |
| 125 | + |
| 126 | + |
| 127 | +if __name__ == "__main__": |
| 128 | + main() |
0 commit comments