//! 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(); if (std.c.getenv("PARDES_KITTY_EXPLORE")) |list| return run.explore(std.mem.span(list)); 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(); if (!gui) try run.under(); try run.icat(); try run.chafa(); try run.yazi(); if (!gui) try plainOuter(arena, exe, kc, base); std.debug.print("kitty harness: {d} failed, {d} skipped\n", .{ failures, skipped }); if (failures > 0) return error.KittyHarnessFailed; } /// Outside, a terminal without kitty graphics (it answers DA, not the /// graphics query): pardes must send it no graphics command, and draws the /// pane's image as glyph art; the program in the pane is answered as ever. fn plainOuter(arena: std.mem.Allocator, exe: [:0]const u8, kc: []const u8, base: [:0]const u8) !void { var h = try eh.Harness.initArgv(gpa, exe, rows, cols, &.{}); defer h.deinit(); try h.expectRawWaitFor("\x1b_Gi=1,a=q\x1b\\", 8000, "pardes did not probe for kitty graphics"); try h.send("\x1b[?62;22c"); try h.expectWaitFor("$ ", 10_000, "the shell's prompt did not show"); try h.pump(400); var run: Run = .{ .arena = arena, .h = &h, .base = base, .kc = kc, .gui = false }; const probe_end = h.raw.items.len; const got = try run.case("place"); check(std.mem.eql(u8, got, "\x1b_Gi=42;OK\x1b\\" ++ sync_reply), "plain outer: the pane's program is answered as ever ({f})", .{std.ascii.hexEscape(got, .lower)}); const raw = h.raw.items[probe_end..]; const sent = std.mem.count(u8, raw, "\x1b_G"); check(sent == 0, "plain outer: no graphics command reaches a terminal without them ({d})", .{sent}); // Glyph art fills the 8x4 cells after ANCHOR>: a solid picture is all // background colour (C64's nearest blue), no glyph. const anchor = try run.find("ANCHOR>") orelse { check(false, "plain outer: ANCHOR> on the screen", .{}); return; }; var art: usize = 0; for (0..4) |dy| for (0..8) |dx| { const cell = h.term.screens.active.pages.getCell(.{ .viewport = .{ .x = @intCast(anchor.x + 7 + dx), .y = @intCast(anchor.y + dy) } }) orelse continue; if (cell.style().bg_color != .none) art += 1; }; check(art == 32, "plain outer: the image is glyph art in its cells ({d} of 32 coloured)", .{art}); } fn hermetic(arena: std.mem.Allocator, base: [:0]const u8, gui: bool) !void { // zig build hands its children NO_COLOR, and vaxis honours it: pardes // would draw no colour at all, glyph art included. Emptied, not unset: // unsetenv compacts the environment block std captured (a null later). _ = setenv("NO_COLOR", "", 1); 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 `.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}); } /// PARDES_KITTY_EXPLORE=: each line `namecommand` runs in /// the pane under `script`, whose log (the client's own bytes, as it /// ran under pardes) goes to $PARDES_KITTY_RECORD/.log; then the /// outer screen and pardes's placements there are printed. fn explore(r: *Run, list_path: []const u8) !void { const list = try readFile(r.arena, try r.arena.dupeSentinel(u8, list_path, 0)); const record = if (std.c.getenv("PARDES_KITTY_RECORD")) |d| std.mem.span(d) else r.base; var lines = std.mem.splitScalar(u8, list, '\n'); while (lines.next()) |line| { const tab = std.mem.indexOfScalar(u8, line, '\t') orelse continue; const name = line[0..tab]; const cmd = std.mem.replaceOwned(u8, r.arena, line[tab + 1 ..], "$BASE", r.base) catch line[tab + 1 ..]; const raw_from = r.h.raw.items.len; const shell_line = try std.fmt.allocPrint(r.arena, "clear; script -q -O {s}/{s}.log -c '{s}' 2>{s}/{s}.err; touch {s}/{s}.out.done", .{ record, name, cmd, r.base, name, r.base, name }); _ = try r.shell(name, shell_line); try r.h.pump(800); std.debug.print("=== {s}: {s}\n", .{ name, cmd }); const err = readFile(r.arena, try std.fmt.allocPrintSentinel(r.arena, "{s}/{s}.err", .{ r.base, name }, 0)) catch ""; if (err.len > 0) std.debug.print("stderr: {s}\n", .{err}); const raw = r.h.raw.items[raw_from..]; std.debug.print("outer: {d} transmits, {d} puts, {d} deletes\n", .{ std.mem.count(u8, raw, "\x1b_Gf="), std.mem.count(u8, raw, "\x1b_Ga=p"), std.mem.count(u8, raw, "\x1b_Ga=d") }); var kinds: std.array_hash_map.String(usize) = .empty; var from: usize = 0; while (std.mem.indexOfPos(u8, raw, from, "\x1b_Ga=")) |i| : (from = i + 1) { const end = std.mem.indexOfAnyPos(u8, raw, i + 1, ";\x1b") orelse continue; var key = raw[i + 3 .. @min(end, i + 3 + 40)]; // Ids and geometry vary; the command's shape is the point. if (std.mem.indexOf(u8, key, ",i=")) |cut| key = key[0..cut]; const gop = try kinds.getOrPut(r.arena, key); gop.value_ptr.* = if (gop.found_existing) gop.value_ptr.* + 1 else 1; } for (kinds.keys(), kinds.values()) |k, n| std.debug.print(" {d}x {s}\n", .{ n, k }); const screen = r.h.term.screens.active; const storage = &screen.kitty_images; var it = storage.placements.iterator(); while (it.next()) |entry| { const img = storage.imageById(entry.key_ptr.image_id) orelse continue; const where: []const u8 = switch (entry.value_ptr.location) { .pin => |pin| if (screen.pages.pointFromPin(.viewport, pin.*)) |at| try std.fmt.allocPrint(r.arena, "{d},{d}", .{ at.viewport.x, at.viewport.y }) else "off-viewport", .virtual => "virtual", .relative => "relative", }; std.debug.print(" image {d} {d}x{d}px at {s} {d}x{d} cells src {d},{d} {d}x{d}\n", .{ entry.key_ptr.image_id, img.width, img.height, where, entry.value_ptr.columns, entry.value_ptr.rows, entry.value_ptr.source_x, entry.value_ptr.source_y, entry.value_ptr.source_width, entry.value_ptr.source_height }); } r.h.dump(name); } } fn under(r: *Run) !void { _ = try r.case("under"); const storage = &r.h.term.screens.active.kitty_images; var it = storage.placements.iterator(); var seen: usize = 0; var below: usize = 0; while (it.next()) |entry| { const img = storage.imageById(entry.key_ptr.image_id) orelse continue; if (img.width != client.side or img.height != client.side) continue; seen += 1; if (entry.value_ptr.z == -1) below += 1; } check(seen > 0 and below == seen, "under: z=-1 reaches the outer terminal on every row ({d} of {d})", .{ below, seen }); } 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")}); } /// yazi previews the PNG (its first entry) through shared memory and a /// virtual placement shown by placeholders, in its right-hand column. /// Killed after 6 s, it leaves the preview up. fn yazi(r: *Run) !void { if (!r.haveTool("yazi")) return skip("yazi: not installed", .{}); const raw_from = r.h.raw.items.len; _ = try r.shell("yazi", try std.fmt.allocPrint(r.arena, "clear; mkdir -p {s}/yz; cp {s}/solid.png {s}/yz/; timeout --foreground -s KILL 6 yazi {s}/yz 2>{s}/yazi.out; touch {s}/yazi.out.done", .{ r.base, r.base, r.base, r.base, r.base, r.base })); if (r.gui) return r.placedNear("yazi"); const raw = r.h.raw.items[raw_from..]; const cells = try r.outerPlacements(client.side, client.side); check(std.mem.indexOf(u8, raw, "\x1b_Gf=32,s=64,v=64,i=") != null and cells.count == 4 and cells.min_x > cols / 2, "yazi: its preview drawn outside, in its right half ({d} rows at {d},{d})", .{ cells.count, cells.min_x, cells.min_y }); } 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); }