diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-28 21:03:48 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-28 21:23:53 -0300 |
| commit | b250eb6135475699a945324c005890e8e1b4dd0b (patch) | |
| tree | c32f06f89cdbd501ba5d75dc8ba80ecebbe3c278 | |
| parent | a48a825b06cc45947adaecf42073ed86af8b7a2d (diff) | |
| download | pardes-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]>
| -rw-r--r-- | build.zig | 56 | ||||
| -rw-r--r-- | docs/typ/building.typ | 4 | ||||
| -rw-r--r-- | src/CHANGELOG.md | 10 | ||||
| -rw-r--r-- | src/TerminalImages.zig | 35 | ||||
| -rw-r--r-- | src/image.zig | 3 | ||||
| -rw-r--r-- | src/pardes.zig | 10 | ||||
| -rw-r--r-- | src/terminal.zig | 45 | ||||
| -rw-r--r-- | test/kitty.zig | 778 | ||||
| -rw-r--r-- | test/kitty_client.zig | 150 | ||||
| -rw-r--r-- | test/kitty_harness.zig | 463 |
10 files changed, 1543 insertions, 11 deletions
@@ -1316,6 +1316,40 @@ pub fn build(b: *std.Build) void { run_image_harness.has_side_effects = true; b.step("image-harness", "exercise native Kitty/SDL image rendering end to end").dependOn(&run_image_harness.step); + // Kitty graphics through a terminal pane, end to end: a client in + // the pane's bash (and kitten icat, chafa when installed), a kitty + // terminal outside (tty) or the GPU capture (gui). test/kitty.zig + // is the same protocol at the core. + const kitty_client = b.addExecutable(.{ + .name = "pardes-kitty-client", + .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("test/kitty_client.zig"), + .link_libc = true, + }), + }); + const kitty_harness = b.addExecutable(.{ + .name = "pardes-kitty-harness", + .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("test/kitty_harness.zig"), + .link_libc = true, + }), + }); + if (ghostty_vt_for_snap) |vt| kitty_harness.root_module.addImport("ghostty-vt", vt); + switch (target.result.os.tag) { + .freebsd, .netbsd, .openbsd => kitty_harness.root_module.linkSystemLibrary("util", .{}), + else => {}, + } + const run_kitty_harness = b.addRunArtifact(kitty_harness); + run_kitty_harness.addArtifactArg(exe); + run_kitty_harness.addArtifactArg(kitty_client); + run_kitty_harness.addArg(if (platform == .gui) "gui" else "tty"); + run_kitty_harness.has_side_effects = true; + b.step("kitty-harness", "kitty graphics through a terminal pane end to end (a client inside, a kitty terminal or the GPU capture outside)").dependOn(&run_kitty_harness.step); + const pdf_harness_step = b.step("pdf-harness", "exercise continuous PDF rendering, search, and sections navigation end to end"); if (enable_mupdf) { const run_pdf_harness = b.addRunArtifact(image_harness); @@ -1694,6 +1728,28 @@ pub fn build(b: *std.Build) void { pane_test_step.dependOn(&run_pane_tests.step); if (testMatch(b, unit_profile, test_filters, pane_test_step)) |check| check.addArtifactArg(pane_tests); + // Kitty graphics conformance at the core: what a terminal pane's + // program sends, what it reads back, what ghostty stores and what a + // frame draws (test/kitty.zig). The end-to-end arm, through a real + // pty and the shell's output, is the kitty-harness step. + const kitty_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("test/kitty.zig"), + .link_libc = true, + }); + kitty_module.addImport("pardes", core_module); + const kitty_tests = b.addTest(.{ .root_module = kitty_module, .filters = test_filters }); + if (test_nonce) |nonce| kitty_tests.root_module.addImport("test_rebuild_nonce", nonce); + test_build.dependOn(&kitty_tests.step); + const run_kitty_tests = b.addRunArtifact(kitty_tests); + run_kitty_tests.has_side_effects = true; + unit_step.dependOn(&run_kitty_tests.step); + if (unit_match) |check| check.addArtifactArg(kitty_tests); + const kitty_test_step = b.step("kitty-test", "run the kitty graphics conformance cases for terminal panes"); + kitty_test_step.dependOn(&run_kitty_tests.step); + if (testMatch(b, unit_profile, test_filters, kitty_test_step)) |check| check.addArtifactArg(kitty_tests); + // Keep native transport integration reachable even when the core's // anonymous test-import block is filtered out by Zig. const ninep_io_module = b.createModule(.{ diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 8d7524f9..d551c251 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -72,6 +72,10 @@ zig build unit-test module and shell unit tests (the perf gate runs with zig build test-build compile the unit-test programs without running them zig build core-test core tests without native shell tests zig build pane-test pane, output, PDF and namespace integration tests +zig build kitty-test kitty graphics conformance of terminal panes, at the core +zig build kitty-harness kitty graphics through a pane end to end (a fake kitty + terminal outside on the tty, the GPU capture on the gui; + kitten icat and chafa too when installed) zig build syntax-test tree-sitter tests without building the editor zig build syntax deterministic per-byte highlighting snapshots zig build fs-test real sessions and mounts over 9P (with a short 9P monkey) diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 2144f710..7aab597d 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- Kitty graphics in a terminal pane take every medium kitty and ghostty + do: a file (`t=f`), a temporary file (`t=t`) and shared memory (`t=s`) + beside direct data, so `kitten icat` no longer falls back to base64 + through the pty. A program asking about many images in one write + hears every answer, where answers past 256 bytes of one read were cut + off mid-sequence (now 4 KiB, and an answer that does not fit is dropped + whole). Animations (`a=f`, `a=a`) play, frame by frame, where only the + first frame was drawn; and an image placed relative to another + (`P=`, `Q=`, `H=`, `V=`) is drawn beside it. `zig build kitty-test` and + `zig build kitty-harness` check the protocol through a terminal pane. - ghostty moves to its 1.4.0 release (from a main commit six days before it; libvaxis and uucode stay on the commits it pins). A terminal's `clear` (ED 3) now takes away the kitty images placed on the history it diff --git a/src/TerminalImages.zig b/src/TerminalImages.zig index 4140813f..f3333460 100644 --- a/src/TerminalImages.zig +++ b/src/TerminalImages.zig @@ -29,6 +29,9 @@ petscii: bool = false, converted: std.AutoHashMapUnmanaged(u32, Converted) = .empty, /// Glyph art for the fragments drawn as cells, kept while on screen. glyphs: std.AutoHashMapUnmanaged(GlyphKey, Glyphs) = .empty, +/// When the next frame of a playing animation (a=a) is due, in ms on the +/// core's clock (`Pardes.stepped_ns`): the core wakes for it (nextWake). +animation_due_ms: ?u64 = null, const Converted = struct { generation: u64, rgba: []u8, used: bool = true }; const Glyphs = struct { cells: []GlyphArt.Cell, used: bool = true }; @@ -147,6 +150,11 @@ pub fn draw( const screen = vt.screens.active; const storage = &screen.kitty_images; + // Animations step on the core's clock, as this frame shows them; the + // shown frame is `renderData()` (a new `generation` each step, which + // the caches key on). + const now_ms = p.stepped_ns / std.time.ns_per_ms; + ti.animation_due_ms = if (storage.animationTick(vt.io(), now_ms)) |delay| now_ms +| delay else null; const pages = &screen.pages; const top = pages.getTopLeft(.viewport); const bottom = pages.getBottomRight(.viewport) orelse return; @@ -187,10 +195,25 @@ pub fn draw( var it = storage.placements.iterator(); while (it.next()) |entry| { const placed = entry.value_ptr.*; + // A placement relative to another (P=/Q=) sits at its chain's root + // plus the chain's cell offsets (H=/V=), as ghostty's renderer puts it. + var dx: i64 = 0; + var dy: i64 = 0; const pin = switch (placed.location) { .pin => |pin| pin, - // ponytail: a placement relative to another (P=/Q=, new in ghostty) is not drawn; resolve its chain if a program needs it. - .virtual, .relative => continue, + .virtual => continue, + .relative => |rel| root: { + const chain = storage.resolveChain(rel) orelse continue; + dx = chain.horizontal_offset; + dy = chain.vertical_offset; + break :root switch (chain.root.location) { + .pin => |pin| pin, + // ponytail: a chain rooted on a virtual placement (shown + // through placeholders) is not drawn; ghostty anchors it at + // the placeholder run. + .virtual, .relative => continue, + }; + }, }; const img = storage.images.get(entry.key_ptr.image_id) orelse continue; const at = pages.pointFromPin(.screen, pin.*) orelse continue; @@ -201,8 +224,8 @@ pub fn draw( const sh = if (placed.source_height > 0) @min(placed.source_height, img.height - sy) else img.height - sy; if (size.width == 0 or size.height == 0 or sw == 0 or sh == 0) continue; ctx.place(img, .{ .x = sx, .y = sy, .w = sw, .h = sh }, .{ - .x = @as(i64, at.screen.x) * cw + placed.x_offset, - .y = (@as(i64, at.screen.y) - @as(i64, origin.screen.y)) * ch + placed.y_offset, + .x = (@as(i64, at.screen.x) + dx) * cw + placed.x_offset, + .y = (@as(i64, at.screen.y) - @as(i64, origin.screen.y) + dy) * ch + placed.y_offset, .w = size.width, .h = size.height, }); @@ -289,7 +312,7 @@ const Ctx = struct { fn pixelsOf(ti: *TerminalImages, gpa: std.mem.Allocator, img: gfx.Image) ?[]const u8 { const n = @as(usize, img.width) * img.height; if (n == 0) return null; - const data = img.data.bytes() orelse return null; + const data = img.renderData().bytes() orelse return null; if (img.format == .rgba) return if (data.len == n * 4) data else null; const gop = ti.converted.getOrPut(gpa, img.id) catch return null; if (gop.found_existing) { @@ -316,7 +339,7 @@ fn convert(gpa: std.mem.Allocator, img: gfx.Image, n: usize) ?[]u8 { .gray => 1, else => return null, }; - const data = img.data.bytes() orelse return null; + const data = img.renderData().bytes() orelse return null; if (data.len != n * depth) return null; const out = gpa.alloc(u8, n * 4) catch return null; for (0..n) |i| { diff --git a/src/image.zig b/src/image.zig index 19dbb9e4..5ceadd76 100644 --- a/src/image.zig +++ b/src/image.zig @@ -771,6 +771,9 @@ pub fn readable(bytes: []const u8) bool { const Decoded = struct { rgba: []u8, w: usize, h: usize }; pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?Decoded { + // stb_image allocates through what `start` gave it: before that, a call + // jumps through a null pointer (a terminal's PNG in a core no shell set up). + if (!started) return null; if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int)) return null; // Bounded before decoding: a few KB of PNG can name gigapixels. var iw: c_int = 0; diff --git a/src/pardes.zig b/src/pardes.zig index 3721cc32..c7ae6704 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -7813,6 +7813,16 @@ pub const Pardes = struct { const wait = @max(1, (pane.repl_enter_due_ns -| p.stepped_ns + animation.frame_ns - 1) / animation.frame_ns); frames = if (frames) |soonest| @min(soonest, wait) else wait; }; + // A terminal's kitty animation, at its next frame. Only a time still + // ahead counts: a pane not drawn keeps the last one it was given, + // and a past one would wake every frame for nothing. + if (comptime terminal_panes) for (p.panes) |slot| if (slot) |pane| if (panes.terminal.animationDueMs(pane)) |due_ms| { + const due = due_ms *| std.time.ns_per_ms; + if (due > p.stepped_ns) { + const wait = @max(1, (due - p.stepped_ns + animation.frame_ns - 1) / animation.frame_ns); + frames = if (frames) |soonest| @min(soonest, wait) else wait; + } + }; return if (frames) |n| p.stepped_ns + n * animation.frame_ns else null; } diff --git a/src/terminal.zig b/src/terminal.zig index 77ee9b44..ce41bd95 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -146,8 +146,14 @@ pub const MarkedHandler = if (enabled) struct { pub const State = struct { vt: VtSlot, stream: StreamSlot, - reply: [256]u8 = undefined, + /// The emulator's answers to its program (DSR, DA, kitty graphics, ...) + /// from one read of its output, written to its pty after it. Room for + /// a read's worth of kitty answers (yazi or `kitten icat` asking about + /// a batch of images in one write); an answer that does not fit whole + /// is dropped whole, never cut short (`reply_dropped` counts them). + reply: [4096]u8 = undefined, reply_len: u16 = 0, + reply_dropped: u32 = 0, /// The grid cell the program last heard the mouse at, so motion is /// reported once per cell. mouse_cell: if (enabled) ?ghostty_vt.Coordinate else void = if (enabled) null else {}, @@ -315,6 +321,16 @@ pub fn deinitPendingCommand(pane: *Pane) void { pane.pending_command = .{}; } +/// Where a kitty client puts its temporary files: `$TMPDIR`, else /tmp +/// (which ghostty accepts whatever this says). The environment block lives +/// as long as the process and pardes never edits it (ChildEnv.exportVar). +fn tempDir() []const u8 { + if (comptime !pardes.hosted) return "/tmp"; + const dir = std.c.getenv("TMPDIR") orelse return "/tmp"; + const path = std.mem.span(dir); + return if (path.len > 0 and path[0] == '/') path else "/tmp"; +} + pub fn terminalIo() std.Io { return if (comptime !pardes.hosted) std.Io.failing @@ -606,6 +622,13 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { .rows = rows, .max_scrollback_bytes = 16 * 1024 * 1024, .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, + // Every kitty medium, as ghostty and kitty take them: a file (t=f), + // a temporary file it then deletes (t=t, in the temp directory and + // named as one) and shared memory (t=s), beside direct data. libghostty + // defaults to direct alone, which `kitten icat` and timg detect and + // fall back from, base64 through the pty. What the program can read + // it could send itself: it runs as the user, under pardes. + .kitty_image_loading_limits = if (images_enabled) .allWithTempDir(tempDir()) else .direct, }); state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = gpa }); state.reply_len = 0; @@ -677,7 +700,6 @@ fn ingest(pane: *Pane, bytes: []const u8) void { pane.terminal.?.stream.nextSlice(bytes); } - test "replay ownership is terminal-only and construction rolls back on allocation failure" { const Case = struct { fn run(gpa: std.mem.Allocator, terminal: bool) !void { @@ -2808,9 +2830,14 @@ pub fn redo(p: *Pardes, pane: *Pane) void { pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); const room = state.reply.len - state.reply_len; - const n = @min(room, data.len); - @memcpy(state.reply[state.reply_len..][0..n], data[0..n]); - state.reply_len += @intCast(n); + // A cut answer is worse than none: the program would read the start of + // a sequence and wait, or misparse what follows. + if (data.len > room) { + state.reply_dropped +|= 1; + return; + } + @memcpy(state.reply[state.reply_len..][0..data.len], data); + state.reply_len += @intCast(data.len); } const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo( @@ -2838,6 +2865,14 @@ fn syncPixels(p: *const Pardes, pane: *Pane) void { vt.height_px = @as(u32, vt.rows) * p.cell_pixels.h; } +/// When the pane's next kitty animation frame is due (ms on the core's +/// clock), as its last drawn frame left it; null when nothing plays. +pub fn animationDueMs(pane: *const Pane) ?u64 { + if (comptime !images_enabled) return null; + const state = pane.terminal orelse return null; + return state.images.animation_due_ms; +} + /// The Petscii builtin on a terminal: its kitty graphics as glyph art, /// or back to pixels where the shell draws pixels. pub fn togglePetscii(pane: *Pane) void { diff --git a/test/kitty.zig b/test/kitty.zig new file mode 100644 index 00000000..3f9776fa --- /dev/null +++ b/test/kitty.zig @@ -0,0 +1,778 @@ +//! Kitty graphics protocol conformance for terminal panes, at the core. +//! +//! zig build kitty-test -Dplatform=tty|gui these cases alone +//! zig build unit-test they run with the rest +//! +//! ghostty-vt implements the protocol; what pardes owns is the proxy around +//! it: a program's APC reaches the emulator whole however the pty splits it, +//! the emulator's replies go back to that program's pty (and nowhere else), +//! and what the emulator stores is drawn where the program put it. Each case +//! feeds a pane's output the way a pty read does and checks all three: the +//! bytes the program would read back, ghostty's image storage, and the +//! `ImagePlace`s a frame hands the shell (which a tty re-emits to the outer +//! terminal and the GUI draws; test/kitty_harness.zig follows them there). +//! +//! A case pardes does not pass yet is a `knownGap`: its check runs, the test +//! is skipped with the reason while it fails, and fails once it passes, so +//! the marker goes when the gap closes. +const std = @import("std"); +const pardes = @import("pardes"); +const Pardes = pardes.Pardes; +const config = pardes.config; +const terminal = pardes.panes.terminal; + +const gpa = std.testing.allocator; + +// 4x2 pixels, the left half red and the right half blue, in every encoding +// the protocol has (generated with Python's zlib and a hand-built PNG). +const rgb_b64 = "/wAA/wAAAAD/AAD//wAA/wAAAAD/AAD/"; +const rgba_b64 = "/wAA//8AAP8AAP//AAD///8AAP//AAD/AAD//wAA//8="; +const rgb_zlib_b64 = "eJz7z8Dwn4EBTPz/j8QGAGO0B/k="; +const png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAIAAADwyuo0AAAAE0lEQVR4nGP4z8AARGDiPwMyBwBnsgf5Q2OaZwAAAABJRU5ErkJggg=="; +const rgb_raw = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255, 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 }; +// 256x256 transparent RGBA, zlib: 256 KiB stored per copy for 373 bytes sent. +const blank_256_zlib_b64 = "eNrtwTEBAAAAwqD1T+1tB6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN4AADwAAQ=="; + +const red = [4]u8{ 255, 0, 0, 255 }; +const blue = [4]u8{ 0, 0, 255, 255 }; + +/// `ESC _ G <control> ; <payload> ESC \` +inline fn apc(comptime control: []const u8, comptime payload: []const u8) []const u8 { + return comptime "\x1b_G" ++ control ++ ";" ++ payload ++ "\x1b\\"; +} + +/// What the protocol answers: `ESC _ G <keys> ; <message> ESC \` +inline fn reply(comptime keys: []const u8, comptime message: []const u8) []const u8 { + return comptime "\x1b_G" ++ keys ++ ";" ++ message ++ "\x1b\\"; +} + +fn knownGap(comptime reason: []const u8, passes: bool) !void { + if (passes) { + std.debug.print("kitty: a known gap passes now, drop its marker: {s}\n", .{reason}); + return error.KnownGapNowPasses; + } + std.debug.print("kitty: known gap: {s}\n", .{reason}); + return error.SkipZigTest; +} + +/// A session of `shells` (1, or up to 3) terminal panes with 10x20 pixel cells, under a +/// shell that draws pixels, every pane's keyboard at its pty. +const Rig = struct { + p: *Pardes, + frame: std.heap.ArenaAllocator, + /// What each pane's program has read back since `take`. + read: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty), + + fn init(shells: u8) !Rig { + // f=100 decodes through pardes's own decoder (stb_image), which the + // shells start at launch. + pardes.image.start(std.testing.io, gpa); + // ghostty warns of every refused command; the refusals are the point. + std.testing.log_level = .err; + // A core boots one shell or the classic three. + const p = try Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = if (shells > 1) 3 else 1 }); + p.native_images = true; + p.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 10, .h = 20 } } }); + for (p.panes) |slot| if (slot) |each| { + each.body.mode = .tty; + }; + var r: Rig = .{ .p = p, .frame = .init(gpa) }; + r.drain(); + for (&r.read) |*b| b.clearRetainingCapacity(); + return r; + } + + fn deinit(r: *Rig) void { + for (&r.read) |*b| b.deinit(gpa); + r.frame.deinit(); + r.p.deinit(); + pardes.image.stop(); + } + + fn drain(r: *Rig) void { + while (r.p.nextEffect()) |effect| { + if (effect == .write) r.read[effect.write.pane].appendSlice(gpa, effect.write.bytes.slice()) catch @panic("OOM"); + } + } + + /// One pty read of pane `id`'s output. + fn feed(r: *Rig, id: u8, bytes: []const u8) void { + r.p.update(.{ .output = .{ .pane = id, .bytes = bytes } }); + r.drain(); + } + + /// The same output, as reads of `step` bytes. + fn feedSplit(r: *Rig, id: u8, bytes: []const u8, step: usize) void { + var at: usize = 0; + while (at < bytes.len) : (at += step) r.feed(id, bytes[at..@min(bytes.len, at + step)]); + } + + /// What pane `id`'s program read back, since the last take. + fn take(r: *Rig, id: u8) ![]u8 { + defer r.read[id].clearRetainingCapacity(); + return r.frame.allocator().dupe(u8, r.read[id].items); + } + + fn pane(r: *Rig, id: u8) *pardes.Pane { + return r.p.panes[id].?; + } + + fn vt(r: *Rig, id: u8) @TypeOf(&r.pane(id).terminal.?.vt) { + return &r.pane(id).terminal.?.vt; + } + + fn storage(r: *Rig, id: u8) @TypeOf(&r.vt(id).screens.active.kitty_images) { + return &r.vt(id).screens.active.kitty_images; + } + + fn places(r: *Rig) ![]const ?pardes.ImagePlace { + _ = r.frame.reset(.retain_capacity); + const s = try r.p.render(r.frame.allocator()); + return s.images[0..s.nimages]; + } + + /// The top-left cell of pane `id`'s body, in screen cells. + fn origin(r: *Rig, id: u8) struct { x: u16, y: u16 } { + const rect = r.p.rects[id]; + return .{ .x = rect.x + config.GUTTER, .y = r.p.bodyTop(r.pane(id), rect) }; + } + + /// The places drawn for the image a program called `image_id`. + fn placesOf(r: *Rig, image_id: u32) ![]const pardes.ImagePlace { + var out: std.ArrayList(pardes.ImagePlace) = .empty; + for (try r.places()) |maybe| if (maybe) |place| if (place.native.page == image_id) + try out.append(r.frame.allocator(), place); + return out.items; + } + + fn placementCount(r: *Rig, id: u8) usize { + return r.storage(id).placements.count(); + } + + fn hasImage(r: *Rig, id: u8, image_id: u32) bool { + return r.storage(id).imageById(image_id) != null; + } +}; + +/// The pixel at `(x, y)` of a drawn place's whole image, as RGBA. +fn pixel(place: pardes.ImagePlace, x: usize, y: usize) [4]u8 { + return place.rgba[(y * place.iw + x) * 4 ..][0..4].*; +} + +test "kitty: a support query is answered on the asking pane's pty and stores nothing" { + var r = try Rig.init(2); + defer r.deinit(); + r.feed(1, apc("i=31,s=1,v=1,a=q,t=d,f=24", "AAAA")); + try std.testing.expectEqualStrings(reply("i=31", "OK"), try r.take(1)); + try std.testing.expectEqualStrings("", try r.take(0)); + try std.testing.expect(!r.hasImage(1, 31)); + try std.testing.expectEqual(@as(usize, 0), (try r.places()).len); +} + +test "kitty: a query that cannot load says why, with its keys" { + var r = try Rig.init(1); + defer r.deinit(); + // Too little data for a 2x2 RGB image. + r.feed(0, apc("i=32,s=2,v=2,a=q,t=d,f=24", "AAAA")); + const got = try r.take(0); + try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=32;E")); + try std.testing.expect(std.mem.endsWith(u8, got, "\x1b\\")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, got, "\x1b_G")); +} + +test "kitty: quiet levels: q=1 drops the OK, q=2 the errors too" { + const Case = struct { control: []const u8, payload: []const u8, answered: bool }; + const cases = [_]Case{ + .{ .control = "i=33,s=1,v=1,a=q,f=24,q=0", .payload = "AAAA", .answered = true }, + .{ .control = "i=33,s=1,v=1,a=q,f=24,q=1", .payload = "AAAA", .answered = false }, + .{ .control = "i=33,s=2,v=2,a=q,f=24,q=1", .payload = "AAAA", .answered = true }, + .{ .control = "i=33,s=2,v=2,a=q,f=24,q=2", .payload = "AAAA", .answered = false }, + .{ .control = "i=33,s=4,v=2,a=t,f=24,q=1", .payload = rgb_b64, .answered = false }, + .{ .control = "i=33,a=p,q=2", .payload = "", .answered = false }, + }; + for (cases) |c| { + var r = try Rig.init(1); + defer r.deinit(); + const bytes = try std.fmt.allocPrint(r.frame.allocator(), "\x1b_G{s};{s}\x1b\\", .{ c.control, c.payload }); + r.feed(0, bytes); + const got = try r.take(0); + std.testing.expectEqual(c.answered, got.len > 0) catch |err| { + std.debug.print("q case {s}: read back {f}\n", .{ c.control, std.ascii.hexEscape(got, .lower) }); + return err; + }; + } +} + +test "kitty: RGB, RGBA, PNG and zlib-compressed RGB all draw the same pixels" { + const Case = struct { control: []const u8, payload: []const u8 }; + const cases = [_]Case{ + .{ .control = "a=T,i=1,f=24,s=4,v=2,c=2,r=1", .payload = rgb_b64 }, + .{ .control = "a=T,i=1,f=32,s=4,v=2,c=2,r=1", .payload = rgba_b64 }, + .{ .control = "a=T,i=1,f=100,c=2,r=1", .payload = png_b64 }, + .{ .control = "a=T,i=1,f=24,o=z,s=4,v=2,c=2,r=1", .payload = rgb_zlib_b64 }, + }; + for (cases) |c| { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, try std.fmt.allocPrint(r.frame.allocator(), "\x1b_G{s};{s}\x1b\\", .{ c.control, c.payload })); + try std.testing.expectEqualStrings(reply("i=1", "OK"), try r.take(0)); + const img = r.storage(0).imageById(1) orelse return error.NotStored; + try std.testing.expectEqual(@as(u32, 4), img.width); + try std.testing.expectEqual(@as(u32, 2), img.height); + const drawn = try r.placesOf(1); + try std.testing.expectEqual(@as(usize, 1), drawn.len); + try std.testing.expectEqual(@as(usize, 4), drawn[0].iw); + for ([_][2]usize{ .{ 0, 0 }, .{ 1, 1 } }) |at| try std.testing.expectEqual(red, pixel(drawn[0], at[0], at[1])); + for ([_][2]usize{ .{ 2, 0 }, .{ 3, 1 } }) |at| try std.testing.expectEqual(blue, pixel(drawn[0], at[0], at[1])); + } +} + +test "kitty: a chunked transmission arrives whole however the pty splits it, answered once" { + // Three chunks of base64 (each a multiple of four), the keys on the first. + const chunked = apc("a=T,i=2,f=24,s=4,v=2,c=2,r=1,m=1", rgb_b64[0..8]) ++ + apc("m=1", rgb_b64[8..20]) ++ apc("m=0", rgb_b64[20..]); + for ([_]usize{ 1, 2, 3, 5, 7, 16, 64, chunked.len }) |step| { + var r = try Rig.init(1); + defer r.deinit(); + r.feedSplit(0, chunked, step); + try std.testing.expectEqualStrings(reply("i=2", "OK"), try r.take(0)); + const img = r.storage(0).imageById(2) orelse return error.NotStored; + try std.testing.expectEqualSlices(u8, &rgb_raw, img.data.bytes().?); + try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(2)).len); + } +} + +test "kitty: text around an APC prints, in the same read and split across reads" { + for ([_]usize{ 1, 4, 1024 }) |step| { + var r = try Rig.init(1); + defer r.deinit(); + r.feedSplit(0, "before" ++ apc("a=t,i=3,f=24,s=4,v=2,q=2", rgb_b64) ++ "after", step); + const text = try terminal.screenTextAlloc(r.pane(0), r.frame.allocator()); + try std.testing.expect(std.mem.indexOf(u8, text, "beforeafter") != null); + try std.testing.expect(r.hasImage(0, 3)); + } +} + +const shm = struct { + extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: std.c.mode_t) c_int; + extern "c" fn shm_unlink(name: [*:0]const u8) c_int; +}; + +fn writeTemp(path: [:0]const u8, bytes: []const u8) !void { + const fd = std.c.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o600)); + if (fd < 0) return error.OpenFailed; + defer _ = std.c.close(fd); + if (std.c.write(fd, bytes.ptr, bytes.len) != @as(isize, @intCast(bytes.len))) return error.WriteFailed; +} + +fn exists(path: [:0]const u8) bool { + return std.c.access(path, std.c.F_OK) == 0; +} + +fn b64(arena: std.mem.Allocator, bytes: []const u8) ![]const u8 { + const enc = std.base64.standard.Encoder; + const out = try arena.alloc(u8, enc.calcSize(bytes.len)); + return enc.encode(out, bytes); +} + +test "kitty: file, temporary-file and shared-memory media load, and the terminal removes what it should" { + var r = try Rig.init(1); + defer r.deinit(); + const arena = r.frame.allocator(); + const pid = std.c.getpid(); + + // t=f: a file the program keeps. + const file = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-file.rgb", .{pid}, 0); + try writeTemp(file, &rgb_raw); + defer _ = std.c.unlink(file); + r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=f,i=41,f=24,s=4,v=2;{s}\x1b\\", .{try b64(arena, file)})); + const file_reply = try r.take(0); + // t=t: a temporary file, which the terminal deletes once read; its name + // must say it is one. + const temp = try std.fmt.allocPrintSentinel(arena, "/tmp/tty-graphics-protocol-pardes-{d}.rgb", .{pid}, 0); + try writeTemp(temp, &rgb_raw); + defer _ = std.c.unlink(temp); + r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=t,i=42,f=24,s=4,v=2;{s}\x1b\\", .{try b64(arena, temp)})); + const temp_reply = try r.take(0); + // t=s: a POSIX shared memory object, which the terminal unlinks. + const name = try std.fmt.allocPrintSentinel(arena, "/pardes-kitty-{d}", .{pid}, 0); + const fd = shm.shm_open(name, @bitCast(std.c.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600); + if (fd < 0) return error.ShmOpenFailed; + defer _ = shm.shm_unlink(name); + if (std.c.write(fd, &rgb_raw, rgb_raw.len) != rgb_raw.len) return error.WriteFailed; + _ = std.c.close(fd); + r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=s,i=43,f=24,s=4,v=2,S={d};{s}\x1b\\", .{ rgb_raw.len, try b64(arena, name) })); + const shm_reply = try r.take(0); + + const passes = std.mem.eql(u8, file_reply, reply("i=41", "OK")) and + std.mem.eql(u8, temp_reply, reply("i=42", "OK")) and + std.mem.eql(u8, shm_reply, reply("i=43", "OK")); + if (!passes) { + std.debug.print("media replies: f {f} | t {f} | s {f}\n", .{ + std.ascii.hexEscape(file_reply, .lower), + std.ascii.hexEscape(temp_reply, .lower), + std.ascii.hexEscape(shm_reply, .lower), + }); + return error.MediumRefused; + } + for ([_]u32{ 41, 42, 43 }) |id| { + const img = r.storage(0).imageById(id) orelse return error.NotStored; + try std.testing.expectEqualSlices(u8, &rgb_raw, img.data.bytes().?); + } + try std.testing.expect(exists(file)); + try std.testing.expect(!exists(temp)); +} + +test "kitty: a temporary file outside the temp directory, or not named as one, is refused" { + var r = try Rig.init(1); + defer r.deinit(); + const arena = r.frame.allocator(); + const file = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-notemp.rgb", .{std.c.getpid()}, 0); + try writeTemp(file, &rgb_raw); + defer _ = std.c.unlink(file); + r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=t,i=44,f=24,s=4,v=2;{s}\x1b\\", .{try b64(arena, file)})); + const got = try r.take(0); + try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=44;E")); + try std.testing.expect(!r.hasImage(0, 44)); + // Refused, it is left where it was. + try std.testing.expect(exists(file)); +} + +test "kitty: a=T draws at the cursor and moves the cursor past the image; C=1 leaves it" { + for ([_]bool{ false, true }) |still| { + var r = try Rig.init(1); + defer r.deinit(); + if (still) + r.feed(0, "\x1b[3;5H" ++ apc("a=T,i=4,f=24,s=4,v=2,c=2,r=2,C=1,q=2", rgb_b64)) + else + r.feed(0, "\x1b[3;5H" ++ apc("a=T,i=4,f=24,s=4,v=2,c=2,r=2,q=2", rgb_b64)); + const cursor = r.vt(0).screens.active.cursor; + if (still) { + try std.testing.expectEqual(@as(usize, 4), cursor.x); + try std.testing.expectEqual(@as(usize, 2), cursor.y); + } else { + // Kitty: one cell past the image's right edge, on its last row. + try std.testing.expectEqual(@as(usize, 6), cursor.x); + try std.testing.expectEqual(@as(usize, 3), cursor.y); + } + const drawn = try r.placesOf(4); + // A cell row at a time: two rows. + try std.testing.expectEqual(@as(usize, 2), drawn.len); + const o = r.origin(0); + try std.testing.expectEqual(o.x + 4, drawn[0].x); + try std.testing.expectEqual(o.y + 2, drawn[0].y); + try std.testing.expectEqual(o.y + 3, drawn[1].y); + for (drawn) |place| try std.testing.expectEqual(@as(u16, 2), place.w); + } +} + +test "kitty: a=p places one image twice by placement id, a source rect crops it, and a re-put moves it" { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, apc("a=t,i=7,f=24,s=4,v=2", rgb_b64)); + try std.testing.expectEqualStrings(reply("i=7", "OK"), try r.take(0)); + try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(7)).len); + r.feed(0, "\x1b[1;1H" ++ apc("a=p,i=7,p=1,c=2,r=1", "")); + try std.testing.expectEqualStrings(reply("i=7,p=1", "OK"), try r.take(0)); + // The right half only (x=2, w=2): blue, in one cell. + r.feed(0, "\x1b[6;10H" ++ apc("a=p,i=7,p=2,x=2,y=0,w=2,h=2,c=1,r=1", "")); + try std.testing.expectEqualStrings(reply("i=7,p=2", "OK"), try r.take(0)); + try std.testing.expectEqual(@as(usize, 2), r.placementCount(0)); + const o = r.origin(0); + var drawn = try r.placesOf(7); + try std.testing.expectEqual(@as(usize, 2), drawn.len); + var cropped: ?pardes.ImagePlace = null; + for (drawn) |place| if (place.y == o.y + 5) { + cropped = place; + }; + const crop = cropped orelse return error.CroppedPlacementMissing; + try std.testing.expectEqual(o.x + 9, crop.x); + try std.testing.expectEqual(@as(u16, 1), crop.w); + const g = crop.native.geometry.?; + try std.testing.expectEqual(@as(u32, 2), g.src.x); + try std.testing.expectEqual(@as(u32, 2), g.src.w); + // Put again under the same id, placement 1 moves; it is not doubled. + r.feed(0, "\x1b[10;1H" ++ apc("a=p,i=7,p=1,c=2,r=1,q=1", "")); + try std.testing.expectEqual(@as(usize, 2), r.placementCount(0)); + drawn = try r.placesOf(7); + var at_ten = false; + var at_one = false; + for (drawn) |place| { + if (place.y == o.y + 9) at_ten = true; + if (place.y == o.y) at_one = true; + } + try std.testing.expect(at_ten and !at_one); +} + +test "kitty: a=p of an image that is not there answers ENOENT" { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, apc("a=p,i=99", "")); + const got = try r.take(0); + try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=99;ENOENT")); +} + +test "kitty: an image number gets an id, which the reply carries" { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, apc("a=t,I=5,f=24,s=4,v=2", rgb_b64)); + const got = try r.take(0); + // `i=<assigned>,I=5;OK` + try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=")); + try std.testing.expect(std.mem.endsWith(u8, got, ",I=5;OK\x1b\\")); + try std.testing.expect(r.storage(0).imageByNumber(5) != null); +} + +test "kitty: z-index orders images, and a negative one goes under the text" { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=8,f=24,s=4,v=2,c=2,r=1,z=-1,q=2", rgb_b64) ++ "\x1b[1;1Htext"); + try std.testing.expectEqual(@as(usize, 1), r.placementCount(0)); + var it = r.storage(0).placements.iterator(); + try std.testing.expectEqual(@as(i32, -1), it.next().?.value_ptr.z); + try knownGap("pardes draws every terminal image over the cells, in storage order: an ImagePlace has no z-index, so z<0 (under the text) and the order between overlapping images are lost", @hasField(pardes.ImagePlace, "z")); +} + +/// A screen with two images in known places, for the deletes: +/// image 1: placement 1 at (0,0) 2x1, placement 2 at (10,5) 2x1, z=5 +/// image 2: placement 1 at (20,8) 2x2, z=-3 +/// and the cursor parked at (20,8), on image 2. +fn deleteScene(r: *Rig) void { + r.feed(0, apc("a=t,i=1,f=24,s=4,v=2,q=2", rgb_b64) ++ apc("a=t,i=2,f=24,s=4,v=2,q=2", rgb_b64)); + r.feed(0, "\x1b[1;1H" ++ apc("a=p,i=1,p=1,c=2,r=1,C=1,q=2", "") ++ + "\x1b[6;11H" ++ apc("a=p,i=1,p=2,c=2,r=1,z=5,C=1,q=2", "") ++ + "\x1b[9;21H" ++ apc("a=p,i=2,p=1,c=2,r=2,z=-3,C=1,q=2", "")); +} + +test "kitty: every delete takes the placements it names, and the uppercase ones free the image" { + const Case = struct { + control: []const u8, + /// Placements left, and whether images 1 and 2 are still stored. + left: usize, + one: bool, + two: bool, + }; + const cases = [_]Case{ + .{ .control = "a=d", .left = 0, .one = true, .two = true }, // d=a is the default + .{ .control = "a=d,d=a", .left = 0, .one = true, .two = true }, + .{ .control = "a=d,d=A", .left = 0, .one = false, .two = false }, + .{ .control = "a=d,d=i,i=1", .left = 1, .one = true, .two = true }, + .{ .control = "a=d,d=I,i=1", .left = 1, .one = false, .two = true }, + .{ .control = "a=d,d=i,i=1,p=2", .left = 2, .one = true, .two = true }, + .{ .control = "a=d,d=c", .left = 2, .one = true, .two = true }, + .{ .control = "a=d,d=C", .left = 2, .one = true, .two = false }, + .{ .control = "a=d,d=p,x=11,y=6", .left = 2, .one = true, .two = true }, + .{ .control = "a=d,d=P,x=21,y=10", .left = 2, .one = true, .two = false }, + .{ .control = "a=d,d=q,x=11,y=6,z=5", .left = 2, .one = true, .two = true }, + .{ .control = "a=d,d=q,x=11,y=6,z=4", .left = 3, .one = true, .two = true }, + .{ .control = "a=d,d=x,x=2", .left = 2, .one = true, .two = true }, + .{ .control = "a=d,d=X,x=22", .left = 2, .one = true, .two = false }, + .{ .control = "a=d,d=y,y=6", .left = 2, .one = true, .two = true }, + .{ .control = "a=d,d=Y,y=10", .left = 2, .one = true, .two = false }, + .{ .control = "a=d,d=z,z=-3", .left = 2, .one = true, .two = true }, + .{ .control = "a=d,d=Z,z=-3", .left = 2, .one = true, .two = false }, + .{ .control = "a=d,d=r,x=1,y=1", .left = 1, .one = true, .two = true }, + .{ .control = "a=d,d=R,x=1,y=2", .left = 0, .one = false, .two = false }, + }; + for (cases) |c| { + var r = try Rig.init(1); + defer r.deinit(); + deleteScene(&r); + try std.testing.expectEqual(@as(usize, 3), r.placementCount(0)); + try std.testing.expectEqual(@as(usize, 4), (try r.places()).len); + r.feed(0, try std.fmt.allocPrint(r.frame.allocator(), "\x1b_G{s}\x1b\\", .{c.control})); + const drawn = (try r.places()).len; + const got = .{ r.placementCount(0), r.hasImage(0, 1), r.hasImage(0, 2) }; + std.testing.expectEqual(.{ c.left, c.one, c.two }, got) catch |err| { + std.debug.print("delete {s}: left {d}, image 1 {}, image 2 {}\n", .{ c.control, got[0], got[1], got[2] }); + return err; + }; + // Deletes never answer, and the frame draws what is left: a 2x1 + // placement is one place, the 2x2 one two. + try std.testing.expectEqualStrings("", try r.take(0)); + var rows: usize = 0; + var it = r.storage(0).placements.iterator(); + while (it.next()) |entry| rows += if (entry.key_ptr.image_id == 2) 2 else 1; + try std.testing.expectEqual(rows, drawn); + } +} + +test "kitty: deletes by image number take that image's placements, and N frees it" { + for ([_]bool{ false, true }) |free| { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, "\x1b[1;1H" ++ apc("a=T,I=11,f=24,s=4,v=2,c=2,r=1,C=1,q=2", rgb_b64) ++ + "\x1b[5;1H" ++ apc("a=T,i=2,f=24,s=4,v=2,c=2,r=1,C=1,q=2", rgb_b64)); + try std.testing.expectEqual(@as(usize, 2), r.placementCount(0)); + if (free) r.feed(0, apc("a=d,d=N,I=11", "")) else r.feed(0, apc("a=d,d=n,I=11", "")); + try std.testing.expectEqual(@as(usize, 1), r.placementCount(0)); + try std.testing.expectEqual(!free, r.storage(0).imageByNumber(11) != null); + try std.testing.expect(r.hasImage(0, 2)); + try std.testing.expectEqual(@as(usize, 1), (try r.places()).len); + } +} + +test "kitty: a delete abandons a chunked load in progress" { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, apc("a=t,i=9,f=24,s=4,v=2,m=1", rgb_b64[0..8])); + r.feed(0, apc("a=d,d=A", "")); + r.feed(0, apc("m=0", rgb_b64[8..])); + try std.testing.expect(!r.hasImage(0, 9)); +} + +test "kitty: Unicode placeholders draw a virtual placement over two rows, with implicit columns" { + var r = try Rig.init(1); + defer r.deinit(); + // Image 7 in the placeholders' foreground; row diacritics U+0305 (0) + // and U+030D (1); the first cell of each row names its column (U+0305 = + // 0) and the next one carries on from it with no diacritic of its own. + r.feed(0, apc("a=T,U=1,i=7,f=24,s=4,v=2,c=2,r=2,q=2", rgb_b64) ++ + "\x1b[2;3H\x1b[38;2;0;0;7m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}" ++ + "\x1b[3;3H\u{10EEEE}\u{030D}\u{0305}\u{10EEEE}\x1b[39mX"); + const drawn = try r.placesOf(7); + const o = r.origin(0); + try std.testing.expectEqual(@as(usize, 2), drawn.len); + try std.testing.expectEqual(o.x + 2, drawn[0].x); + try std.testing.expectEqual(o.y + 1, drawn[0].y); + try std.testing.expectEqual(o.y + 2, drawn[1].y); + for (drawn) |place| try std.testing.expectEqual(@as(u16, 2), place.w); + // The top row shows the image's top half, the bottom its bottom half. + try std.testing.expectEqual(@as(u32, 0), drawn[0].native.geometry.?.src.y); + try std.testing.expectEqual(@as(u32, 1), drawn[1].native.geometry.?.src.y); +} + +test "kitty: a placeholder naming its placement in the underline colour picks that placement" { + var r = try Rig.init(1); + defer r.deinit(); + // Two virtual placements of image 7: p=1 one cell, p=2 two cells wide. + r.feed(0, apc("a=t,i=7,f=24,s=4,v=2,q=2", rgb_b64) ++ + apc("a=p,U=1,i=7,p=1,c=1,r=1,q=2", "") ++ apc("a=p,U=1,i=7,p=2,c=2,r=1,q=2", "") ++ + "\x1b[1;1H\x1b[38;2;0;0;7m\x1b[58;2;0;0;2m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}\x1b[39;59m"); + const drawn = try r.placesOf(7); + try std.testing.expectEqual(@as(usize, 1), drawn.len); + // Placement 2 spans two cells, so each cell is half the image. + try std.testing.expectEqual(@as(u16, 2), drawn[0].w); +} + +test "kitty: an image follows its text when the shell scrolls, resizes and reflows" { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, "\x1b[5;1Hmarker" ++ apc("a=T,i=10,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64)); + const o = r.origin(0); + try std.testing.expectEqual(o.y + 4, (try r.placesOf(10))[0].y); + // Two lines of output at the bottom scroll it up two rows. + r.feed(0, "\x1b[40;1H\n\n"); + try std.testing.expectEqual(o.y + 2, (try r.placesOf(10))[0].y); + // A narrower pane reflows the text; the image stays on its row. + const pane = r.pane(0); + terminal.resizeGrid(pane, gpa, 40, pane.rows); + const text = try terminal.screenTextAlloc(pane, r.frame.allocator()); + var row: usize = 0; + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| : (row += 1) if (std.mem.startsWith(u8, line, "marker")) break; + const drawn = try r.placesOf(10); + try std.testing.expectEqual(@as(usize, 1), drawn.len); + const viewport_top: usize = @intCast(terminal.gridOffset(pane)); + try std.testing.expectEqual(o.y + @as(u16, @intCast(row - viewport_top)), drawn[0].y); +} + +test "kitty: the alternate screen has its own images, and the primary's come back after it" { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=11,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64)); + r.feed(0, "\x1b[?1049h"); + try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(11)).len); + // yazi's way in: the image goes on the alternate screen. + r.feed(0, "\x1b[3;3H" ++ apc("a=T,i=12,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64)); + try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(12)).len); + try std.testing.expect(!r.hasImage(0, 11)); // per screen + r.feed(0, "\x1b[?1049l"); + try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(12)).len); + try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(11)).len); +} + +test "kitty: clear (ED 2 + ED 3) takes the images away, and they stay away" { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=13,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64)); + var nl: [2 * 60]u8 = undefined; + for (0..60) |i| nl[2 * i ..][0..2].* = "\r\n".*; + r.feed(0, &nl); + r.feed(0, "\x1b[H\x1b[2J\x1b[3J"); + try std.testing.expectEqual(@as(usize, 0), r.placementCount(0)); + try std.testing.expectEqual(@as(usize, 0), (try r.places()).len); + r.feed(0, "after clear\r\n"); + try std.testing.expectEqual(@as(usize, 0), (try r.places()).len); +} + +test "kitty: replies go to the pane that asked, never another, and never into the drawn cells" { + var r = try Rig.init(3); + defer r.deinit(); + r.feed(1, apc("i=51,s=1,v=1,a=q,f=24", "AAAA")); + r.feed(2, apc("i=52,s=1,v=1,a=q,f=24", "AAAA")); + r.feed(1, apc("a=t,i=53,f=24,s=4,v=2", rgb_b64)); + r.feed(2, apc("a=p,i=53", "")); + try std.testing.expectEqualStrings(reply("i=51", "OK") ++ reply("i=53", "OK"), try r.take(1)); + try std.testing.expect(std.mem.startsWith(u8, try r.take(2), reply("i=52", "OK") ++ "\x1b_Gi=53;ENOENT")); + try std.testing.expectEqualStrings("", try r.take(0)); + // Images are per pane: pane 2 never sees pane 1's. + try std.testing.expect(r.hasImage(1, 53) and !r.hasImage(2, 53)); + _ = try r.places(); + const s = &r.p.surface; + for (0..s.rows) |y| for (0..s.cols) |x| { + const g = s.at(@intCast(x), @intCast(y)).grapheme(); + try std.testing.expect(std.mem.indexOfScalar(u8, g, 0x1b) == null); + try std.testing.expect(!std.mem.eql(u8, g, "_")); + }; +} + +test "kitty: many replies from one read all arrive, each whole, in order" { + var r = try Rig.init(1); + defer r.deinit(); + var batch: std.ArrayList(u8) = .empty; + defer batch.deinit(gpa); + var want: std.ArrayList(u8) = .empty; + defer want.deinit(gpa); + for (100..164) |id| { + try batch.print(gpa, "\x1b_Gi={d},s=1,v=1,a=q,f=24;AAAA\x1b\\", .{id}); + try want.print(gpa, "\x1b_Gi={d};OK\x1b\\", .{id}); + } + r.feed(0, batch.items); + try std.testing.expectEqualStrings(want.items, try r.take(0)); +} + +test "kitty: answers past what one read may hold are dropped whole, never cut" { + var r = try Rig.init(1); + defer r.deinit(); + var batch: std.ArrayList(u8) = .empty; + defer batch.deinit(gpa); + // Each fails with a long EINVAL: far more answer than the pane holds. + for (1..1001) |id| try batch.print(gpa, "\x1b_Gi={d},s=2,v=2,a=q,f=24;AAAA\x1b\\", .{id}); + r.feed(0, batch.items); + const got = try r.take(0); + try std.testing.expect(got.len > 0); + try std.testing.expect(r.pane(0).terminal.?.reply_dropped > 0); + // Whole sequences only, each its own `ESC _ G ... ESC \`. + var rest = got; + while (rest.len > 0) { + try std.testing.expect(std.mem.startsWith(u8, rest, "\x1b_Gi=")); + const end = std.mem.indexOf(u8, rest, "\x1b\\") orelse return error.CutAnswer; + try std.testing.expect(std.mem.indexOf(u8, rest[3..end], "\x1b") == null); + rest = rest[end + 2 ..]; + } + // The next read is answered again. + r.feed(0, apc("i=31,s=1,v=1,a=q,f=24", "AAAA")); + try std.testing.expectEqualStrings(reply("i=31", "OK"), try r.take(0)); +} + +test "kitty: the graphics answer comes before DA's, as a probe expects" { + var r = try Rig.init(1); + defer r.deinit(); + // yazi, chafa and kitten icat probe this way and wait for DA to end it. + r.feed(0, apc("i=31,s=1,v=1,a=q,t=d,f=24", "AAAA") ++ "\x1b[c"); + const got = try r.take(0); + const kitty = std.mem.indexOf(u8, got, reply("i=31", "OK")) orelse return error.NoKittyReply; + const da = std.mem.indexOf(u8, got, "\x1b[?") orelse return error.NoDaReply; + try std.testing.expect(kitty < da); +} + +test "kitty: a cancelled (CAN, SUB) APC runs nothing, answers nothing, and the text goes on" { + for ([_][]const u8{ "\x18", "\x1a" }) |cancel| { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, "\x1b_Ga=T,i=60,f=24,s=4,v=2;" ++ rgb_b64); + r.feed(0, cancel); + r.feed(0, "after"); + try std.testing.expect(!r.hasImage(0, 60)); + try std.testing.expectEqualStrings("", try r.take(0)); + const text = try terminal.screenTextAlloc(r.pane(0), r.frame.allocator()); + try std.testing.expect(std.mem.indexOf(u8, text, "after") != null); + } +} + +test "kitty: an image too large to hold is refused with an error" { + var r = try Rig.init(1); + defer r.deinit(); + // Past ghostty's 10000-pixel side. + r.feed(0, apc("a=t,i=61,f=32,s=20000,v=2,o=z", blank_256_zlib_b64)); + const got = try r.take(0); + try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=61;E")); + try std.testing.expect(!r.hasImage(0, 61)); +} + +test "kitty: many images stay inside the pane's storage limit, oldest out first, and go with the pane" { + var r = try Rig.init(1); + defer r.deinit(); + const storage = r.storage(0); + var buf: [600]u8 = undefined; + // 256 KiB each: 300 of them is past the 64 MiB a screen may hold. + for (1..301) |id| r.feed(0, try std.fmt.bufPrint(&buf, "\x1b_Ga=t,i={d},f=32,s=256,v=256,o=z,q=2;{s}\x1b\\", .{ id, blank_256_zlib_b64 })); + try std.testing.expect(storage.total_bytes <= storage.total_limit); + try std.testing.expect(storage.images.count() < 300); + try std.testing.expect(r.hasImage(0, 300)); + try std.testing.expect(!r.hasImage(0, 1)); + try std.testing.expectEqualStrings("", try r.take(0)); + // The testing allocator checks the pane gives all of it back (deinit). +} + +test "kitty: an animation's frames play" { + var r = try Rig.init(1); + defer r.deinit(); + // Root frame red, frame 2 blue (a whole-frame RGB replacement), then + // run it: s=3, looping. + const blue_frame = "AAD/AAD/AAD/AAD/AAD/AAD/AAD/AAD/"; + r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=70,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64) ++ + apc("a=f,i=70,f=24,s=4,v=2,z=40,q=2", blue_frame) ++ + // The root frame's gap is 0 (gapless, skipped) until it is given one. + apc("a=a,i=70,r=1,z=40,q=2", "") ++ + apc("a=a,i=70,s=3,v=1,q=2", "")); + const img = r.storage(0).imageById(70) orelse return error.NotStored; + try std.testing.expect(img.animation != null); + // On the core's clock: the first frame drawn starts it (red), the core + // asks to wake for the next, and a frame drawn after 40 ms shows blue. + const base: u64 = 10 * std.time.ns_per_s; + r.p.advance(base); + const first = try r.placesOf(70); + try std.testing.expectEqual(red, pixel(first[0], 0, 0)); + try std.testing.expect(r.p.nextWake() != null); + var shows_blue = false; + for (1..20) |k| { + r.p.advance(base + k * 50 * std.time.ns_per_ms); + const drawn = try r.placesOf(70); + if (drawn.len == 1 and std.mem.eql(u8, &pixel(drawn[0], 0, 0), &blue)) shows_blue = true; + } + try std.testing.expect(shows_blue); + // Stopped (s=1), nothing more to wake for. + r.feed(0, apc("a=a,i=70,s=1,q=2", "")); + _ = try r.places(); + try std.testing.expectEqual(@as(?u64, null), terminal.animationDueMs(r.pane(0))); +} + +test "kitty: a placement relative to another (P=, Q=) is drawn at its parent's cell plus H/V" { + var r = try Rig.init(1); + defer r.deinit(); + r.feed(0, apc("a=t,i=80,f=24,s=4,v=2,q=2", rgb_b64) ++ "\x1b[2;2H" ++ + apc("a=p,i=80,p=1,c=2,r=1,q=2", "") ++ + // Three cells right of placement 1, one row down; then one relative + // to that, a chain two deep. + apc("a=p,i=80,p=2,P=80,Q=1,H=3,V=1,c=2,r=1,q=2", "") ++ + apc("a=p,i=80,p=3,P=80,Q=2,H=3,c=2,r=1,q=2", "")); + try std.testing.expectEqual(@as(usize, 3), r.placementCount(0)); + const drawn = try r.placesOf(80); + try std.testing.expectEqual(@as(usize, 3), drawn.len); + const o = r.origin(0); + var cells: [3][2]u16 = undefined; + for (drawn, 0..) |place, i| cells[i] = .{ place.x - o.x, place.y - o.y }; + std.mem.sort([2]u16, &cells, {}, struct { + fn lt(_: void, a: [2]u16, b: [2]u16) bool { + return a[0] < b[0]; + } + }.lt); + try std.testing.expectEqual([2]u16{ 1, 1 }, cells[0]); + try std.testing.expectEqual([2]u16{ 4, 2 }, cells[1]); + try std.testing.expectEqual([2]u16{ 7, 2 }, cells[2]); + // Its parent deleted, a relative placement goes with it. + r.feed(0, apc("a=d,d=i,i=80,p=1", "")); + try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(80)).len); +} diff --git a/test/kitty_client.zig b/test/kitty_client.zig new file mode 100644 index 00000000..23c7587f --- /dev/null +++ b/test/kitty_client.zig @@ -0,0 +1,150 @@ +//! A kitty graphics client for test/kitty_harness.zig: run in a pardes +//! terminal pane, it plays one case of the protocol the way yazi or +//! `kitten icat` do (raw mode, a batch of commands, then reads what comes +//! back) and records every byte its pty gave it. +//! +//! pardes-kitty-client <case> <out> +//! +//! After the case's commands it sends a sync query (`i=999`); replies come +//! in order, so all the case's are in before the sync's. `<out>` gets the +//! bytes read, and `<out>.done` is made last, which the harness waits for. +const std = @import("std"); +const c = std.c; + +// 64x64 RGB, one colour: the harness looks for it in the outer terminal's +// image store and in the GUI's capture. +pub const side = 64; +pub const colour = [3]u8{ 13, 77, 231 }; +const sync = "\x1b_Gi=999,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\"; + +pub fn main(init: std.process.Init) !void { + var arena_state: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const args = try init.minimal.args.toSlice(arena); + if (args.len != 3) return error.BadArgs; + const case = args[1]; + const out = try arena.dupeSentinel(u8, args[2], 0); + + var saved: c.termios = undefined; + if (c.tcgetattr(0, &saved) != 0) return error.NotATerminal; + var raw = saved; + raw.lflag.ICANON = false; + raw.lflag.ECHO = false; + raw.cc[@backingInt(c.V.MIN)] = 0; + raw.cc[@backingInt(c.V.TIME)] = 1; + _ = c.tcsetattr(0, .NOW, &raw); + defer _ = c.tcsetattr(0, .NOW, &saved); + + var cmds: std.ArrayList(u8) = .empty; + try play(arena, case, &cmds); + try cmds.appendSlice(arena, sync); + try writeAll(cmds.items); + + // Read until the sync's answer, or 5 s. + var got: std.ArrayList(u8) = .empty; + var buf: [4096]u8 = undefined; + var waited: usize = 0; + while (waited < 50 and std.mem.indexOf(u8, got.items, "\x1b_Gi=999;") == null) { + const n = c.read(0, &buf, buf.len); + if (n > 0) try got.appendSlice(arena, buf[0..@intCast(n)]) else waited += 1; + } + // A little longer, for anything that should not have come. + for (0..3) |_| { + const n = c.read(0, &buf, buf.len); + if (n > 0) try got.appendSlice(arena, buf[0..@intCast(n)]); + } + // t=f's file stays the client's to remove (a terminal deletes only t=t's). + _ = c.unlink(try std.fmt.allocPrintSentinel(arena, "/tmp/kc-{d}.rgb", .{c.getpid()}, 0)); + try writeFile(out, got.items); + try writeFile(try std.fmt.allocPrintSentinel(arena, "{s}.done", .{out}, 0), ""); +} + +fn play(arena: std.mem.Allocator, case: []const u8, cmds: *std.ArrayList(u8)) !void { + const pixels = try solid(arena); + const enc = std.base64.standard.Encoder; + const b64 = try arena.alloc(u8, enc.calcSize(pixels.len)); + _ = enc.encode(b64, pixels); + const pid = c.getpid(); + + if (std.mem.eql(u8, case, "query")) { + // yazi's and chafa's probe: a graphics query, then DA to end it. + try cmds.appendSlice(arena, "\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\x1b[c"); + } else if (std.mem.eql(u8, case, "place")) { + // A line to find, then the image right after it: chunked in 1 KiB + // pieces, as kitten icat sends a big one, 8x4 cells. + try cmds.appendSlice(arena, "\r\nANCHOR>"); + var at: usize = 0; + var first = true; + while (at < b64.len) : (at += 1024) { + const end = @min(b64.len, at + 1024); + const more: u8 = if (end < b64.len) '1' else '0'; + if (first) + try cmds.print(arena, "\x1b_Ga=T,i=42,f=24,s={d},v={d},c=8,r=4,m={c};{s}\x1b\\", .{ side, side, more, b64[at..end] }) + else + try cmds.print(arena, "\x1b_Gm={c};{s}\x1b\\", .{ more, b64[at..end] }); + first = false; + } + try cmds.appendSlice(arena, "\r\n"); + } else if (std.mem.eql(u8, case, "media")) { + const file = try std.fmt.allocPrintSentinel(arena, "/tmp/kc-{d}.rgb", .{pid}, 0); + const temp = try std.fmt.allocPrintSentinel(arena, "/tmp/tty-graphics-protocol-kc-{d}.rgb", .{pid}, 0); + const shm_name = try std.fmt.allocPrintSentinel(arena, "/kc-{d}", .{pid}, 0); + try writeFile(file, pixels); + try writeFile(temp, pixels); + const fd = shm_open(shm_name, @bitCast(c.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600); + if (fd < 0) return error.ShmOpenFailed; + if (c.write(fd, pixels.ptr, pixels.len) != @as(isize, @intCast(pixels.len))) return error.WriteFailed; + _ = c.close(fd); + for ([_]struct { u8, u32, []const u8 }{ .{ 'f', 51, file }, .{ 't', 52, temp }, .{ 's', 53, shm_name } }) |m| { + const path = try arena.alloc(u8, enc.calcSize(m[2].len)); + _ = enc.encode(path, m[2]); + try cmds.print(arena, "\x1b_Ga=t,t={c},i={d},f=24,s={d},v={d};{s}\x1b\\", .{ m[0], m[1], side, side, path }); + } + } else if (std.mem.eql(u8, case, "quiet")) { + // q=1 hides the OK, q=2 the error; q=0's error is heard. + try cmds.print(arena, "\x1b_Ga=t,i=61,f=24,s={d},v={d},q=1;{s}\x1b\\", .{ side, side, b64 }); + try cmds.appendSlice(arena, "\x1b_Ga=t,i=62,f=24,s=2,v=2,q=2;AAAA\x1b\\"); + try cmds.appendSlice(arena, "\x1b_Ga=t,i=63,f=24,s=2,v=2,q=0;AAAA\x1b\\"); + } else if (std.mem.eql(u8, case, "cancel")) { + // CAN in the middle of the payload: nothing runs, the text goes on. + try cmds.print(arena, "\x1b_Ga=T,i=64,f=24,s={d},v={d};{s}\x18CANCELLED-OK\r\n", .{ side, side, b64[0..512] }); + } else if (std.mem.eql(u8, case, "show")) { + try cmds.print(arena, "\x1b_Ga=T,i=65,f=24,s={d},v={d},c=8,r=4,q=2;{s}\x1b\\\r\n", .{ side, side, b64 }); + } else if (std.mem.eql(u8, case, "delete")) { + // Run after `show`, in the same pane: image 65 is still stored. + try cmds.appendSlice(arena, "\x1b_Ga=d,d=I,i=65\x1b\\"); + } else return error.UnknownCase; +} + +extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: c.mode_t) c_int; + +fn solid(arena: std.mem.Allocator) ![]u8 { + const px = try arena.alloc(u8, side * side * 3); + for (0..side * side) |i| px[i * 3 ..][0..3].* = colour; + return px; +} + +fn writeAll(bytes: []const u8) !void { + var at: usize = 0; + while (at < bytes.len) { + const n = c.write(1, bytes[at..].ptr, bytes.len - at); + if (n < 0) { + if (c.errno(n) == .INTR or c.errno(n) == .AGAIN) continue; + return error.WriteFailed; + } + at += @intCast(n); + } +} + +fn writeFile(path: [:0]const u8, bytes: []const u8) !void { + const fd = c.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(c.mode_t, 0o644)); + if (fd < 0) return error.OpenFailed; + defer _ = c.close(fd); + var at: usize = 0; + while (at < bytes.len) { + const n = c.write(fd, bytes[at..].ptr, bytes.len - at); + if (n <= 0) return error.WriteFailed; + at += @intCast(n); + } +} 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); +} |
