Skip to content

Commit 5e09ab2

Browse files
authored
feat: add panel and device styles to screenshot (#26)
- `--style panel` draws glowing LEDs in a housing on a transparent background, `--style device` the 3D mockup cropped to the device - Both render through the web page in headless Chrome so they match the live view, Playwright is an optional `screenshot` extra - `pixels` stays the default
1 parent 146b04e commit 5e09ab2

8 files changed

Lines changed: 471 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,23 @@ non-zero with the error printed. `--scale <n>` sets the output PNG's
224224
pixel scale factor (default 8). `--size` / `--width` / `--height` pick
225225
the panel size, same as `matrixbox app`.
226226

227+
`--style` picks how the frame is drawn:
228+
229+
- `pixels` (default): the raw frame, each pixel an NxN block.
230+
- `panel`: glowing round LEDs in a dark housing, on a transparent
231+
background, exactly like the browser renderer's panel view.
232+
- `device`: the browser renderer's device mockup, cropped to the device.
233+
234+
```sh
235+
matrixbox screenshot /path/to/matrixbox/apps/clock --style device -o clock.png
236+
```
237+
238+
`panel` and `device` render through the real web page in a headless
239+
browser, so they need [Playwright][playwright]
240+
(`pip install 'matrixbox-simulator[screenshot]'`). An installed Chrome is
241+
used if there is one, otherwise run `playwright install chromium` once.
242+
For these, `--scale` is the size of one LED in pixels.
243+
227244
## Sandbox
228245

229246
Every `matrixbox app`/`screenshot` run stages a fresh copy of the
@@ -274,3 +291,4 @@ https://github.com/user-attachments/assets/d0655003-ce85-4c79-b668-5602e9f14155
274291
[matrixbox-source]: https://github.com/MatrixBOX-dev/matrixbox
275292
[circuitpython]: https://circuitpython.org/
276293
[uv]: https://docs.astral.sh/uv/
294+
[playwright]: https://playwright.dev/python/

‎matrixbox_simulator/device/run_screenshot.py‎

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import io
1515
import json
1616
import os
17+
import subprocess
1718
import sys
1819
import threading
1920
import time
@@ -26,6 +27,8 @@
2627
from matrixbox_simulator.device import frame_bridge, run_app
2728
from matrixbox_simulator.sizes import ROTATION_OVERRIDES, SIZE_PRESETS
2829

30+
SCREENSHOT_STYLES = ("pixels", "panel", "device")
31+
2932

3033
def build_parser(
3134
parser: argparse.ArgumentParser | None = None,
@@ -84,7 +87,16 @@ def build_parser(
8487
type=int,
8588
default=8,
8689
help="pixel scale factor for the output PNG: each device pixel is "
87-
"drawn as an NxN block (default 8)",
90+
"drawn as an NxN block, or an N pixel LED for --style panel/device "
91+
"(default 8)",
92+
)
93+
parser.add_argument(
94+
"--style",
95+
choices=SCREENSHOT_STYLES,
96+
default="pixels",
97+
help="pixels: the raw frame, scaled up (default). panel: glowing "
98+
"LEDs in a dark housing, like the web renderer. device: the web "
99+
"renderer's 3D device mockup. panel and device need Playwright",
88100
)
89101
parser.add_argument(
90102
"-o",
@@ -224,6 +236,38 @@ def _write_screenshot(
224236
path.write_bytes(buffer.getvalue())
225237

226238

239+
def _write_web_screenshot(
240+
path: Path, width: int, height: int, rgb: bytes, *, style: str, scale: int
241+
) -> None:
242+
# A separate, unsandboxed process: this one has open()/stat() and
243+
# friends redirected into the app's sandbox, which a browser driver
244+
# can't run under. -P keeps the staged checkout's own modules (it has
245+
# a code.py, for one) from shadowing the standard library there.
246+
result = subprocess.run(
247+
[
248+
sys.executable,
249+
"-P",
250+
"-m",
251+
"matrixbox_simulator.web.capture",
252+
"--style",
253+
style,
254+
"--width",
255+
str(width),
256+
"--height",
257+
str(height),
258+
"--led-size",
259+
str(scale),
260+
"--output",
261+
str(path),
262+
],
263+
input=rgb,
264+
cwd=path.parent,
265+
check=False,
266+
)
267+
if result.returncode != 0:
268+
raise SystemExit(f"couldn't render the {style} screenshot")
269+
270+
227271
def run(args: argparse.Namespace) -> None:
228272
args.geometry_explicit = (
229273
args.size is not None or args.width is not None or args.height is not None
@@ -355,10 +399,17 @@ def run_app_code() -> None:
355399
f"{app_dir.name} never drew a frame within {args.timeout:.1f}s"
356400
)
357401

358-
_write_screenshot(output, width, height, rgb, scale=args.scale)
402+
if args.style == "pixels":
403+
_write_screenshot(output, width, height, rgb, scale=args.scale)
404+
else:
405+
_write_web_screenshot(
406+
output, width, height, rgb, style=args.style, scale=args.scale
407+
)
408+
359409
print(
360410
f"matrixbox-simulator: wrote {output} ({width}x{height}, "
361-
f"{count} frame{'s' if count != 1 else ''} drawn, {args.scale}x scale)"
411+
f"{count} frame{'s' if count != 1 else ''} drawn, {args.style} style, "
412+
f"{args.scale}x scale)"
362413
)
363414

364415

‎matrixbox_simulator/web/capture.py‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
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()

‎matrixbox_simulator/web/static/app.js‎

Lines changed: 65 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,10 @@ class CableRope {
435435
this.restingFrames = 0;
436436
}
437437

438+
settled() {
439+
return this.points.length > 0 && !this.running;
440+
}
441+
438442
start() {
439443
this.points = [];
440444
this.endY = 0;
@@ -701,15 +705,68 @@ class SimulatorPage {
701705
this.viewButtons = document.querySelectorAll("[data-view]");
702706
this.drawPending = false;
703707
this.lastFrameSize = "";
704-
this.view =
705-
new URLSearchParams(window.location.search).get("view") ?? this.preferences.read("view", "panel");
708+
const params = new URLSearchParams(window.location.search);
709+
this.view = params.get("view") ?? this.preferences.read("view", "panel");
710+
// Screenshot mode: just the panel or device at a fixed LED size, no
711+
// page chrome, flagging when it's safe to capture.
712+
this.capture = params.get("capture") === "1" ? { ledCssSize: Number(params.get("led")) || 8 } : null;
706713

707714
this.renderer.showSeams = this.preferences.read("seams", "off") === "on";
708715
this.seamsToggle.checked = this.renderer.showSeams;
709716
this.renderAppControls();
710717
this.bindControls();
711718
this.setView(this.view);
712719
this.connect();
720+
if (this.capture) {
721+
this.prepareCapture();
722+
}
723+
}
724+
725+
prepareCapture() {
726+
document.body.classList.add("capture", `capture-${this.view}`);
727+
window.matrixboxCaptureBounds = () => this.captureBounds();
728+
729+
const markReadyOnceSettled = () => {
730+
const drawn = this.renderer.frame && this.renderer.ledSize;
731+
if (drawn && (this.view !== "device" || this.cable.settled())) {
732+
document.body.dataset.ready = "true";
733+
return;
734+
}
735+
736+
window.requestAnimationFrame(markReadyOnceSettled);
737+
};
738+
window.requestAnimationFrame(markReadyOnceSettled);
739+
}
740+
741+
// The region worth keeping: the panel itself, or the device with a
742+
// little room around it, leaving the cable to run off the edge.
743+
captureBounds() {
744+
const elements =
745+
this.view === "device"
746+
? document.querySelectorAll("#box .face, #plug .plug-side, #device-button .cylinder-top")
747+
: [this.renderer.canvas];
748+
const margin = this.view === "device" ? this.capture.ledCssSize * 5 : 0;
749+
let left = Infinity;
750+
let top = Infinity;
751+
let right = -Infinity;
752+
let bottom = -Infinity;
753+
for (const element of elements) {
754+
const rect = element.getBoundingClientRect();
755+
left = Math.min(left, rect.left);
756+
top = Math.min(top, rect.top);
757+
right = Math.max(right, rect.right);
758+
bottom = Math.max(bottom, rect.bottom);
759+
}
760+
761+
const x = Math.max(0, Math.floor(left - margin));
762+
const y = Math.max(0, Math.floor(top - margin));
763+
764+
return {
765+
x,
766+
y,
767+
width: Math.min(window.innerWidth, Math.ceil(right + margin)) - x,
768+
height: Math.min(window.innerHeight, Math.ceil(bottom + margin)) - y,
769+
};
713770
}
714771

715772
renderAppControls() {
@@ -784,7 +841,8 @@ class SimulatorPage {
784841
const enclosureLeds = DEVICE_BEZEL_LEDS * 2 + DEVICE_DEPTH_LEDS;
785842
const ledsWide = frame.width + enclosureLeds;
786843
const ledsHigh = frame.height + enclosureLeds;
787-
const ledCssSize = Math.min((bounds.width * 0.86) / ledsWide, (bounds.height * 0.8) / ledsHigh);
844+
const ledCssSize =
845+
this.capture?.ledCssSize ?? Math.min((bounds.width * 0.86) / ledsWide, (bounds.height * 0.8) / ledsHigh);
788846
// A hair over, so rounding down to whole device pixels lands on it.
789847
this.renderer.layout(frame.width * ledCssSize + 0.01, frame.height * ledCssSize + 0.01);
790848
const canvas = this.renderer.canvas;
@@ -794,6 +852,10 @@ class SimulatorPage {
794852
this.renderer.cssLedSize(),
795853
);
796854
this.cable.start();
855+
} else if (this.capture) {
856+
const housing = PANEL_HOUSING_LEDS * 2;
857+
const led = this.capture.ledCssSize;
858+
this.renderer.layout((frame.width + housing) * led + 0.01, (frame.height + housing) * led + 0.01);
797859
} else {
798860
this.renderer.layout(bounds.width - 32, bounds.height - 32);
799861
}

‎matrixbox_simulator/web/static/style.css‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,23 @@ body {
4545
font-size: 14px;
4646
}
4747

48+
body.capture {
49+
grid-template-rows: 1fr;
50+
}
51+
52+
body.capture-panel {
53+
background: transparent;
54+
}
55+
56+
.capture .toolbar,
57+
.capture .footer {
58+
display: none;
59+
}
60+
61+
.capture .panel-view .leds {
62+
filter: none;
63+
}
64+
4865
[hidden] {
4966
display: none !important;
5067
}

0 commit comments

Comments
 (0)