summaryrefslogtreecommitdiff
path: root/test/kitty_harness.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-28 21:03:48 -0300
committerGabriel Schneider <[email protected]>2026-10-28 21:23:53 -0300
commitb250eb6135475699a945324c005890e8e1b4dd0b (patch)
treec32f06f89cdbd501ba5d75dc8ba80ecebbe3c278 /test/kitty_harness.zig
parenta48a825b06cc45947adaecf42073ed86af8b7a2d (diff)
downloadpardes-b250eb6135475699a945324c005890e8e1b4dd0b.tar.gz
pardes-b250eb6135475699a945324c005890e8e1b4dd0b.zip
kitty graphics conformance for terminal panes: a core suite (test/kitty.zig, `zig build kitty-test`, in unit-test) and an end-to-end harness (`zig build kitty-harness`, tty and gui); four gaps it found fixed, one left
The core suite feeds a pane's output as pty reads do and checks what the program reads back, ghostty's image storage and the ImagePlaces a frame draws: queries and their errors, q=0/1/2, f=24/32/100 and o=z, chunked m=1 split at every read size, t=f/t=t/t=s, a=T and C=1 cursor movement, a=p by placement id with source rects and re-puts, image numbers, every d= delete (a/A i/I n/N c/C p/P q/Q x/X y/Y z/Z r/R) and a delete abandoning a chunked load, Unicode placeholders over two rows with implicit columns and a placement named in the underline colour, scroll/resize/reflow, the alternate screen, clear (ED 2 + ED 3), replies per pane and never in the cells, many replies from one read, kitty before DA, CAN/SUB, an oversized image, 300 images against the storage limit, animations and relative placements. The harness runs test/kitty_client.zig in a pane's bash (query, a 16-chunk 8x4-cell place, the three media, quiet levels, CAN, show then delete) and kitten icat (stream and detect) and chafa when installed. Outside, the tty arm is a kitty terminal (a ghostty-vt emulator): the image pardes re-emits lands at the cell after ANCHOR>, 8x4 cells a row at a time, the client's own commands and replies never pass through, and d=I frees what was sent. The gui arm reads the GPU capture. Fixed: kitty file, temporary-file and shared-memory media (libghostty defaults to direct only; now allWithTempDir like ghostty and kitty); replies past 256 bytes of one read were cut mid-sequence (4 KiB now, an answer that does not fit dropped whole and counted); animations never played (TerminalImages draws renderData(), ticks ImageStorage.animationTick on the core clock, nextWake wakes for the next frame); relative placements (P=/Q=/H=/V=) were not drawn (resolveChain, as ghostty's renderer). image.decode no longer jumps through stb_image's null allocator before image.start. Known gap (a knownGap test): no z-index; every image is drawn over the cells in storage order. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'test/kitty_harness.zig')
-rw-r--r--test/kitty_harness.zig463
1 files changed, 463 insertions, 0 deletions
diff --git a/test/kitty_harness.zig b/test/kitty_harness.zig
new file mode 100644
index 00000000..ad864671
--- /dev/null
+++ b/test/kitty_harness.zig
@@ -0,0 +1,463 @@
+//! Kitty graphics end to end through a terminal pane.
+//!
+//! zig build kitty-harness -Dplatform=tty a fake kitty terminal outside
+//! zig build kitty-harness -Dplatform=gui the SDL renderer's capture
+//!
+//! test/kitty.zig checks the proxy at the core; this checks it through the
+//! real things on both sides of it. Inside: a bash in a pardes terminal pane
+//! runs test/kitty_client.zig (each case as yazi or `kitten icat` would play
+//! it, recording what its pty reads back), then `kitten icat` and `chafa`
+//! themselves when they are installed. Outside, on the tty, the harness is a
+//! kitty terminal: a ghostty-vt emulator that stores the images pardes
+//! re-emits, so a check reads where they landed in cells; on the GUI, the
+//! GPU readback (PARDES_TEST_CAPTURE_DIR) is where the pixels landed.
+const std = @import("std");
+const libc = std.c;
+const eh = @import("e2e_harness.zig");
+const client = @import("kitty_client.zig");
+
+extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
+extern "c" fn unsetenv(name: [*:0]const u8) c_int;
+extern "c" fn chdir(path: [*:0]const u8) c_int;
+
+pub const std_options: std.Options = .{ .log_level = .err };
+
+const gpa = std.heap.page_allocator;
+const rows = 40;
+const cols = 120;
+const sync_reply = "\x1b_Gi=999;OK\x1b\\";
+
+var failures: usize = 0;
+var skipped: usize = 0;
+
+fn check(ok: bool, comptime what: []const u8, args: anytype) void {
+ if (ok) {
+ std.debug.print(" ok " ++ what ++ "\n", args);
+ } else {
+ failures += 1;
+ std.debug.print(" FAIL " ++ what ++ "\n", args);
+ }
+}
+
+fn skip(comptime what: []const u8, args: anytype) void {
+ skipped += 1;
+ std.debug.print(" skip " ++ what ++ "\n", args);
+}
+
+pub fn main(init: std.process.Init) !void {
+ var arena_state: std.heap.ArenaAllocator = .init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const args = try init.minimal.args.toSlice(arena);
+ if (args.len != 4) return error.BadArgs;
+ // Run steps pass artifacts relative to the build root; the harness
+ // works from its own directory.
+ const exe = try absolute(arena, args[1]);
+ const kc = try absolute(arena, args[2]);
+ const gui = std.mem.eql(u8, args[3], "gui");
+
+ const base = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-harness-{d}", .{libc.getpid()}, 0);
+ if (libc.mkdir(base, 0o755) != 0) return error.MkdirFailed;
+ defer removeTree(arena, base);
+ try hermetic(arena, base, gui);
+
+ var h = try eh.Harness.initArgv(gpa, exe, rows, cols, &.{});
+ defer h.deinit();
+ var run: Run = .{ .arena = arena, .h = &h, .base = base, .kc = kc, .gui = gui };
+ try run.start();
+
+ std.debug.print("kitty harness ({s}):\n", .{if (gui) "gui" else "tty"});
+ try run.query();
+ try run.place();
+ try run.media();
+ try run.quiet();
+ try run.cancel();
+ if (!gui) try run.delete();
+ try run.icat();
+ try run.chafa();
+
+ std.debug.print("kitty harness: {d} failed, {d} skipped\n", .{ failures, skipped });
+ if (failures > 0) return error.KittyHarnessFailed;
+}
+
+fn hermetic(arena: std.mem.Allocator, base: [:0]const u8, gui: bool) !void {
+ for ([_][*:0]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE", "PARDES_MOUNT", "PARDES_TEST", "PARDES_TEST_CAPTURE_DIR", "PARDES_TEST_COLS", "PARDES_TEST_ROWS", "PARDES_DUMP" }) |name|
+ _ = unsetenv(name);
+ _ = setenv("HOME", base, 1);
+ const config_home = try std.fmt.allocPrintSentinel(arena, "{s}/.config", .{base}, 0);
+ _ = setenv("XDG_CONFIG_HOME", config_home, 1);
+ const state_home = try std.fmt.allocPrintSentinel(arena, "{s}/.state", .{base}, 0);
+ _ = setenv("XDG_STATE_HOME", state_home, 1);
+ if (libc.mkdir(config_home, 0o755) != 0) return error.MkdirFailed;
+ const config_dir = try std.fmt.allocPrintSentinel(arena, "{s}/pardes", .{config_home}, 0);
+ if (libc.mkdir(config_dir, 0o755) != 0) return error.MkdirFailed;
+ try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/init", .{config_dir}, 0), "Shell bash\nTheme helix\nMessageAnimation off\nMessageLinger 0\n");
+ try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/.bashrc", .{base}, 0), "PS1='$ '\nHISTFILE=\n");
+ _ = setenv("HISTFILE", "/dev/null", 1);
+ _ = setenv("TERM", "xterm-256color", 1);
+ _ = setenv("LC_ALL", "C", 1);
+ _ = setenv("PARDES_NOTIME", "1", 1);
+ if (gui) {
+ _ = setenv("PARDES_TEST", "1", 1);
+ _ = setenv("PARDES_TEST_CAPTURE_DIR", base, 1);
+ _ = setenv("PARDES_TEST_COLS", "120", 1);
+ _ = setenv("PARDES_TEST_ROWS", "40", 1);
+ }
+ if (chdir(base) != 0) return error.ChdirFailed;
+ try writePng(arena, try std.fmt.allocPrintSentinel(arena, "{s}/solid.png", .{base}, 0));
+}
+
+const Run = struct {
+ arena: std.mem.Allocator,
+ h: *eh.Harness,
+ base: [:0]const u8,
+ kc: []const u8,
+ gui: bool,
+
+ fn capturePath(r: *Run) ![:0]const u8 {
+ return std.fmt.allocPrintSentinel(r.arena, "{s}/latest.ppm", .{r.base}, 0);
+ }
+
+ fn start(r: *Run) !void {
+ if (r.gui) {
+ // Up once the first frame is captured.
+ const path = try r.capturePath();
+ const deadline = eh.nowMs() + 10_000;
+ while (eh.nowMs() < deadline and libc.access(path, libc.F_OK) != 0) _ = try r.h.pumpOnce(50);
+ if (libc.access(path, libc.F_OK) != 0) return error.GuiNeverDrew;
+ try r.h.pump(1500);
+ } else {
+ // A kitty terminal: graphics, then DA to close the probe.
+ try r.h.expectRawWaitFor("\x1b_Gi=1,a=q\x1b\\", 8000, "pardes did not probe for kitty graphics");
+ try r.h.send("\x1b_Gi=1;OK\x1b\\\x1b[?1;2c");
+ try r.h.expectWaitFor("$ ", 10_000, "the shell's prompt did not show");
+ }
+ // A fresh shell pane has the keyboard, at its pty (tty mode).
+ try r.h.pump(400);
+ }
+
+ /// Type `line` into the pane's bash and wait for `<case>.out.done`.
+ fn shell(r: *Run, name: []const u8, line: []const u8) ![]const u8 {
+ const out = try std.fmt.allocPrintSentinel(r.arena, "{s}/{s}.out", .{ r.base, name }, 0);
+ const done = try std.fmt.allocPrintSentinel(r.arena, "{s}.done", .{out}, 0);
+ try r.h.send(line);
+ try r.h.send("\r");
+ const deadline = eh.nowMs() + 15_000;
+ while (eh.nowMs() < deadline and libc.access(done, libc.F_OK) != 0) _ = try r.h.pumpOnce(50);
+ if (libc.access(done, libc.F_OK) != 0) {
+ r.h.dump(name);
+ return error.CaseTimedOut;
+ }
+ // Its frame drawn and shown.
+ try r.h.pump(600);
+ return readFile(r.arena, out) catch "";
+ }
+
+ fn case(r: *Run, name: []const u8) ![]const u8 {
+ return r.shell(name, try std.fmt.allocPrint(r.arena, "clear; {s} {s} {s}/{s}.out", .{ r.kc, name, r.base, name }));
+ }
+
+ fn query(r: *Run) !void {
+ const got = try r.case("query");
+ const kitty = std.mem.indexOf(u8, got, "\x1b_Gi=31;OK\x1b\\");
+ const da = std.mem.indexOf(u8, got, "\x1b[?");
+ check(kitty != null and da != null and kitty.? < da.?, "query: OK on the client's pty, ahead of DA ({f})", .{std.ascii.hexEscape(got, .lower)});
+ check(std.mem.indexOf(u8, r.h.raw.items, "\x1b_Gi=31;OK") == null, "query: the answer never reaches the outer terminal", .{});
+ }
+
+ fn place(r: *Run) !void {
+ const raw_from = r.h.raw.items.len;
+ const got = try r.case("place");
+ check(std.mem.eql(u8, got, "\x1b_Gi=42;OK\x1b\\" ++ sync_reply), "place: one OK for 16 chunks, then sync ({f})", .{std.ascii.hexEscape(got, .lower)});
+ const raw = r.h.raw.items[raw_from..];
+ // Its RGB payload (13,77,231 is "DU3n" in base64) would show whole
+ // were it passed through; pardes sends RGBA it decoded.
+ check(std.mem.indexOf(u8, raw, "\x1b_Ga=T,i=42") == null and std.mem.indexOf(u8, raw, "DU3nDU3nDU3n") == null, "place: the client's own commands are not passed through", .{});
+ if (r.gui) return r.placedOnCapture();
+ // Outside, pardes's own transmission of the 64x64 and its per-row
+ // placements, from the cell after `ANCHOR>`.
+ const anchor = try r.find("ANCHOR>") orelse {
+ check(false, "place: ANCHOR> on the outer screen", .{});
+ return;
+ };
+ const cells = try r.outerPlacements(client.side, client.side);
+ check(cells.count > 0, "place: pardes placed a 64x64 image in the outer terminal ({d} placements)", .{cells.count});
+ if (cells.count == 0) return;
+ check(cells.min_x == anchor.x + 7 and cells.min_y == anchor.y, "place: at the cell after ANCHOR> (outer {d},{d}; anchor {d},{d})", .{ cells.min_x, cells.min_y, anchor.x, anchor.y });
+ check(cells.rows == 4 and cells.width == 8, "place: 8x4 cells, one placement a row ({d} rows, {d} wide)", .{ cells.rows, cells.width });
+ }
+
+ fn placedOnCapture(r: *Run) !void {
+ const path = try r.capturePath();
+ const deadline = eh.nowMs() + 5000;
+ var bounds: ?ColorBounds = null;
+ var ppm_w: usize = 0;
+ var ppm_h: usize = 0;
+ while (eh.nowMs() < deadline) {
+ if (captureColour(path, 0)) |seen| {
+ ppm_w = seen.width;
+ ppm_h = seen.height;
+ bounds = seen.bounds;
+ if (bounds) |b| if (b.count > 200) break;
+ }
+ _ = try r.h.pumpOnce(50);
+ }
+ const b = bounds orelse {
+ check(false, "place: the image's colour in the GUI capture", .{});
+ return;
+ };
+ // 8x4 cells of the capture's own cell size.
+ const cw = ppm_w / cols;
+ const ch = ppm_h / rows;
+ const w = b.max_x - b.min_x + 1;
+ const ht = b.max_y - b.min_y + 1;
+ check(w + 2 >= 8 * cw and w <= 8 * cw + 2 and ht + 2 >= 4 * ch and ht <= 4 * ch + 2, "place: 8x4 cells in the GUI ({d}x{d} px, cell {d}x{d})", .{ w, ht, cw, ch });
+ check(b.count * 10 >= w * ht * 9, "place: solid where drawn ({d} of {d} px)", .{ b.count, w * ht });
+ }
+
+ fn media(r: *Run) !void {
+ const got = try r.case("media");
+ for ([_][]const u8{ "\x1b_Gi=51;OK", "\x1b_Gi=52;OK", "\x1b_Gi=53;OK" }, [_][]const u8{ "t=f", "t=t", "t=s" }) |want, medium| {
+ check(std.mem.indexOf(u8, got, want) != null, "media: {s} loads ({f})", .{ medium, std.ascii.hexEscape(got, .lower) });
+ }
+ }
+
+ fn quiet(r: *Run) !void {
+ const got = try r.case("quiet");
+ check(std.mem.indexOf(u8, got, "i=61") == null and std.mem.indexOf(u8, got, "i=62") == null and
+ std.mem.startsWith(u8, got, "\x1b_Gi=63;E"), "quiet: q=1's OK and q=2's error unsaid, q=0's error heard ({f})", .{std.ascii.hexEscape(got, .lower)});
+ }
+
+ fn cancel(r: *Run) !void {
+ const got = try r.case("cancel");
+ check(std.mem.eql(u8, got, sync_reply), "cancel: a CAN'd command answers nothing ({f})", .{std.ascii.hexEscape(got, .lower)});
+ if (!r.gui) check(try r.find("CANCELLED-OK") != null, "cancel: the text after it prints", .{});
+ }
+
+ fn delete(r: *Run) !void {
+ // Shown first (pardes transmits it outside), then deleted by a
+ // second run of the client in the same pane.
+ const raw_from = r.h.raw.items.len;
+ _ = try r.case("show");
+ const shown = r.h.raw.items[raw_from..];
+ const transmit = "\x1b_Gf=32,s=64,v=64,i=";
+ const i = std.mem.indexOf(u8, shown, transmit) orelse {
+ check(false, "delete: the image to delete was drawn outside", .{});
+ return;
+ };
+ const id_at = i + transmit.len;
+ const id_end = std.mem.indexOfAnyPos(u8, shown, id_at, ",;") orelse return error.BadTransmit;
+ const free = try std.fmt.allocPrint(r.arena, "\x1b_Ga=d,d=I,i={s}", .{shown[id_at..id_end]});
+ const before = r.h.raw.items.len;
+ _ = try r.shell("delete", try std.fmt.allocPrint(r.arena, "{s} delete {s}/delete.out", .{ r.kc, r.base }));
+ try r.h.pump(400);
+ check(std.mem.indexOf(u8, r.h.raw.items[before..], free) != null, "delete: d=I in the pane frees what pardes sent outside ({s})", .{free[3..]});
+ const cells = try r.outerPlacements(client.side, client.side);
+ check(cells.count == 0, "delete: no placement of it left outside ({d})", .{cells.count});
+ }
+
+ fn haveTool(r: *Run, name: []const u8) bool {
+ const which = std.fmt.allocPrintSentinel(r.arena, "command -v {s} >/dev/null 2>&1", .{name}, 0) catch return false;
+ return system(which) == 0;
+ }
+
+ fn icat(r: *Run) !void {
+ if (!r.haveTool("kitten")) return skip("kitten icat: not installed", .{});
+ for ([_][]const u8{ "stream", "detect" }) |mode| {
+ const raw_from = r.h.raw.items.len;
+ const name = try std.fmt.allocPrint(r.arena, "icat-{s}", .{mode});
+ const line = try std.fmt.allocPrint(r.arena, "clear; kitten icat --transfer-mode={s} --align=left {s}/solid.png 2>{s}/{s}.out; touch {s}/{s}.out.done", .{ mode, r.base, r.base, name, r.base, name });
+ const err = try r.shell(name, line);
+ if (r.gui) {
+ try r.placedNear(name);
+ continue;
+ }
+ const raw = r.h.raw.items[raw_from..];
+ const sent = std.mem.indexOf(u8, raw, "\x1b_Gf=32,s=64,v=64,i=") != null;
+ check(sent and err.len == 0, "kitten icat --transfer-mode={s}: drawn outside ({s})", .{ mode, std.mem.trim(u8, err, " \r\n") });
+ }
+ }
+
+ fn chafa(r: *Run) !void {
+ if (!r.haveTool("chafa")) return skip("chafa: not installed", .{});
+ const raw_from = r.h.raw.items.len;
+ const err = try r.shell("chafa", try std.fmt.allocPrint(r.arena, "clear; chafa -f kitty -s 8x4 {s}/solid.png 2>{s}/chafa.out; touch {s}/chafa.out.done", .{ r.base, r.base, r.base }));
+ if (r.gui) return r.placedNear("chafa");
+ const raw = r.h.raw.items[raw_from..];
+ // chafa scales to the cells it asked for: any image transmitted.
+ check(std.mem.indexOf(u8, raw, "\x1b_Gf=32,s=") != null and err.len == 0, "chafa -f kitty: drawn outside ({s})", .{std.mem.trim(u8, err, " \r\n")});
+ }
+
+ fn placedNear(r: *Run, name: []const u8) !void {
+ const path = try r.capturePath();
+ const deadline = eh.nowMs() + 4000;
+ var count: usize = 0;
+ while (eh.nowMs() < deadline) {
+ if (captureColour(path, 4)) |seen| {
+ count = if (seen.bounds) |b| b.count else 0;
+ if (count > 200) break;
+ }
+ _ = try r.h.pumpOnce(50);
+ }
+ check(count > 200, "{s}: drawn in the GUI ({d} px of its colour)", .{ name, count });
+ }
+
+ /// Where `needle` is on the outer screen, in cells.
+ fn find(r: *Run, needle: []const u8) !?struct { x: usize, y: usize } {
+ const text = try r.h.screenText();
+ defer gpa.free(text);
+ var y: usize = 0;
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ while (lines.next()) |line| : (y += 1) {
+ if (std.mem.indexOf(u8, line, needle)) |x| return .{ .x = try std.unicode.utf8CountCodepoints(line[0..x]), .y = y };
+ }
+ return null;
+ }
+
+ const Cells = struct { count: usize = 0, min_x: usize = std.math.maxInt(usize), min_y: usize = std.math.maxInt(usize), rows: usize = 0, width: usize = 0 };
+
+ /// The outer terminal's placements of its `w`x`h` images, in viewport cells.
+ fn outerPlacements(r: *Run, w: u32, h: u32) !Cells {
+ const screen = r.h.term.screens.active;
+ const storage = &screen.kitty_images;
+ var out: Cells = .{};
+ var row_seen: [rows]bool = @splat(false);
+ var it = storage.placements.iterator();
+ while (it.next()) |entry| {
+ const img = storage.imageById(entry.key_ptr.image_id) orelse continue;
+ if (img.width != w or img.height != h) continue;
+ const pin = switch (entry.value_ptr.location) {
+ .pin => |pin| pin,
+ else => continue,
+ };
+ const at = screen.pages.pointFromPin(.viewport, pin.*) orelse continue;
+ out.count += 1;
+ out.min_x = @min(out.min_x, at.viewport.x);
+ out.min_y = @min(out.min_y, at.viewport.y);
+ if (at.viewport.y < rows and !row_seen[at.viewport.y]) {
+ row_seen[at.viewport.y] = true;
+ out.rows += 1;
+ }
+ out.width = @max(out.width, entry.value_ptr.columns);
+ }
+ return out;
+ }
+};
+
+extern "c" fn system(command: [*:0]const u8) c_int;
+extern "c" fn realpath(path: [*:0]const u8, resolved: ?[*]u8) ?[*:0]u8;
+
+fn absolute(arena: std.mem.Allocator, path: []const u8) ![:0]const u8 {
+ var buf: [4096]u8 = undefined;
+ const z = try arena.dupeSentinel(u8, path, 0);
+ const got = realpath(z, &buf) orelse return error.NoSuchArtifact;
+ return arena.dupeSentinel(u8, std.mem.span(got), 0);
+}
+
+/// The GUI's latest capture: its size and where the client's colour is.
+fn captureColour(path: [:0]const u8, tolerance: u8) ?struct { width: usize, height: usize, bounds: ?ColorBounds } {
+ var scratch: std.heap.ArenaAllocator = .init(gpa);
+ defer scratch.deinit();
+ const bytes = readFile(scratch.allocator(), path) catch return null;
+ const ppm = ppmView(bytes) orelse return null;
+ return .{ .width = ppm.width, .height = ppm.height, .bounds = colorBounds(ppm, client.colour, tolerance) };
+}
+
+const ColorBounds = struct { count: usize, min_x: usize, min_y: usize, max_x: usize, max_y: usize };
+const PpmView = struct { width: usize, height: usize, pixels: []const u8 };
+
+/// Where `colour` is in the capture, each channel within `tolerance`
+/// (chafa hands back its pixels a step off the source's).
+fn colorBounds(ppm: PpmView, colour: [3]u8, tolerance: u8) ?ColorBounds {
+ var b: ColorBounds = .{ .count = 0, .min_x = std.math.maxInt(usize), .min_y = std.math.maxInt(usize), .max_x = 0, .max_y = 0 };
+ for (0..ppm.width * ppm.height) |i| {
+ const px = ppm.pixels[i * 3 ..][0..3];
+ const near = for (px, colour) |got, want| {
+ if (@max(got, want) - @min(got, want) > tolerance) break false;
+ } else true;
+ if (!near) continue;
+ const x = i % ppm.width;
+ const y = i / ppm.width;
+ b.count += 1;
+ b.min_x = @min(b.min_x, x);
+ b.min_y = @min(b.min_y, y);
+ b.max_x = @max(b.max_x, x);
+ b.max_y = @max(b.max_y, y);
+ }
+ return if (b.count == 0) null else b;
+}
+
+fn ppmView(bytes: []const u8) ?PpmView {
+ if (!std.mem.startsWith(u8, bytes, "P6\n")) return null;
+ const dims_end = std.mem.indexOfScalarPos(u8, bytes, 3, '\n') orelse return null;
+ var dims = std.mem.splitScalar(u8, bytes[3..dims_end], ' ');
+ const width = std.fmt.parseUnsigned(usize, dims.next() orelse return null, 10) catch return null;
+ const height = std.fmt.parseUnsigned(usize, dims.next() orelse return null, 10) catch return null;
+ const max_end = std.mem.indexOfScalarPos(u8, bytes, dims_end + 1, '\n') orelse return null;
+ const len = width * height * 3;
+ if (bytes.len -| (max_end + 1) < len) return null;
+ return .{ .width = width, .height = height, .pixels = bytes[max_end + 1 ..][0..len] };
+}
+
+fn readFile(arena: std.mem.Allocator, path: [:0]const u8) ![]u8 {
+ const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0));
+ if (fd < 0) return error.OpenFailed;
+ defer _ = libc.close(fd);
+ var out: std.ArrayList(u8) = .empty;
+ var buf: [1 << 16]u8 = undefined;
+ while (true) {
+ const n = libc.read(fd, &buf, buf.len);
+ if (n < 0) return error.ReadFailed;
+ if (n == 0) break;
+ try out.appendSlice(arena, buf[0..@intCast(n)]);
+ }
+ return out.items;
+}
+
+/// A 64x64 PNG of the client's colour, stored (uncompressed) deflate.
+fn writePng(arena: std.mem.Allocator, path: [:0]const u8) !void {
+ const side = client.side;
+ var raw: std.ArrayList(u8) = .empty;
+ for (0..side) |_| {
+ try raw.append(arena, 0);
+ for (0..side) |_| try raw.appendSlice(arena, &client.colour);
+ }
+ var z: std.ArrayList(u8) = .empty;
+ try z.appendSlice(arena, &.{ 0x78, 0x01 });
+ var at: usize = 0;
+ while (at < raw.items.len) {
+ const n: u16 = @intCast(@min(65535, raw.items.len - at));
+ const final: u8 = if (at + n == raw.items.len) 1 else 0;
+ try z.append(arena, final);
+ try z.appendSlice(arena, &std.mem.toBytes(std.mem.nativeToLittle(u16, n)));
+ try z.appendSlice(arena, &std.mem.toBytes(std.mem.nativeToLittle(u16, ~n)));
+ try z.appendSlice(arena, raw.items[at..][0..n]);
+ at += n;
+ }
+ try z.appendSlice(arena, &std.mem.toBytes(std.mem.nativeToBig(u32, std.hash.Adler32.hash(raw.items))));
+ var png: std.ArrayList(u8) = .empty;
+ try png.appendSlice(arena, "\x89PNG\r\n\x1a\n");
+ var ihdr: [13]u8 = undefined;
+ std.mem.writeInt(u32, ihdr[0..4], side, .big);
+ std.mem.writeInt(u32, ihdr[4..8], side, .big);
+ ihdr[8..13].* = .{ 8, 2, 0, 0, 0 };
+ try chunk(arena, &png, "IHDR", &ihdr);
+ try chunk(arena, &png, "IDAT", z.items);
+ try chunk(arena, &png, "IEND", "");
+ try eh.writeFile(path, png.items);
+}
+
+fn chunk(arena: std.mem.Allocator, png: *std.ArrayList(u8), kind: *const [4]u8, data: []const u8) !void {
+ try png.appendSlice(arena, &std.mem.toBytes(std.mem.nativeToBig(u32, @intCast(data.len))));
+ try png.appendSlice(arena, kind);
+ try png.appendSlice(arena, data);
+ var crc = std.hash.Crc32.init();
+ crc.update(kind);
+ crc.update(data);
+ try png.appendSlice(arena, &std.mem.toBytes(std.mem.nativeToBig(u32, crc.final())));
+}
+
+fn removeTree(arena: std.mem.Allocator, base: [:0]const u8) void {
+ const cmd = std.fmt.allocPrintSentinel(arena, "rm -rf '{s}'", .{base}, 0) catch return;
+ _ = system(cmd);
+}