summaryrefslogtreecommitdiff
path: root/test/terminal.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 03:44:57 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commita22b579ad2df8d1811f0e194fa1bbc06e2282cf8 (patch)
tree9dcaaa6d17c6c67048b58456dcd9dbdb74b9fc9a /test/terminal.zig
parenta3509e4df5efc94b0deee3b06dd72f85b0d96647 (diff)
downloadpardes-a22b579ad2df8d1811f0e194fa1bbc06e2282cf8.tar.gz
pardes-a22b579ad2df8d1811f0e194fa1bbc06e2282cf8.zip
term: the terminal a module of its own (docs/next-terminal.md, Phase 1): src/term/term.zig roots it, importing std, ghostty-vt, wuffs, zstbi and plain, never the core, and gives the core one table, `ops` (plain.term.Ops: about 60 entries, the records they take and give and the opaque handles State, Encoder, Track and Replica, in src/plain/term.zig), its own functions put in it through a cast refused at compile time unless each parameter and result matches the table's but for the handles and every error is one the table names; src/Term.zig, the core's side, takes `ops` from the term module when the build's term_options say the core has one (every core module but core-test's), null otherwise, and Term.State is a handle with the walk's hooks, so a dump keeps a terminal as it did (its Parts by name through walk.save, then ghostty's snapshot) and the digest is the emulator's; echo.zig comes back to the core (src/echo.zig: predicted echo is the replica's presentation, its five reads of the emulator through Term.grid, modes, prompt and Term.echoCell); screen_state's Peer is a plain record both sides name (its noteSent a function of screen_state's), its Encoder, Track and Replica handles made and freed through the table (replica.Screens makes its encoder at the first encode); a prompt's cut is told in columns and measured in its row's text by the core (Term.promptPrefix, File.rawAtDisplay); TerminalImages' decode bound moves from memory.limits to the decoder it bounds; build.zig: core_lean, the core module without the terminal, is core-test's, and wireCore no longer gives any core module ghostty-vt, wuffs or zstbi (the term module has them), so core-test's compile names none of ghostty, wuffs, zstbi, simdutf, highway or -lc++ (from --verbose); term-test runs the module's own tests (the pager's, screen_state's, the luminance table's); the tests of a terminal through a core move as they were to test/terminal.zig, in pane-test, which imports both (`of` reads the emulator behind a handle; the dump round trip frees through State.dumpFree), and tests elsewhere that read the emulator do it through Term.emulatorOf, a test in core-test skipping first; core-test skips a test whose terminal Term.open refuses; Authority.init releases its tape when the core it boots fails (it leaked); tests: core-test (no terminal) 409 of 941, 532 skipped, shell-test (the same tests with the terminal) 984 of 984, pane-test 180 of 181 (1 skipped, as before), term-test 15 of 15, kitty-test 45 of 45, replicas checked/wrong 0, hxdiff 658 cases 0 mismatches, behaviour-test 268 of 272 (the base's four addon ABI tests), lib-test
Diffstat (limited to 'test/terminal.zig')
-rw-r--r--test/terminal.zig983
1 files changed, 983 insertions, 0 deletions
diff --git a/test/terminal.zig b/test/terminal.zig
new file mode 100644
index 00000000..cfc58e52
--- /dev/null
+++ b/test/terminal.zig
@@ -0,0 +1,983 @@
+//! The terminal through the core (docs/next-terminal.md, Phase 1): what
+//! were src/term/terminal.zig's and screen_state.zig's tests of a terminal
+//! pane, moved as they were. They boot a core and read the emulator behind
+//! it, so they need both modules, which only a suite outside both has:
+//! pane-test's (test/panes.zig). The emulator's own tests stay in src/term/.
+const std = @import("std");
+const pardes = @import("pardes");
+const plain = @import("plain");
+const term = @import("term");
+const ghostty_vt = @import("ghostty-vt");
+const emu = term.terminal;
+const screen_state = term.screen_state;
+const Encoder = screen_state.Encoder;
+const Track = screen_state.Track;
+const Peer = screen_state.Peer;
+const Replica = screen_state.Replica;
+const encode = screen_state.encode;
+const Surface = pardes.Surface;
+const Pane = pardes.Pane;
+const FilterPalette = Term.FilterPalette;
+const Pardes = pardes.Pardes;
+const panes = pardes.panes;
+const config = pardes.config;
+const tagline = pardes.tagline;
+const ansi = pardes.ansi;
+const Term = pardes.Term;
+const State = Term.State;
+const GColor = ghostty_vt.color;
+const images_enabled = emu.images_enabled;
+const close = Term.close;
+const grid = Term.grid;
+const modes = Term.modes;
+const prompt = Term.prompt;
+const scroll = Term.scroll;
+const scrollback = Term.scrollback;
+const commandOutput = Term.commandOutput;
+const petscii = Term.petscii;
+const filterOf = emu.filterOf;
+const filterPalette = emu.filterPalette;
+const keyedRgb = emu.keyedRgb;
+const paletteRgb = emu.paletteRgb;
+const legible = emu.legible;
+const nearestKey = emu.nearestKey;
+const asGhostRgb = emu.asGhostRgb;
+const asPardesColor = emu.asPardesColor;
+const min_contrast = emu.min_contrast;
+
+/// The module's own state behind a pane's handle.
+fn of(s: *Term.State) *emu.State {
+ return @ptrCast(@alignCast(s.impl));
+}
+
+/// Every byte the core wrote to each pane's pty since the last call, `\n`
+/// between panes' shares: "0:<bytes>\n1:<bytes>\n" for panes that got any.
+fn ptyWritesByPane(p: *Pardes, out: *std.ArrayList(u8)) ![]const u8 {
+ out.clearRetainingCapacity();
+ var per: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty);
+ defer for (&per) |*b| b.deinit(p.gpa);
+ while (p.nextEffect()) |effect| {
+ if (effect == .write) try per[effect.write.pane].appendSlice(p.gpa, effect.write.bytes.slice());
+ }
+ for (per, 0..) |b, id| if (b.items.len > 0) try out.print(p.gpa, "{d}:{s}\n", .{ id, b.items });
+ return out.items;
+}
+
+/// `a=T` of a 4x2 RGB image, `i=7`, red on the left half, blue on the
+/// right, with the rest of the control data `extra` (`c=2,r=1` places it
+/// over two cells).
+inline fn kittyTransmit(comptime extra: []const u8) []const u8 {
+ return comptime blk: {
+ const row = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 };
+ const pixels = row ++ row;
+ var buf: [std.base64.standard.Encoder.calcSize(pixels.len)]u8 = undefined;
+ const b64 = std.base64.standard.Encoder.encode(&buf, &pixels)[0..buf.len].*;
+ break :blk "\x1b_Ga=T,f=24,s=4,v=2,i=7," ++ extra ++ ";" ++ b64 ++ "\x1b\\";
+ };
+}
+
+fn imagePlaces(s: *const Surface) []const plain.Placement {
+ return s.placements.items;
+}
+
+/// `n` line breaks: enough of them push the screen's rows into history.
+fn lineBreaks(comptime n: usize) [2 * n]u8 {
+ var out: [2 * n]u8 = undefined;
+ for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*;
+ return out;
+}
+
+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 {
+ const pane = if (terminal) try panes.createTerminal(gpa, 40, 12) else try panes.createDoc(gpa, 40, 12);
+ defer gpa.destroy(pane);
+ defer if (pane.terminal) |state| close(state, gpa);
+ try std.testing.expectEqual(terminal, pane.terminal != null);
+ }
+ };
+ try std.testing.expect(@sizeOf(Pane) < 128 * 1024);
+ try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false});
+ try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true});
+}
+
+test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" {
+ // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field
+ // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30).
+ const Filling = struct {
+ child: std.mem.Allocator,
+ fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ const ptr = self.child.rawAlloc(len, a, ra) orelse return null;
+ @memset(ptr[0..len], 0xAA);
+ return ptr;
+ }
+ fn grow(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ return self.child.rawResize(buf, a, n, ra);
+ }
+ fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ return self.child.rawRemap(buf, a, n, ra);
+ }
+ fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ self.child.rawFree(buf, a, ra);
+ }
+ const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = grow, .remap = remap, .free = free };
+ };
+ var filling: Filling = .{ .child = std.testing.allocator };
+ const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable };
+ const pane = try panes.createTerminal(gpa, 40, 12);
+ defer gpa.destroy(pane);
+ defer if (pane.terminal) |state| close(state, gpa);
+ try std.testing.expect(of(pane.terminal.?).resize_to == null);
+}
+
+test "document construction allocates only the pane and has inert terminal defaults" {
+ var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 });
+ const allocator = failing.allocator();
+ const pane = try panes.createDoc(allocator, 40, 12);
+ defer allocator.destroy(pane);
+ defer if (pane.terminal) |state| close(state, allocator);
+ try std.testing.expect(pane.terminal == null);
+ try std.testing.expectEqual(@as(usize, 1), failing.alloc_index);
+ try std.testing.expectEqual(@as(usize, 0), failing.resize_index);
+ try std.testing.expect(!failing.has_induced_failure);
+ try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes);
+ try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal));
+ try std.testing.expectEqual(Term.Modes{}, modes(pane.terminal));
+ try std.testing.expectEqual(Term.Prompt{}, prompt(pane.terminal));
+ pane.scrollBy(100);
+ pane.followOutput();
+ pane.resizeGrid(80, 24);
+ try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal));
+ try std.testing.expectEqualStrings("", try scrollback(pane.terminal, allocator));
+ try std.testing.expect(!failing.has_induced_failure);
+}
+
+test "terminal state keeps parser fragments and sends emulator replies through its owner" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ const state = of(pane.terminal.?);
+ try std.testing.expect(state.stream.handler.inner.terminal == &state.vt);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } });
+ while (p.nextEffect()) |effect| {
+ if (effect == .write) return error.PrematureTerminalReply;
+ }
+ p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } });
+ var answers: usize = 0;
+ while (p.nextEffect()) |effect| {
+ if (effect != .write) continue;
+ try std.testing.expectEqual(@as(u8, 0), effect.write.pane);
+ try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice());
+ answers += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 1), answers);
+ try std.testing.expectEqual(@as(u16, 0), state.reply_len);
+}
+
+test "a terminal's dump restores the cells it drew, its history and where its view was" {
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ pane.feedOutput(p, "\x1b[31mred\x1b[0m\r\ncafé\r\n");
+ for (0..30) |i| {
+ var line: [16]u8 = undefined;
+ pane.feedOutput(p, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable);
+ }
+ scroll(pane.terminal.?, -5);
+ const bytes = try pardes.walk.save(State, gpa, pane.terminal.?);
+ defer gpa.free(bytes);
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const state = try gpa.create(State);
+ defer gpa.destroy(state);
+ state.* = try pardes.walk.load(State, gpa, bytes, null);
+ defer State.dumpFree(state, gpa);
+ try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state));
+ try std.testing.expectEqual(of(pane.terminal.?).vt.screens.active.pages.scrollbar(), of(state).vt.screens.active.pages.scrollbar());
+}
+
+test "a restored command pane comes back finished, its command not run again" {
+ if (comptime pardes.isolated) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const cmd = p.freeSlot().?;
+ _ = try panes.newCommand(p, cmd, "/tmp", "make test");
+ p.panes[cmd].?.feedOutput(p, "ok\r\n");
+ p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } });
+ try pardes.dump.dumpState(p);
+ const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?);
+ defer restored.deinit();
+ var spawns: usize = 0;
+ while (restored.nextEffect()) |effect| switch (effect) {
+ .spawn => spawns += 1,
+ else => {},
+ };
+ try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command
+ const again = for (restored.panes) |slot| {
+ if (slot) |pane| if (pane.command != null) break pane;
+ } else return error.CommandPaneLost;
+ try std.testing.expectEqualStrings("make test", again.command.?);
+ try std.testing.expect(again.command_done);
+ try std.testing.expectEqual(@as(?u8, 2), again.command_status);
+ const text = try scrollback(again.terminal, gpa);
+ defer gpa.free(text);
+ try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null);
+}
+
+test "a restored terminal keeps its history above a marker and gets a shell where it was" {
+ if (comptime pardes.isolated) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ pane.feedOutput(p, "old output\r\n$ ls\r\n");
+ try pane.setOwnedCwd("/tmp");
+ pane.shell = try gpa.dupe(u8, "bash"); // `Term bash`: it comes back as bash
+ try pardes.dump.dumpState(p);
+ const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?);
+ defer restored.deinit();
+ var spawned = false;
+ while (restored.nextEffect()) |effect| switch (effect) {
+ .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"),
+ else => {},
+ };
+ try std.testing.expect(spawned);
+ const again = restored.panes[0].?;
+ try std.testing.expectEqualStrings("bash", again.shell.?);
+ try std.testing.expect(again.command == null);
+ try std.testing.expectEqual(.spawn, again.pending_command.wait);
+ const text = try scrollback(again.terminal, gpa);
+ defer gpa.free(text);
+ const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost;
+ const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker;
+ try std.testing.expect(old_at < mark_at);
+}
+
+test "a position that cannot follow the output for want of memory is said on the message row, and logged" {
+ var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
+ const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ pane.feedOutput(p, "one\r\ntwo\r\n");
+ // More positions than the emulator's pins have room for: following them
+ // through the output needs memory, and there is none.
+ try std.testing.expect(pane.body.reserveSels());
+ for (pane.body.sels[0..8], 0..) |*range, i| range.* = .{ .row = @intCast(i), .col = 0, .arow = @intCast(i), .acol = 1 };
+ pane.body.nsel = 8;
+ failing.fail_index = failing.alloc_index;
+ pane.feedOutput(p, "three\r\n");
+ failing.fail_index = std.math.maxInt(usize);
+ try std.testing.expect(failing.has_induced_failure);
+ try std.testing.expectEqualStrings(panes.positions_lost, pane.msg[0..pane.msg_len]);
+ const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged;
+ try std.testing.expectEqualStrings(panes.positions_lost, logged.slice());
+}
+
+test "raw terminal output needs no position tracking allocations" {
+ var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
+ const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ pane.body.mode = .tty;
+ pane.feedOutput(p, "warm");
+ const allocations = failing.alloc_index;
+ failing.fail_index = allocations;
+ const pins = of(pane.terminal.?).vt.screens.active.pages.countTrackedPins();
+ pane.feedOutput(p, " output");
+ try std.testing.expectEqual(allocations, failing.alloc_index);
+ try std.testing.expect(!failing.has_induced_failure);
+ try std.testing.expectEqual(pins, of(pane.terminal.?).vt.screens.active.pages.countTrackedPins());
+}
+
+test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ try std.testing.expect(pane.terminal != null);
+ _ = try pardes.edit.shellRows(p, pane);
+ // A pane's teardown drops its entry; the rows stay until the sweep.
+ p.shell_rows.dropPane(pane);
+ _ = try pardes.edit.shellRows(p, pane);
+}
+
+
+test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" {
+ const testing = std.testing;
+ // Raw index assertions require a theme that inherits the ANSI palette.
+ const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ pane.tag_expanded = false; // a one-row tag keeps this small screen's rows
+ p.sync();
+ try testing.expect(pane.tty_filter);
+ pane.tty_filter = false;
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++
+ "\x1b[38;5;196mB" ++
+ "\x1b[38;2;255;0;0mC" ++
+ "\x1b[0;48;5;25mD" ++
+ "\x1b[0;48;2;0;95;175mE" ++
+ "\x1b[0;1;2;3;4;5;7;8;9mF" ++
+ "\x1b[0;48;5;25m\x1b[K" ++
+ "\r\n\x1b[0;38;5;2m界" } });
+
+ var frame = std.heap.ArenaAllocator.init(testing.allocator);
+ defer frame.deinit();
+ const r = p.view().rects[0];
+ const tx = r.x + config.GUTTER;
+ const body_y = p.bodyTop(pane, r);
+
+ const raw = try p.render(frame.allocator());
+ try testing.expectEqual(plain.Color{ .index = 1 }, raw.at(tx, body_y).style.fg);
+ try testing.expectEqual(plain.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg);
+ try testing.expectEqual(plain.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg);
+
+ pane.tty_filter = true;
+ _ = frame.reset(.retain_capacity);
+ const filtered = try p.render(frame.allocator());
+ var expected_cache: FilterPalette = .{};
+ const expected = filterPalette(&expected_cache, &ansi.inkOf(p.theme()));
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[1])), filtered.at(tx, body_y).style.fg);
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), filtered.at(tx + 1, body_y).style.fg);
+ try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg);
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[25])), filtered.at(tx + 3, body_y).style.bg);
+ try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg);
+
+ const attrs = filtered.at(tx + 5, body_y).style;
+ try testing.expect(attrs.bold);
+ try testing.expect(attrs.dim);
+ try testing.expect(attrs.italic);
+ try testing.expect(attrs.blink);
+ try testing.expect(attrs.reverse);
+ try testing.expect(attrs.invisible);
+ try testing.expect(attrs.strikethrough);
+ try testing.expectEqual(.single, attrs.ul);
+
+ const erased = of(pane.terminal.?).vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?;
+ try testing.expectEqual(.bg_color_palette, erased.cell.content_tag);
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[25])), filtered.at(tx + 6, body_y).style.bg);
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[2])), filtered.at(tx, body_y + 1).style.fg);
+ try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style);
+ // A filtered terminal never delegates either colour to a backend palette,
+ // including cells which were empty/default before the pass.
+ for (0..r.w - config.GUTTER) |col| {
+ const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y);
+ try testing.expect(!cell.default);
+ switch (cell.style.fg) {
+ .rgb => {},
+ else => return error.FilteredForegroundWasNotRgb,
+ }
+ switch (cell.style.bg) {
+ .rgb => {},
+ else => return error.FilteredBackgroundWasNotRgb,
+ }
+ }
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } });
+ const osc_red = of(pane.terminal.?).vt.colorForXterm(.{ .palette = 1 }).?;
+ try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 }));
+ pane.tty_filter = false;
+ pane.tty_filter = true;
+ try testing.expect(osc_red.eql(of(pane.terminal.?).vt.colorForXterm(.{ .palette = 1 }).?));
+ _ = frame.reset(.retain_capacity);
+ const osc_palette = try p.render(frame.allocator());
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), osc_palette.at(tx, body_y).style.fg);
+
+ // Dynamic default foreground/background colours key every default cell,
+ // including the otherwise blank end of the row.
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++
+ "\x1b]11;#5f5f5f\x1b\\" } });
+ const dyn_fg = of(pane.terminal.?).vt.colorForXterm(.{ .dynamic = .foreground }).?;
+ const dyn_bg = of(pane.terminal.?).vt.colorForXterm(.{ .dynamic = .background }).?;
+ try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 }));
+ try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 }));
+ _ = frame.reset(.retain_capacity);
+ const dynamic = try p.render(frame.allocator());
+ const edge = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style;
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), edge.fg);
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[59])), edge.bg);
+
+ const explicit_before_reverse = dynamic.at(tx, body_y).style.fg;
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), explicit_before_reverse);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } });
+ _ = frame.reset(.retain_capacity);
+ const reversed = try p.render(frame.allocator());
+ const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style;
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[59])), reversed_blank.fg);
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), reversed_blank.bg);
+ const reversed_explicit = reversed.at(tx, body_y).style;
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), reversed_explicit.bg);
+ try testing.expectEqual(plain.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg);
+ try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg));
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } });
+ _ = frame.reset(.retain_capacity);
+ const unreversed = try p.render(frame.allocator());
+ const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style;
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), unreversed_blank.fg);
+ try testing.expectEqual(asPardesColor(asGhostRgb(expected[59])), unreversed_blank.bg);
+
+ // The cache is keyed by values, not a theme name. Replacing a custom
+ // theme in place immediately recolours already-rendered indexed cells.
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } });
+ var custom = p.theme().*;
+ custom.name = try p.gpa.dupe(u8, "same-name");
+ custom.palette = null;
+ custom.kw = .{ 1, 2, 3 };
+ p.custom_theme = custom;
+ _ = frame.reset(.retain_capacity);
+ const custom_first = try p.render(frame.allocator());
+ try testing.expectEqual(plain.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg);
+ if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 };
+ _ = frame.reset(.retain_capacity);
+ const custom_second = try p.render(frame.allocator());
+ try testing.expectEqual(plain.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg);
+}
+
+test "terminal Filter keeps extended keys dark-to-light on a light theme" {
+ const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true });
+ defer p.deinit();
+ try std.testing.expectEqualStrings("acme", p.theme().name);
+ var cache: FilterPalette = .{};
+ const palette = filterPalette(&cache, &ansi.inkOf(p.theme()));
+ try std.testing.expect(asGhostRgb(palette[16]).eql(asGhostRgb(p.theme().fg.?)));
+ try std.testing.expect(asGhostRgb(palette[231]).eql(asGhostRgb(p.theme().bg.?)));
+}
+
+test "terminal Filter preserves exact palette-null light theme default roles" {
+ const testing = std.testing;
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+
+ var light = p.theme().*;
+ light.name = try p.gpa.dupe(u8, "filter-light-defaults");
+ light.bg = .{ 0xf8, 0xf8, 0xf8 };
+ light.fg = .{ 0x38, 0x38, 0x38 };
+ light.palette = null;
+ p.custom_theme = light;
+
+ const pane = p.panes[0].?;
+ try testing.expectEqual(@as(?GColor.RGB, null), of(pane.terminal.?).vt.colorForXterm(.{ .dynamic = .foreground }));
+ try testing.expectEqual(@as(?GColor.RGB, null), of(pane.terminal.?).vt.colorForXterm(.{ .dynamic = .background }));
+ pane.tty_filter = true;
+
+ var frame = std.heap.ArenaAllocator.init(testing.allocator);
+ defer frame.deinit();
+ const r = p.view().rects[0];
+ const tx = r.x + config.GUTTER;
+ const body_y = p.bodyTop(pane, r);
+ const ordinary = try p.render(frame.allocator());
+ try testing.expectEqual(plain.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg);
+ try testing.expectEqual(plain.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg);
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } });
+ _ = frame.reset(.retain_capacity);
+ const reversed = try p.render(frame.allocator());
+ try testing.expectEqual(plain.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg);
+ try testing.expectEqual(plain.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg);
+}
+
+test "terminal Filter maps the default roles before it maps anything else" {
+ const testing = std.testing;
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ try testing.expect(pane.tty_filter);
+
+ // Native dark/light palettes plus legacy helix/dark/acme, including
+ // the null-page fallback that only the legacy dark theme exercises.
+ for (0..9) |t| {
+ p.settings.theme = @intCast(t);
+ const stage_one = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &of(pane.terminal.?).vt);
+ // `dark` declares no background of its own, which is exactly why the
+ // resolver reads the tag colours as the fallback rather than `.?`.
+ const theme = p.theme();
+ try testing.expect(asGhostRgb(stage_one.theme_bg).eql(asGhostRgb(theme.bg orelse theme.tag_bg)));
+ try testing.expect(asGhostRgb(stage_one.theme_fg).eql(asGhostRgb(theme.fg orelse theme.tag_fg)));
+ // With no OSC 11 in play the mapped page IS that anchor, and the
+ // fallback is the other one: a background never contrasts with itself.
+ try testing.expect(asGhostRgb(stage_one.default_bg).eql(asGhostRgb(stage_one.theme_bg)));
+ try testing.expect(asGhostRgb(stage_one.fallback_fg).eql(asGhostRgb(stage_one.theme_fg)));
+ }
+
+ p.settings.theme = 0;
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } });
+ var moved = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &of(pane.terminal.?).vt);
+ try testing.expect(!asGhostRgb(moved.default_bg).eql(asGhostRgb(moved.theme_bg)));
+ try testing.expect(asGhostRgb(moved.default_bg).eql(keyedRgb(&moved, .{ .r = 0x5f, .g = 0x5f, .b = 0x5f })));
+}
+
+test "terminal Filter refuses a foreground that would collapse onto the page" {
+ const testing = std.testing;
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ try testing.expect(pane.tty_filter);
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++
+ "\x1b[0;30mB" ++
+ "\x1b[0;31mR" } });
+
+ var frame = std.heap.ArenaAllocator.init(testing.allocator);
+ defer frame.deinit();
+ const r = p.view().rects[0];
+ const tx = r.x + config.GUTTER;
+ const body_y = p.bodyTop(pane, r);
+
+ for (0..9) |t| {
+ p.settings.theme = @intCast(t);
+ var fc = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &of(pane.terminal.?).vt);
+ const page = asPardesColor(asGhostRgb(fc.default_bg));
+ const rescued = asPardesColor(asGhostRgb(fc.fallback_fg));
+ _ = frame.reset(.retain_capacity);
+ const g = try p.render(frame.allocator());
+
+ // The colour each of the three would have been given with no floor.
+ const raw_white = keyedRgb(&fc, .{ .r = 255, .g = 255, .b = 255 });
+ const raw_black = paletteRgb(&fc, 0, GColor.default[0]);
+ const raw_red = paletteRgb(&fc, 1, GColor.default[1]);
+
+ for ([_]struct { at: u16, raw: GColor.RGB }{
+ .{ .at = 0, .raw = raw_white },
+ .{ .at = 1, .raw = raw_black },
+ .{ .at = 2, .raw = raw_red },
+ }) |case| {
+ const cell = g.at(tx + case.at, body_y).style;
+ try testing.expectEqual(page, cell.bg);
+ if (case.raw.contrast(asGhostRgb(fc.default_bg)) < min_contrast) {
+ // Refused: the projection's answer is not painted, the anchor is.
+ try testing.expectEqual(rescued, cell.fg);
+ try testing.expect(!std.meta.eql(cell.fg, cell.bg));
+ } else {
+ // Cleared the floor, so stage two leaves it exactly alone.
+ try testing.expectEqual(asPardesColor(case.raw), cell.fg);
+ }
+ // Either way a filtered cell delegates neither colour to a backend.
+ switch (cell.fg) {
+ .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(asGhostRgb(fc.default_bg)) >=
+ min_contrast),
+ else => return error.FilteredForegroundWasNotRgb,
+ }
+ }
+
+ // At least one of the three has to have been a real collapse, or this
+ // theme proved nothing: white on the light theme, black on the dark.
+ try testing.expect(raw_white.contrast(asGhostRgb(fc.default_bg)) < min_contrast or
+ raw_black.contrast(asGhostRgb(fc.default_bg)) < min_contrast);
+ // A saturated red is never the page on any curated theme.
+ try testing.expect(raw_red.contrast(asGhostRgb(fc.default_bg)) >= min_contrast);
+ }
+}
+
+test "terminal Filter holds every projected foreground off the page" {
+ const testing = std.testing;
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+
+ for (0..9) |t| {
+ p.settings.theme = @intCast(t);
+ var fc = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &of(pane.terminal.?).vt);
+ var refused: usize = 0;
+ for (fc.target, 0..) |projected_triple, slot| {
+ const projected = asGhostRgb(projected_triple);
+ const ink = legible(&fc, projected);
+ try testing.expect(ink.contrast(asGhostRgb(fc.default_bg)) >= min_contrast);
+ if (!ink.eql(projected)) {
+ refused += 1;
+ try testing.expect(ink.eql(asGhostRgb(fc.fallback_fg)));
+ // Only ever refused for being too near the page.
+ try testing.expect(projected.contrast(asGhostRgb(fc.default_bg)) < min_contrast);
+ }
+ // The key a background asks for is handed back untouched, including
+ // the one whose value is the page itself.
+ try testing.expect(keyedRgb(&fc, GColor.default[slot]).eql(asGhostRgb(fc.target[nearestKey(&fc, GColor.default[slot])])));
+ }
+ // Every curated theme owns at least one collapsing key — that is why
+ // the floor exists — and the floor must not be flattening the palette.
+ try testing.expect(refused > 0);
+ try testing.expect(refused < fc.target.len / 8);
+ }
+}
+
+test "tty ansi colors follow the prompt hug into normal mode" {
+ const testing = std.testing;
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ pane.tty_filter = false;
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } });
+
+ var frame = std.heap.ArenaAllocator.init(testing.allocator);
+ defer frame.deinit();
+ const r = p.view().rects[0];
+ const tx = r.x + config.GUTTER;
+ const body_y = p.bodyTop(pane, r);
+ const red: plain.Color = .{ .rgb = p.theme().palette.?[1] };
+ const blue: plain.Color = .{ .rgb = p.theme().palette.?[4] };
+
+ // tty mode projects the emulator's ansi colours cell for cell.
+ pane.body.mode = .tty;
+ p.shell_rows.stale = true;
+ const tty = try p.render(frame.allocator());
+ try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg);
+ try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg);
+
+ pane.body.mode = .normal;
+ p.shell_rows.stale = true;
+ _ = frame.reset(.retain_capacity);
+ const norm = try p.render(frame.allocator());
+ try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme());
+ try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme());
+ try testing.expectEqual(red, norm.at(tx, body_y).style.fg);
+ try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg);
+}
+
+test "a prompt row hidden end to end paints nothing at all" {
+ const testing = std.testing;
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ const pane = p.panes[0].?;
+ pane.tag_expanded = false; // a 12x8 screen: the body, not the tag
+ p.sync();
+ pane.tty_filter = false;
+ pane.body.mode = .normal;
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } });
+
+ var frame = std.heap.ArenaAllocator.init(testing.allocator);
+ defer frame.deinit();
+ const r = p.view().rects[0];
+ const tx = r.x + config.GUTTER;
+ const body_y = p.bodyTop(pane, r);
+ p.shell_rows.stale = true;
+ const s = try p.render(frame.allocator());
+
+ try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme());
+ try testing.expect(!std.meta.eql(plain.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg));
+}
+
+test "a program that asked for focus reports hears CSI I and CSI O as its pane takes and gives up the keyboard, and as the window does" {
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .cols = 90, .rows = 30, .shells = 3 });
+ defer p.deinit();
+ var frame = std.heap.ArenaAllocator.init(gpa);
+ defer frame.deinit();
+ _ = try p.render(frame.allocator());
+ var out: std.ArrayList(u8) = .empty;
+ defer out.deinit(gpa);
+ _ = try ptyWritesByPane(p, &out);
+ p.view().active = 0;
+ // Asking while its pane has the keyboard: told at once that it has.
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1004h" } });
+ try std.testing.expectEqualStrings("0:\x1b[I\n", try ptyWritesByPane(p, &out));
+ p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?1004h" } });
+ try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out));
+ // A click into the other pane moves the keyboard: out of one, into the
+ // other.
+ const r = p.view().rects[1];
+ const at_col = r.x + config.GUTTER + 2;
+ const at_row = p.bodyTop(p.panes[1].?, r) + 1;
+ p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = at_col, .row = at_row } });
+ p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = at_col, .row = at_row } });
+ try std.testing.expectEqual(@as(usize, 1), p.view().active);
+ try std.testing.expectEqualStrings("0:\x1b[O\n1:\x1b[I\n", try ptyWritesByPane(p, &out));
+ // The window: away and back.
+ p.update(.{ .focus = false });
+ try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out));
+ p.update(.{ .focus = false });
+ try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out));
+ p.update(.{ .focus = true });
+ try std.testing.expectEqualStrings("1:\x1b[I\n", try ptyWritesByPane(p, &out));
+ // A program that did not ask hears nothing: pane 2.
+ p.view().active = 2;
+ p.update(.tick);
+ try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out));
+}
+
+test "a terminal's kitty graphics image is drawn where its program placed it, and a delete takes it away" {
+ if (comptime !images_enabled) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 });
+ defer p.deinit();
+ p.view().frontend.native_images = true;
+ p.view().active = 0;
+ p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } });
+ var frame = std.heap.ArenaAllocator.init(gpa);
+ defer frame.deinit();
+ const pane = p.panes[0].?;
+ pane.body.mode = .tty;
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3;5H" ++ kittyTransmit("c=2,r=1") } });
+ var s = try p.render(frame.allocator());
+ const places = imagePlaces(s);
+ try std.testing.expectEqual(@as(usize, 1), places.len);
+ const place = places[0];
+ const r = p.view().rects[0];
+ const img = of(pane.terminal.?).vt.screens.active.kitty_images.imageById(7).?;
+ try std.testing.expectEqual(plain.Placement.keyOf(pane.serial, 7, @truncate(img.generation)), place.key);
+ try std.testing.expectEqual(plain.RectCell{ .x = r.x + config.GUTTER + 4, .y = p.bodyTop(pane, r) + 2, .w = 2, .h = 1 }, place.dst);
+ try std.testing.expectEqual(@as(u32, 4), place.raster.w);
+ try std.testing.expectEqual(@as(u32, 2), place.raster.h);
+ try std.testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, place.raster.bytes()[0..4]);
+ try std.testing.expectEqual(plain.RectPx{ .x = 0, .y = 0, .w = 4, .h = 2 }, place.src);
+ try std.testing.expectEqual(plain.RectPx{ .x = 0, .y = 0, .w = 20, .h = 20 }, place.at.?);
+
+ // Scrolled up by the shell's output, it goes up with the text.
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[24;1H\n\n" } });
+ _ = frame.reset(.retain_capacity);
+ s = try p.render(frame.allocator());
+ try std.testing.expectEqual(p.bodyTop(pane, r), imagePlaces(s)[0].dst.y);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\n" } });
+ _ = frame.reset(.retain_capacity);
+ s = try p.render(frame.allocator());
+ try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len);
+
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } });
+ _ = frame.reset(.retain_capacity);
+ s = try p.render(frame.allocator());
+ try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b_Ga=d,d=A\x1b\\" } });
+ _ = frame.reset(.retain_capacity);
+ s = try p.render(frame.allocator());
+ try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len);
+}
+
+test "ED 3 takes away a kitty placement whose row it erased: it never comes back at the top" {
+ if (comptime !images_enabled) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 });
+ defer p.deinit();
+ p.view().frontend.native_images = true;
+ p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } });
+ var frame = std.heap.ArenaAllocator.init(gpa);
+ defer frame.deinit();
+ const pane = p.panes[0].?;
+ pane.body.mode = .tty;
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } });
+ const storage = &of(pane.terminal.?).vt.screens.active.kitty_images;
+ try std.testing.expectEqual(@as(usize, 1), storage.placements.count());
+ // Scrolled into the history, it is not on screen; `clear` (ED 2 then
+ // ED 3) erases that history and the placement with it.
+ p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(40) } });
+ var s = try p.render(frame.allocator());
+ try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[H\x1b[2J\x1b[3J" } });
+ try std.testing.expectEqual(@as(usize, 0), storage.placements.count());
+ _ = frame.reset(.retain_capacity);
+ s = try p.render(frame.allocator());
+ try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len);
+}
+
+test "a finished command's output erased by a later ED 3 is not called whole, and no rows stand in for it" {
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 });
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ const marked = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ p.update(.{ .output = .{ .pane = 0, .bytes = marked ++ "\r\n\x1b]133;C;aid=pardes\x07printed\r\n\x1b]133;D;0;aid=pardes\x07" ++ marked } });
+ const before = try commandOutput(pane.terminal, gpa, 100);
+ defer gpa.free(before.text);
+ try std.testing.expect(before.whole);
+ try std.testing.expect(std.mem.startsWith(u8, before.text, "printed"));
+ // The command's rows go into the history, and ED 3 erases them: its
+ // pins are `garbage` now (ghostty 1.4), not moved to the screen's top,
+ // where another program's text would be read as its output.
+ p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } });
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } });
+ const after = try commandOutput(pane.terminal, gpa, 100);
+ defer gpa.free(after.text);
+ try std.testing.expect(!after.whole);
+ try std.testing.expectEqualStrings("", after.text);
+}
+
+test "a selection whose row ED 3 erased goes; one on the screen stays" {
+ const gpa = std.testing.allocator;
+ for ([_]bool{ true, false }) |in_history| {
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 });
+ defer p.deinit();
+ const pane = p.panes[0].?;
+ pane.body.mode = .tty;
+ p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } });
+ pane.body.mode = .normal;
+ const pages = &of(pane.terminal.?).vt.screens.active.pages;
+ const top: i32 = @intCast(pages.total_rows - pane.rows);
+ const row: i32 = if (in_history) top - 3 else top + 2;
+ pane.body.vsel = .{ .active = true, .row = row, .col = 1 };
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } });
+ try std.testing.expectEqual(!in_history, pane.body.vsel.active);
+ if (!in_history) try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.row);
+ }
+}
+
+test "a virtual kitty placement shows through its placeholder cells, which draw no text" {
+ if (comptime !images_enabled) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 });
+ defer p.deinit();
+ p.view().frontend.native_images = true;
+ p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } });
+ var frame = std.heap.ArenaAllocator.init(gpa);
+ defer frame.deinit();
+ const pane = p.panes[0].?;
+ pane.body.mode = .tty;
+ // yazi's way: a virtual placement two cells by one, then the two
+ // placeholders, the image's id in their colour, row and column in
+ // their diacritics.
+ p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("U=1,c=2,r=1,q=2") ++
+ "\x1b[2;3H\x1b[38;2;0;0;7m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}\u{0305}\u{030D}\x1b[39mX" } });
+ const s = try p.render(frame.allocator());
+ const places = imagePlaces(s);
+ try std.testing.expectEqual(@as(usize, 1), places.len);
+ const r = p.view().rects[0];
+ const tx = r.x + config.GUTTER;
+ const y = p.bodyTop(pane, r) + 1;
+ try std.testing.expectEqual(plain.RectCell{ .x = tx + 2, .y = y, .w = 2, .h = 1 }, places[0].dst);
+ try std.testing.expectEqualStrings(" ", s.at(tx + 2, y).grapheme());
+ try std.testing.expectEqualStrings(" ", s.at(tx + 3, y).grapheme());
+ try std.testing.expectEqualStrings("X", s.at(tx + 4, y).grapheme());
+}
+
+test "a terminal's image is a placement whatever the frontend draws, and the Petscii builtin asks for it as glyph art" {
+ if (comptime !images_enabled) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 });
+ defer p.deinit();
+ p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } });
+ var frame = std.heap.ArenaAllocator.init(gpa);
+ defer frame.deinit();
+ const pane = p.panes[0].?;
+ pane.body.mode = .tty;
+ p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("c=2,r=1") } });
+ const r = p.view().rects[0];
+ const tx = r.x + config.GUTTER;
+ const y = p.bodyTop(pane, r);
+
+ // A frontend that draws no pixels (a tty under no kitty graphics) is
+ // handed the picture all the same, and the cells under it are its.
+ p.view().frontend.native_images = false;
+ var s = try p.render(frame.allocator());
+ try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len);
+ try std.testing.expect(!imagePlaces(s)[0].art.glyph);
+ try std.testing.expectEqualStrings(" ", s.at(tx, y).grapheme());
+ try std.testing.expectEqualStrings(" ", s.at(tx + 1, y).grapheme());
+ // The tag says what that frontend draws, glyph art, as an image pane's does.
+ try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null);
+
+ // The builtin flips the pane to glyph art and back.
+ p.view().frontend.native_images = true;
+ try std.testing.expect(p.executeBuiltinLine(0, "Petscii"));
+ _ = frame.reset(.retain_capacity);
+ s = try p.render(frame.allocator());
+ try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len);
+ try std.testing.expect(imagePlaces(s)[0].art.glyph);
+ try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null);
+ // Dumped and restored, it still asks for glyph art.
+ try pardes.dump.dumpState(p);
+ const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
+ defer restored.deinit();
+ try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?.terminal));
+ try std.testing.expect(p.executeBuiltinLine(0, "Petscii"));
+ _ = frame.reset(.retain_capacity);
+ s = try p.render(frame.allocator());
+ try std.testing.expect(!imagePlaces(s)[0].art.glyph);
+}
+
+test "a new terminal draws its program's images as pixels, and one without images says nothing of them" {
+ if (comptime !images_enabled) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 });
+ defer p.deinit();
+ try std.testing.expectEqual(false, petscii(p.panes[0].?.terminal).?);
+ // A pane without images says nothing of them.
+ try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, p.panes[0].?), "petscii") == null);
+ const id = p.freeSlot().?;
+ const fresh = try p.newShell(id, "");
+ try std.testing.expectEqual(false, petscii(fresh.terminal).?);
+}
+
+test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" {
+ if (comptime !images_enabled) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 });
+ defer p.deinit();
+ p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } });
+ var out: std.ArrayList(u8) = .empty;
+ defer out.deinit(gpa);
+ _ = try ptyWritesByPane(p, &out);
+ p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[16t" } });
+ try std.testing.expectEqualStrings("0:\x1b[6;20;10t\n", try ptyWritesByPane(p, &out));
+}
+
+test "colors.xterm is the palette the emulator starts from, all 256" {
+ for (pardes.colors.xterm, ghostty_vt.color.default) |ours, its| try std.testing.expectEqual(ours, [3]u8{ its.r, its.g, its.b });
+}
+
+test "a replica's terminal pane draws as its authority's does" {
+ const testing = std.testing;
+ const gpa = testing.allocator;
+ const a = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 });
+ defer a.deinit();
+ const b = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 });
+ defer b.deinit();
+ while (a.nextEffect()) |_| {}
+ while (b.nextEffect()) |_| {}
+ var fa = std.heap.ArenaAllocator.init(gpa);
+ defer fa.deinit();
+ var fb = std.heap.ArenaAllocator.init(gpa);
+ defer fb.deinit();
+ // Laid out once, so both panes have their size before the first delta.
+ _ = try a.render(fa.allocator());
+ _ = try b.render(fb.allocator());
+ const ta = &of(a.panes[0].?.terminal.?).vt;
+ const tb = &of(b.panes[0].?.terminal.?).vt;
+ var enc: Encoder = .init(gpa);
+ defer enc.deinit();
+ var peer: Peer = .{};
+ defer peer.deinit(gpa);
+ var tr: Track = .init(gpa);
+ defer tr.deinit(gpa, ta);
+ var rep: Replica = .{};
+ defer rep.deinit(gpa);
+ var delta: std.Io.Writer.Allocating = .init(gpa);
+ defer delta.deinit();
+ var line: [256]u8 = undefined;
+ for (0..60) |i| {
+ const bytes = try std.fmt.bufPrint(&line, "\x1b[1;3{d}m{d}\x1b[0m 漢字 e\u{301} \x1b[48;2;{d};40;60mbg\x1b[0m and then some text that wraps past the width of the pane\r\n", .{ i % 8, i, i * 4 % 256 });
+ a.update(.{ .output = .{ .pane = 0, .bytes = bytes } });
+ delta.clearRetainingCapacity();
+ try testing.expect(try encode(&enc, &tr, &peer, ta, @intCast(i + 1), "", &delta.writer));
+ peer.ack((try rep.apply(gpa, std.Io.Threaded.global_single_threaded.io(), tb, delta.written())).seq);
+ b.needs_frame = true;
+ _ = fa.reset(.retain_capacity);
+ _ = fb.reset(.retain_capacity);
+ const sa = try a.render(fa.allocator());
+ const sb = try b.render(fb.allocator());
+ const r = a.view().rects[0];
+ // The body: below the pane's tag row.
+ for (r.y + 1..r.y + r.h) |y| for (r.x..r.x + r.w) |x| {
+ const ca = sa.at(@intCast(x), @intCast(y));
+ const cb = sb.at(@intCast(x), @intCast(y));
+ if (!ca.visuallyEqual(cb)) {
+ std.debug.print("step {d}: cell {d},{d}: '{s}' vs '{s}'\n", .{ i, x, y, ca.grapheme(), cb.grapheme() });
+ return error.ReplicaDrawsDifferently;
+ }
+ };
+ }
+}