summaryrefslogtreecommitdiff
path: root/test/kitty.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-30 17:35:06 -0300
committerGabriel Schneider <[email protected]>2026-10-30 17:35:06 -0300
commit6d8da8721141284cf33bb901168b26135893eb86 (patch)
tree791d63401d4e85fbca1d597a8ce0326e70efd545 /test/kitty.zig
parentefd43a3a2cf03bb741366331158b368abf9ac583 (diff)
parentbf6810a8f9d6cc82050e7d9c0cfb06358301b574 (diff)
downloadpardes-6d8da8721141284cf33bb901168b26135893eb86.tar.gz
pardes-6d8da8721141284cf33bb901168b26135893eb86.zip
Merge latest upstream into the macOS branch for Zig 0.17
Retain the macOS branch history and local Acme selection color while adopting upstream's current core and platform changes. Pin Zig and ZLS to 0.17.0, and fetch the existing zstbi compatibility commit through upstream after its original fork was removed.
Diffstat (limited to 'test/kitty.zig')
-rw-r--r--test/kitty.zig1349
1 files changed, 1349 insertions, 0 deletions
diff --git a/test/kitty.zig b/test/kitty.zig
new file mode 100644
index 00000000..de4dd605
--- /dev/null
+++ b/test/kitty.zig
@@ -0,0 +1,1349 @@
+//! 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 travels with the image, and images are handed on lowest z first" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ // Three overlapping at (0,0), given out of order; the virtual one's z
+ // is its placement's.
+ r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=8,f=24,s=4,v=2,c=2,r=1,z=5,C=1,q=2", rgb_b64) ++
+ apc("a=T,i=9,f=24,s=4,v=2,c=2,r=1,z=-7,C=1,q=2", rgb_b64) ++
+ apc("a=T,i=10,f=24,s=4,v=2,c=2,r=1,C=1,q=2", rgb_b64) ++
+ apc("a=T,U=1,i=11,f=24,s=4,v=2,c=1,r=1,z=3,q=2", rgb_b64) ++
+ "\x1b[1;1H\x1b[38;2;0;0;11m\u{10EEEE}\u{0305}\u{0305}\x1b[39m");
+ const drawn = try r.places();
+ try std.testing.expectEqual(@as(usize, 4), drawn.len);
+ var zs: [4]i32 = undefined;
+ var ids: [4]u32 = undefined;
+ for (drawn, 0..) |place, i| {
+ zs[i] = place.?.z;
+ ids[i] = place.?.native.page;
+ }
+ try std.testing.expectEqualSlices(i32, &.{ -7, 0, 3, 5 }, &zs);
+ try std.testing.expectEqualSlices(u32, &.{ 9, 10, 11, 8 }, &ids);
+}
+
+/// 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);
+}
+
+// ---- What t=f, t=t and t=s may make pardes open ----
+//
+// A program in a pane names paths on pardes's machine. Which paths ghostty's
+// loader accepts is its policy (kitty's, which the user accepts); what pardes
+// owns is that none of them hangs or crashes it or blows its memory: a FIFO
+// (an open for reading waits for a writer), a device (an open may do
+// something), a file no screen could hold. And t=t deletes temporary files
+// only.
+
+extern "c" fn mkfifo(path: [*:0]const u8, mode: std.c.mode_t) c_int;
+extern "c" fn symlink(target: [*:0]const u8, link: [*:0]const u8) c_int;
+extern "c" fn usleep(us: c_uint) c_int;
+extern "c" fn ftruncate(fd: c_int, len: i64) c_int;
+extern "c" fn getcwd(buf: [*]u8, size: usize) ?[*:0]u8;
+
+const Guard = struct {
+ path: [:0]const u8,
+ done: std.atomic.Value(bool) = .init(false),
+ blocked: std.atomic.Value(bool) = .init(false),
+
+ /// After 1.5 s still running, the feed is stuck in an open of the FIFO:
+ /// open it for writing, which lets that open return.
+ fn run(g: *Guard) void {
+ for (0..150) |_| {
+ if (g.done.load(.acquire)) return;
+ _ = usleep(10_000);
+ }
+ g.blocked.store(true, .release);
+ const fd = std.c.open(g.path, .{ .ACCMODE = .WRONLY }, @as(std.c.mode_t, 0));
+ if (fd >= 0) _ = std.c.close(fd);
+ }
+};
+
+/// Feeds `bytes`; whether the feed blocked opening `fifo`.
+fn feedBlocks(r: *Rig, bytes: []const u8, fifo: [:0]const u8) !bool {
+ var g: Guard = .{ .path = fifo };
+ const t = try std.Thread.spawn(.{}, Guard.run, .{&g});
+ r.feed(0, bytes);
+ g.done.store(true, .release);
+ t.join();
+ return g.blocked.load(.acquire);
+}
+
+test "kitty: a FIFO named by t=f, t=t or t=s never blocks pardes" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ const arena = r.frame.allocator();
+ const pid = std.c.getpid();
+ const Case = struct { medium: u8, fifo: [:0]const u8, name: []const u8 };
+ const file = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-fifo", .{pid}, 0);
+ const temp = try std.fmt.allocPrintSentinel(arena, "/tmp/tty-graphics-protocol-pardes-{d}-fifo", .{pid}, 0);
+ const shm_path = try std.fmt.allocPrintSentinel(arena, "/dev/shm/pardes-kitty-{d}-fifo", .{pid}, 0);
+ const cases = [_]Case{
+ .{ .medium = 'f', .fifo = file, .name = file },
+ .{ .medium = 't', .fifo = temp, .name = temp },
+ .{ .medium = 's', .fifo = shm_path, .name = shm_path["/dev/shm".len..] },
+ };
+ for (cases) |c| {
+ _ = std.c.unlink(c.fifo);
+ if (mkfifo(c.fifo, 0o600) != 0) return error.MkfifoFailed;
+ defer _ = std.c.unlink(c.fifo);
+ const cmd = try std.fmt.allocPrint(arena, "\x1b_Ga=t,t={c},i=90,f=24,s=1,v=1;{s}\x1b\\", .{ c.medium, try b64(arena, c.name) });
+ const blocked = try feedBlocks(&r, cmd, c.fifo);
+ if (blocked) std.debug.print("t={c}: pardes blocked opening the FIFO {s}\n", .{ c.medium, c.fifo });
+ try std.testing.expect(!blocked);
+ try std.testing.expect(std.mem.startsWith(u8, try r.take(0), "\x1b_Gi=90;E"));
+ try std.testing.expect(!r.hasImage(0, 90));
+ }
+}
+
+test "kitty: t=s through a /dev/shm symlink to a FIFO does not block pardes either" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ const arena = r.frame.allocator();
+ const pid = std.c.getpid();
+ const fifo = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-shmfifo", .{pid}, 0);
+ _ = std.c.unlink(fifo);
+ if (mkfifo(fifo, 0o600) != 0) return error.MkfifoFailed;
+ defer _ = std.c.unlink(fifo);
+ const link = try std.fmt.allocPrintSentinel(arena, "/dev/shm/pardes-kitty-{d}-link", .{pid}, 0);
+ _ = std.c.unlink(link);
+ if (symlink(fifo, link) != 0) return error.SymlinkFailed;
+ defer _ = std.c.unlink(link);
+ const cmd = try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=s,i=91,f=24,s=1,v=1;{s}\x1b\\", .{try b64(arena, link["/dev/shm".len..])});
+ try std.testing.expect(!try feedBlocks(&r, cmd, fifo));
+ try std.testing.expect(std.mem.startsWith(u8, try r.take(0), "\x1b_Gi=91;E"));
+}
+
+test "kitty: t=f and t=t refuse /proc, /sys, devices and directories" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ const arena = r.frame.allocator();
+ const refused = [_][]const u8{ "/proc/self/status", "/sys/devices/system/cpu/online", "/dev/null", "/dev/zero", "/dev/urandom", "/tmp", "/" };
+ for ([_]u8{ 'f', 't' }) |medium| for (refused) |path| {
+ // A raw 1x1 pixel needs 3 bytes (S=3): any readable file would do.
+ r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t={c},i=92,f=24,s=1,v=1,S=3;{s}\x1b\\", .{ medium, try b64(arena, path) }));
+ try std.testing.expect(std.mem.startsWith(u8, try r.take(0), "\x1b_Gi=92;E"));
+ try std.testing.expect(!r.hasImage(0, 92));
+ };
+}
+
+test "kitty: t=t deletes only a temporary file: one outside the temp directory, or behind a symlink, stays" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ const arena = r.frame.allocator();
+ const pid = std.c.getpid();
+ var cwd_buf: [4096]u8 = undefined;
+ const cwd = std.mem.span(getcwd(&cwd_buf, cwd_buf.len) orelse return error.NoCwd);
+ // Outside /tmp, /dev/shm and $TMPDIR: the build's own cache.
+ const dir = try std.fmt.allocPrintSentinel(arena, "{s}/.zig-cache/tmp/pardes-kitty-{d}", .{ cwd, pid }, 0);
+ _ = std.c.mkdir(dir, 0o700);
+ defer _ = std.c.rmdir(dir);
+ const kept = try std.fmt.allocPrintSentinel(arena, "{s}/tty-graphics-protocol-kept.rgb", .{dir}, 0);
+ try writeTemp(kept, &rgb_raw);
+ defer _ = std.c.unlink(kept);
+ const link = try std.fmt.allocPrintSentinel(arena, "/tmp/tty-graphics-protocol-pardes-{d}-link", .{pid}, 0);
+ _ = std.c.unlink(link);
+ if (symlink(kept, link) != 0) return error.SymlinkFailed;
+ defer _ = std.c.unlink(link);
+ for ([_][:0]const u8{ kept, link }) |path| {
+ r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=t,i=93,f=24,s=4,v=2;{s}\x1b\\", .{try b64(arena, path)}));
+ try std.testing.expect(std.mem.startsWith(u8, try r.take(0), "\x1b_Gi=93;E"));
+ try std.testing.expect(!r.hasImage(0, 93));
+ try std.testing.expect(exists(kept));
+ }
+}
+
+test "kitty: a file bigger than a screen may hold is refused, not read whole" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ const arena = r.frame.allocator();
+ // 100 MiB, sparse: 5120x5120 RGBA, past the 64 MiB a screen holds.
+ const big = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-big.rgba", .{std.c.getpid()}, 0);
+ const fd = std.c.open(big, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o600));
+ if (fd < 0) return error.OpenFailed;
+ _ = ftruncate(fd, 5120 * 5120 * 4);
+ _ = std.c.close(fd);
+ defer _ = std.c.unlink(big);
+ r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=f,i=94,f=32,s=5120,v=5120;{s}\x1b\\", .{try b64(arena, big)}));
+ const got = try r.take(0);
+ try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=94;E"));
+ try std.testing.expect(!r.hasImage(0, 94));
+}
+
+// ---- Fuzz ----
+//
+// Seeded random kitty traffic, the way a confused or hostile program sends
+// it: commands with any keys and values, payloads valid and broken, CAN and
+// SUB mid-command, placeholders with any diacritics, cursor moves, ED 2/3,
+// the alternate screen, window and cell-size resizes and frames between,
+// split into reads anywhere. Each seed checks that pardes neither crashes
+// nor leaks (the testing allocator) and that every answer parses.
+//
+// PARDES_KITTY_FUZZ=<seeds> more seeds (default 24)
+// PARDES_KITTY_FUZZ_SEED=<seed> one seed, printing each step
+// PARDES_KITTY_FUZZ_STEPS=<n> steps per seed (default 400)
+//
+// A crash prints `seed S step N`: rerun that seed with fewer steps to
+// shrink it. A bad answer shrinks itself to the shortest failing prefix.
+
+fn envNumber(name: [*:0]const u8, default: u64) u64 {
+ const v = std.c.getenv(name) orelse return default;
+ return std.fmt.parseInt(u64, std.mem.span(v), 10) catch default;
+}
+
+const fuzz_keys = "aiIpfsvxywhcrXYzCUPQHVmoqtSOd";
+const fuzz_actions = "tTpdqfac";
+const fuzz_deletes = "aAiInNcCpPqQxXyYzZrRfF";
+
+fn fuzzValue(rng: std.Random, out: *std.ArrayList(u8), arena: std.mem.Allocator) !void {
+ switch (rng.uintLessThan(u8, 10)) {
+ 0 => try out.appendSlice(arena, "0"),
+ 1 => try out.print(arena, "{d}", .{rng.int(u32)}),
+ 2 => try out.print(arena, "-{d}", .{rng.uintLessThan(u32, 1 << 31)}),
+ 3 => try out.appendSlice(arena, "4294967295"),
+ 4 => try out.appendSlice(arena, "99999999999999999999"),
+ 5 => try out.appendSlice(arena, "x"),
+ else => try out.print(arena, "{d}", .{rng.uintLessThan(u32, 12)}),
+ }
+}
+
+/// A command that loads, or places what is loaded, with any geometry: it
+/// gets past the parser to the storage and the drawing.
+fn fuzzPlacement(rng: std.Random, arena: std.mem.Allocator) ![]const u8 {
+ var out: std.ArrayList(u8) = .empty;
+ const id = 1 + rng.uintLessThan(u32, 4);
+ switch (rng.uintLessThan(u8, 3)) {
+ 0 => try out.print(arena, "\x1b_Ga=T,f=24,s=4,v=2,i={d},q=2", .{id}),
+ 1 => try out.print(arena, "\x1b_Ga=p,i={d},q=2", .{id}),
+ else => try out.print(arena, "\x1b_Ga=T,f=100,i={d},q=2", .{id}),
+ }
+ const keys = "crxywhXYzCUpPQHV";
+ for (0..rng.uintLessThan(usize, 6)) |_| {
+ try out.print(arena, ",{c}=", .{keys[rng.uintLessThan(usize, keys.len)]});
+ try fuzzValue(rng, &out, arena);
+ }
+ try out.append(arena, ';');
+ if (std.mem.startsWith(u8, out.items, "\x1b_Ga=T,f=24")) try out.appendSlice(arena, rgb_b64);
+ if (std.mem.startsWith(u8, out.items, "\x1b_Ga=T,f=100")) try out.appendSlice(arena, png_b64);
+ try out.appendSlice(arena, "\x1b\\");
+ return out.items;
+}
+
+fn fuzzCommand(rng: std.Random, arena: std.mem.Allocator) ![]const u8 {
+ if (rng.boolean()) return fuzzPlacement(rng, arena);
+ var out: std.ArrayList(u8) = .empty;
+ try out.appendSlice(arena, "\x1b_G");
+ const action = fuzz_actions[rng.uintLessThan(usize, fuzz_actions.len)];
+ try out.print(arena, "a={c}", .{action});
+ if (action == 'd') try out.print(arena, ",d={c}", .{fuzz_deletes[rng.uintLessThan(usize, fuzz_deletes.len)]});
+ for (0..rng.uintLessThan(usize, 7)) |_| {
+ const key = fuzz_keys[rng.uintLessThan(usize, fuzz_keys.len)];
+ try out.print(arena, ",{c}=", .{key});
+ switch (key) {
+ 'f' => try out.appendSlice(arena, ([_][]const u8{ "24", "32", "100", "7" })[rng.uintLessThan(usize, 4)]),
+ 't' => try out.appendSlice(arena, ([_][]const u8{ "d", "f", "t", "s", "q" })[rng.uintLessThan(usize, 5)]),
+ 'o' => try out.appendSlice(arena, if (rng.boolean()) "z" else "y"),
+ else => try fuzzValue(rng, &out, arena),
+ }
+ }
+ // Mostly the small ids the rest reuse, so commands meet each other.
+ if (rng.uintLessThan(u8, 4) != 0) try out.print(arena, ",i={d}", .{1 + rng.uintLessThan(u32, 4)});
+ if (rng.boolean()) try out.print(arena, ",s={d},v={d}", .{ rng.uintLessThan(u32, 6), rng.uintLessThan(u32, 6) });
+ try out.append(arena, ';');
+ switch (rng.uintLessThan(u8, 8)) {
+ 0 => try out.appendSlice(arena, rgb_b64),
+ 1 => try out.appendSlice(arena, rgba_b64),
+ 2 => try out.appendSlice(arena, png_b64),
+ 3 => try out.appendSlice(arena, rgb_zlib_b64),
+ 4 => {}, // nothing
+ 5 => {
+ // base64, broken: random characters, wrong padding.
+ for (0..rng.uintLessThan(usize, 40)) |_| try out.append(arena, "AB/+=x!Z09"[rng.uintLessThan(usize, 10)]);
+ },
+ 6 => try out.appendSlice(arena, png_b64[0..rng.uintLessThan(usize, png_b64.len)]),
+ else => try out.appendSlice(arena, "AAAA"),
+ }
+ switch (rng.uintLessThan(u8, 12)) {
+ 0 => try out.append(arena, 0x18), // CAN
+ 1 => try out.append(arena, 0x1a), // SUB
+ 2 => try out.appendSlice(arena, "\x1b[m"), // ESC aborting it
+ else => try out.appendSlice(arena, "\x1b\\"),
+ }
+ return out.items;
+}
+
+fn fuzzOutput(rng: std.Random, arena: std.mem.Allocator) ![]const u8 {
+ return switch (rng.uintLessThan(u8, 9)) {
+ 0 => try std.fmt.allocPrint(arena, "\x1b[{d};{d}H", .{ 1 + rng.uintLessThan(u32, 50), 1 + rng.uintLessThan(u32, 150) }),
+ 1 => "line\r\n",
+ 2 => "\x1b[H\x1b[2J\x1b[3J",
+ 3 => if (rng.boolean()) "\x1b[?1049h" else "\x1b[?1049l",
+ 4 => blk: {
+ // Placeholders: an image id in the colour (24-bit or 256), any
+ // diacritics, up to three per cell.
+ var out: std.ArrayList(u8) = .empty;
+ if (rng.boolean())
+ try out.print(arena, "\x1b[38;2;{d};{d};{d}m", .{ rng.int(u8), rng.int(u8), rng.uintLessThan(u8, 5) })
+ else
+ try out.print(arena, "\x1b[38;5;{d}m", .{rng.uintLessThan(u8, 5)});
+ if (rng.boolean()) try out.print(arena, "\x1b[58;5;{d}m", .{rng.uintLessThan(u8, 4)});
+ for (0..1 + rng.uintLessThan(usize, 6)) |_| {
+ try out.appendSlice(arena, "\u{10EEEE}");
+ const marks = [_][]const u8{ "\u{0305}", "\u{030D}", "\u{030E}", "\u{0310}", "\u{0312}", "\u{033D}", "\u{0346}", "\u{1D242}" };
+ for (0..rng.uintLessThan(usize, 4)) |_| try out.appendSlice(arena, marks[rng.uintLessThan(usize, marks.len)]);
+ }
+ try out.appendSlice(arena, "\x1b[39;59m");
+ break :blk out.items;
+ },
+ 5 => "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
+ 6 => "\x1b[2;8r\x1b[S\x1b[T\x1b[r",
+ 7 => "\x1b[3L\x1b[2M\x1b[4@\x1b[2P",
+ else => "text",
+ };
+}
+
+/// Every answer whole: kitty's `ESC _ G ... ESC \`, or a CSI.
+fn answersParse(got: []const u8) bool {
+ var rest = got;
+ while (rest.len > 0) {
+ if (std.mem.startsWith(u8, rest, "\x1b_G")) {
+ const end = std.mem.indexOf(u8, rest, "\x1b\\") orelse return false;
+ if (std.mem.indexOfScalar(u8, rest[3..end], 0x1b) != null) return false;
+ rest = rest[end + 2 ..];
+ } else if (std.mem.startsWith(u8, rest, "\x1b[")) {
+ var i: usize = 2;
+ while (i < rest.len and !(rest[i] >= 0x40 and rest[i] <= 0x7e)) i += 1;
+ if (i == rest.len) return false;
+ rest = rest[i + 1 ..];
+ } else return false;
+ }
+ return true;
+}
+
+/// One seed's run, `steps` long; false on a bad answer.
+fn fuzzRun(seed: u64, steps: usize, trace: bool) !bool {
+ var prng: std.Random.DefaultPrng = .init(seed);
+ const rng = prng.random();
+ var r = try Rig.init(1);
+ defer r.deinit();
+ var arena_state: std.heap.ArenaAllocator = .init(gpa);
+ defer arena_state.deinit();
+ for (0..steps) |step| {
+ _ = arena_state.reset(.retain_capacity);
+ const arena = arena_state.allocator();
+ if (trace) std.debug.print("seed {d} step {d}\n", .{ seed, step });
+ switch (rng.uintLessThan(u8, 20)) {
+ 0 => {
+ const cols = 20 + rng.uintLessThan(u16, 140);
+ const rows = 6 + rng.uintLessThan(u16, 50);
+ r.p.update(.{ .resize = .{ .cols = cols, .rows = rows, .cell_pixels = .{ .w = 1 + rng.uintLessThan(u16, 30), .h = 1 + rng.uintLessThan(u16, 60) } } });
+ r.drain();
+ },
+ 1 => terminal.resizeGrid(r.pane(0), gpa, 1 + rng.uintLessThan(u16, 120), 1 + rng.uintLessThan(u16, 40)),
+ 2, 3 => {
+ const drawn = try r.places();
+ if (trace) std.debug.print(" {d} places, {d} placements, {d} images\n", .{ drawn.len, r.placementCount(0), r.storage(0).images.count() });
+ },
+ 4, 5, 6, 7 => r.feedSplit(0, try fuzzOutput(rng, arena), 1 + rng.uintLessThan(usize, 64)),
+ else => {
+ var batch: std.ArrayList(u8) = .empty;
+ for (0..1 + rng.uintLessThan(usize, 4)) |_| try batch.appendSlice(arena, try fuzzCommand(rng, arena));
+ r.feedSplit(0, batch.items, 1 + rng.uintLessThan(usize, 200));
+ },
+ }
+ const got = try r.take(0);
+ if (!answersParse(got)) {
+ if (trace) std.debug.print("seed {d} step {d}: unparsable answer {f}\n", .{ seed, step, std.ascii.hexEscape(got, .lower) });
+ return false;
+ }
+ }
+ _ = try r.places();
+ return true;
+}
+
+test "kitty: fuzzed traffic neither crashes nor leaks, and every answer parses" {
+ const steps: usize = @intCast(envNumber("PARDES_KITTY_FUZZ_STEPS", 400));
+ if (std.c.getenv("PARDES_KITTY_FUZZ_SEED")) |one| {
+ const seed = try std.fmt.parseInt(u64, std.mem.span(one), 10);
+ try std.testing.expect(try fuzzRun(seed, steps, true));
+ return;
+ }
+ const seeds = envNumber("PARDES_KITTY_FUZZ", 24);
+ for (0..seeds) |seed| {
+ if (try fuzzRun(seed, steps, false)) continue;
+ // Shrink to the shortest failing prefix.
+ var lo: usize = 1;
+ var hi: usize = steps;
+ while (lo < hi) {
+ const mid = lo + (hi - lo) / 2;
+ if (try fuzzRun(seed, mid, false)) lo = mid + 1 else hi = mid;
+ }
+ std.debug.print("kitty fuzz: seed {d} fails in {d} steps; PARDES_KITTY_FUZZ_SEED={d} PARDES_KITTY_FUZZ_STEPS={d} traces it\n", .{ seed, lo, seed, lo });
+ return error.FuzzFailed;
+ }
+ if (seeds != 24) std.debug.print("kitty fuzz: {d} seeds of {d} steps ok\n", .{ seeds, steps });
+}
+
+// ---- An image's pane, as it lives ----
+
+test "kitty: scrolled back by pardes, an image shows on its row; scrolled forward, it goes" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ const pane = r.pane(0);
+ r.feed(0, "\x1b[1;1Hmarker" ++ apc("a=T,i=20,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);
+ try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(20)).len);
+ // Back to the top of the history: the marker row is the body's first.
+ terminal.scrollGrid(pane, -1000);
+ const o = r.origin(0);
+ const drawn = try r.placesOf(20);
+ try std.testing.expectEqual(@as(usize, 1), drawn.len);
+ try std.testing.expectEqual(o.y, drawn[0].y);
+ try std.testing.expectEqual(o.x + 6, drawn[0].x);
+ terminal.followOutput(pane);
+ try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(20)).len);
+}
+
+test "kitty: an edited copy taller than the rows it covers pushes the images below it down" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ const pane = r.pane(0);
+ r.feed(0, "\x1b[1;1Hone\r\ntwo\r\n\x1b[6;1H" ++ apc("a=T,i=21,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 + 5, (try r.placesOf(21))[0].y);
+ // Row 1 ("two") edited into three lines.
+ pane.body.mode = .normal;
+ pane.ovl = .{ .row = 1, .rows = 1, .text = try gpa.dupe(u8, "two\nthree\nfour") };
+ const drawn = try r.placesOf(21);
+ try std.testing.expectEqual(@as(usize, 1), drawn.len);
+ try std.testing.expectEqual(o.y + 7, drawn[0].y);
+}
+
+test "kitty: an image wider than its pane is cut at the pane's edge, never drawn over the next one" {
+ var r = try Rig.init(3);
+ defer r.deinit();
+ // The classic boot: two columns. Pane 0 is in the left one.
+ const rect = r.p.rects[0];
+ const o = r.origin(0);
+ const right = rect.x + rect.w;
+ // 2x1 cells at its last-but-one column: one cell is the pane's.
+ const at = try std.fmt.allocPrint(r.frame.allocator(), "\x1b[1;{d}H", .{r.pane(0).cols});
+ r.feed(0, at);
+ r.feed(0, apc("a=T,i=22,f=24,s=4,v=2,c=4,r=1,q=2", rgb_b64));
+ const drawn = try r.placesOf(22);
+ try std.testing.expectEqual(@as(usize, 1), drawn.len);
+ try std.testing.expect(drawn[0].x + drawn[0].w <= o.x + r.pane(0).cols);
+ try std.testing.expect(drawn[0].x + drawn[0].w <= right);
+ // And the pixels it takes are only that cell's.
+ const g = drawn[0].native.geometry.?;
+ try std.testing.expect(g.dst.w <= @as(u32, drawn[0].w) * 10);
+}
+
+test "kitty: a collapsed pane draws no image" {
+ var r = try Rig.init(3);
+ defer r.deinit();
+ r.feed(1, "\x1b[1;1H" ++ apc("a=T,i=23,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
+ try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(23)).len);
+ try std.testing.expect(r.p.executeBuiltinLine(1, "Collapse"));
+ try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(23)).len);
+ try std.testing.expect(r.p.executeBuiltinLine(1, "Collapse"));
+ try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(23)).len);
+}
+
+test "kitty: a new cell size (font zoom) redraws an image at the same cells, scaled to the new size" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ r.feed(0, "\x1b[2;3H" ++ apc("a=T,i=24,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
+ var drawn = try r.placesOf(24);
+ try std.testing.expectEqual(@as(u32, 20), drawn[0].native.geometry.?.dst.w);
+ r.p.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 15, .h = 30 } } });
+ r.drain();
+ drawn = try r.placesOf(24);
+ const o = r.origin(0);
+ try std.testing.expectEqual(@as(usize, 1), 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(@as(u32, 30), drawn[0].native.geometry.?.dst.w);
+ try std.testing.expectEqual(@as(u32, 30), drawn[0].native.geometry.?.dst.h);
+}
+
+test "kitty: a dumped and restored terminal keeps its images" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ r.feed(0, "\x1b[1;1Hpicture" ++ apc("a=T,i=25,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
+ try pardes.dump.dumpState(r.p);
+ const restored = try pardes.dump.restore(r.p, r.p.dump_out.?, "/tmp/pardes-kitty.dump.zon");
+ defer restored.deinit();
+ const pane = restored.panes[0].?;
+ const kept = pane.terminal != null and pane.terminal.?.vt.screens.active.kitty_images.placements.count() > 0;
+ try knownGap("a terminal's kitty images do not survive a dump (Dump/Load, Handover, a closed pane reopened from the Store): dumpPane writes the screen as VT text (ScreenFormatter), which has no images; ghostty's snapshot format carries them but is unstable (v1)", kept);
+}
+
+// ---- Real clients' traffic ----
+//
+// What kitten icat 0.49.2 and chafa 1.18.3 wrote to a pardes pane, recorded
+// with script(1) between them and the pane (`PARDES_KITTY_EXPLORE` in
+// test/kitty_harness.zig), a 64x64 PNG on a 118-column pane with 8x16 cells:
+// their probes, then the image streamed. Replayed in 4 KiB reads, each must
+// answer whole and draw its first row where it drew live.
+
+const Recorded = struct {
+ name: []const u8,
+ bytes: []const u8,
+ /// The pane cell its top-left landed on, live; null: draws nothing.
+ at: ?[2]u16,
+};
+
+const recorded = [_]Recorded{
+ .{ .name = "icat --align=left", .bytes = @embedFile("kitty-fixtures/icat-left.vt"), .at = .{ 0, 0 } },
+ .{ .name = "icat --align=center", .bytes = @embedFile("kitty-fixtures/icat-center.vt"), .at = .{ 55, 0 } },
+ .{ .name = "icat --align=right", .bytes = @embedFile("kitty-fixtures/icat-right.vt"), .at = .{ 110, 0 } },
+ .{ .name = "icat --place 10x5@20x3", .bytes = @embedFile("kitty-fixtures/icat-place.vt"), .at = .{ 21, 3 } },
+ .{ .name = "icat --unicode-placeholder", .bytes = @embedFile("kitty-fixtures/icat-placeholder.vt"), .at = .{ 0, 0 } },
+ .{ .name = "chafa -f kitty -s 8x4", .bytes = @embedFile("kitty-fixtures/chafa.vt"), .at = .{ 0, 0 } },
+ .{ .name = "icat --clear", .bytes = @embedFile("kitty-fixtures/icat-clear.vt"), .at = null },
+};
+
+test "kitty: recorded kitten icat and chafa traffic replays: answers whole, images where they were drawn" {
+ for (recorded) |rec| {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ r.p.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } });
+ r.drain();
+ _ = try r.take(0);
+ r.feedSplit(0, rec.bytes, 4096);
+ const got = try r.take(0);
+ std.testing.expect(answersParse(got)) catch |err| {
+ std.debug.print("{s}: unparsable answer {f}\n", .{ rec.name, std.ascii.hexEscape(got, .lower) });
+ return err;
+ };
+ const drawn = try r.places();
+ const want = rec.at orelse {
+ try std.testing.expectEqual(@as(usize, 0), drawn.len);
+ continue;
+ };
+ const o = r.origin(0);
+ var top: ?pardes.ImagePlace = null;
+ for (drawn) |maybe| if (maybe) |place| {
+ if (top == null or place.y < top.?.y or (place.y == top.?.y and place.x < top.?.x)) top = place;
+ };
+ const first = top orelse {
+ std.debug.print("{s}: nothing drawn\n", .{rec.name});
+ return error.NothingDrawn;
+ };
+ std.testing.expectEqual([2]u16{ o.x + want[0], o.y + want[1] }, [2]u16{ first.x, first.y }) catch |err| {
+ std.debug.print("{s}: drawn at {d},{d}, live at {d},{d}\n", .{ rec.name, first.x - o.x, first.y - o.y, want[0], want[1] });
+ return err;
+ };
+ }
+}
+
+test "kitty: under a shell that draws no pixels, a 64x64 image over 8x4 cells is glyph art in every cell" {
+ var r = try Rig.init(1);
+ defer r.deinit();
+ r.p.native_images = false;
+ r.p.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } });
+ r.drain();
+ // Not the frame's arena: each frame resets that.
+ var data: std.heap.ArenaAllocator = .init(gpa);
+ defer data.deinit();
+ const arena = data.allocator();
+ const px = try arena.alloc(u8, 64 * 64 * 3);
+ for (0..64 * 64) |i| px[i * 3 ..][0..3].* = .{ 13, 77, 231 };
+ const enc = try b64(arena, px);
+ for ([_]bool{ false, true }) |helix| {
+ if (helix) try std.testing.expect(r.p.executeBuiltinLine(0, "Theme helix"));
+ // As test/kitty_client.zig's `place` sends it: after text, in
+ // 1 KiB chunks.
+ var cmds: std.ArrayList(u8) = .empty;
+ try cmds.appendSlice(arena, "\x1b[H\x1b[2J\r\nANCHOR>");
+ var at: usize = 0;
+ while (at < enc.len) : (at += 1024) {
+ const end = @min(enc.len, at + 1024);
+ const more: u8 = if (end < enc.len) '1' else '0';
+ if (at == 0)
+ try cmds.print(arena, "\x1b_Ga=T,i=42,f=24,s=64,v=64,c=8,r=4,m={c};{s}\x1b\\", .{ more, enc[at..end] })
+ else
+ try cmds.print(arena, "\x1b_Gm={c};{s}\x1b\\", .{ more, enc[at..end] });
+ }
+ try cmds.appendSlice(arena, "\r\n");
+ r.feed(0, cmds.items);
+ _ = try r.places();
+ const s = &r.p.surface;
+ const o = r.origin(0);
+ var painted: usize = 0;
+ for (0..4) |dy| for (0..8) |dx| {
+ const cell = s.at(o.x + 7 + @as(u16, @intCast(dx)), o.y + 1 + @as(u16, @intCast(dy)));
+ if (cell.style.bg == .rgb and !cell.default) painted += 1;
+ };
+ std.testing.expectEqual(@as(usize, 32), painted) catch |err| {
+ std.debug.print("helix theme {}: {d} cells painted\n", .{ helix, painted });
+ return err;
+ };
+ }
+}