//! The output path through the C ABI alone, so the same model can later check another library //! that exports opentui.h. A seeded script draws cells into an offscreen buffer, moves the cursor, resizes, //! switches between the main screen, the alternate screen and a split footer, writes lines into //! split scrollback, and presents frames. Two Sessions run the script: a candidate that encodes //! frames incrementally and a reference that forces every frame to repaint in full. Each feeds //! its bytes to a Ghostty VT. After every frame both VTs show the frame's cells, at the colour //! depth the Session writes for, and its cursor; the main screen's history holds the lines that //! split mode scrolled away; and the two VTs agree. const std = @import("std"); const c = @import("context_abi_c"); const model = @import("model.zig"); const vt = @import("../ghostty-vt.zig").vt; /// The library under test. Every call goes through this namespace, the functions of opentui.h /// the model needs. This binary links them to its own exports; a test binary for another library /// that exports the header replaces the namespace with extern declarations. const ot = struct { const abi = @import("../context-abi.zig"); const output = @import("../context-output-abi.zig"); pub const ContextHandle = abi.ContextHandle; pub const ot_buffer_acquire_lease = abi.ot_buffer_acquire_lease; pub const ot_buffer_create = abi.ot_buffer_create; pub const ot_buffer_destroy = abi.ot_buffer_destroy; pub const ot_buffer_draw = abi.ot_buffer_draw; pub const ot_buffer_lease_release = abi.ot_buffer_lease_release; pub const ot_buffer_lease_write_resolved_chars = abi.ot_buffer_lease_write_resolved_chars; pub const ot_buffer_resize = abi.ot_buffer_resize; pub const ot_context_create = abi.ot_context_create; pub const ot_context_destroy = abi.ot_context_destroy; pub const ot_scene_create_node = abi.ot_scene_create_node; pub const ot_scene_frame_commit = abi.ot_scene_frame_commit; pub const ot_scene_frame_copy_buffer = output.ot_scene_frame_copy_buffer; pub const ot_scene_frame_draw_buffer = abi.ot_scene_frame_draw_buffer; pub const ot_scene_paint = abi.ot_scene_paint; pub const ot_session_attach_renderer_with_env = abi.ot_session_attach_renderer_with_env; pub const ot_session_cancel = abi.ot_session_cancel; pub const ot_session_complete_output = abi.ot_session_complete_output; pub const ot_session_control = abi.ot_session_control; pub const ot_session_create = abi.ot_session_create; pub const ot_session_destroy = abi.ot_session_destroy; pub const ot_session_get_capabilities = abi.ot_session_get_capabilities; pub const ot_session_get_terminal_state = abi.ot_session_get_terminal_state; pub const ot_session_pump = abi.ot_session_pump; pub const ot_session_read_output = abi.ot_session_read_output; pub const ot_session_render_split = output.ot_session_render_split; pub const ot_session_set_screen = output.ot_session_set_screen; pub const ot_session_setup_terminal = abi.ot_session_setup_terminal; pub const ot_session_split_control = output.ot_session_split_control; }; const reference = 1; /// Terminal rows stay fixed: a row change moves VT history in ways only the host's transition /// logic (outside the library) accounts for. const rows: u32 = 8; const widths = [_]u32{ 12, 16, 10 }; const footers = [_]u32{ 2, 3 }; const black = [4]u16{ 0, 0, 0, 255 }; fn rgb(r: u16, g: u16, b: u16) [4]u16 { return .{ r, g, b, 255 }; } fn indexed(slot: u16, r: u16, g: u16, b: u16) [4]u16 { return .{ r | slot << c.OT_COLOR_META_SHIFT, g | c.OT_COLOR_INDEXED << c.OT_COLOR_META_SHIFT, b, 255 }; } fn default(r: u16, g: u16, b: u16) [4]u16 { return .{ r, g | c.OT_COLOR_DEFAULT << c.OT_COLOR_META_SHIFT, b, 255 }; } const colors = [_][4]u16{ rgb(255, 255, 255), rgb(200, 30, 30), rgb(10, 120, 250), rgb(37, 37, 37), rgb(0, 0, 0), indexed(1, 128, 0, 0), indexed(200, 255, 135, 215), default(255, 255, 255), .{ 0, 0, 0, 0 }, }; /// Wide, combining and plain glyphs; widths agree under every width method. const texts = [_][]const u8{ "a", "hello", "\u{754c}x", "e\u{301}", "\u{1F600}", "ab\u{754c}", " ", "zz\u{754c}\u{754c}" }; /// Scrollback lines with their widths in cells, all narrower than the narrowest terminal. const lines = [_]struct { []const u8, u32 }{ .{ "one", 3 }, .{ "two 2", 5 }, .{ "\u{754c}3", 3 }, .{ "e\u{301}4", 2 }, .{ "five55", 6 }, .{ "\u{1F600}!", 3 }, }; const Depth = enum { truecolor, ansi256 }; const Mode = enum { main, alternate, split }; const Op = union(enum) { text: struct { x: u8, y: u8, text: u8, fg: u8, bg: u8, attributes: u8 }, cell: struct { x: u8, y: u8, char: u8, fg: u8, bg: u8, attributes: u8 }, fill: struct { x: u8, y: u8, w: u8, h: u8, bg: u8 }, cursor: struct { x: u8, y: u8, visible: bool }, resize: u8, screen: struct { mode: Mode, footer: u8 }, output: u8, frame: bool, }; fn record(comptime T: type) T { var value = std.mem.zeroes(T); value.struct_size = @sizeOf(T); value.abi_version = c.OT_CONTEXT_ABI_VERSION; return value; } /// A zeroed ot_buffer_draw record with its header filled in. fn drawRecord(comptime T: type, operation: u32, flags: u32) T { var value = std.mem.zeroes(T); value.header = .{ .struct_size = @sizeOf(T), .abi_version = c.OT_CONTEXT_ABI_VERSION, .operation = operation, .flags = flags }; return value; } fn ok(status: c.ot_status) !void { if (status != c.OT_OK) { std.debug.print("ABI status {d}\n", .{status}); return error.AbiStatus; } } /// The frame's cells, read back through a copy of the draft. const Cells = struct { width: u32, height: u32, /// UTF-8 of each cell's grapheme; empty for the cells a wide glyph covers. text: [][]const u8, fg: [][4]u16, bg: [][4]u16, attributes: []u32, }; /// The xterm palette the header defines (OT_COLOR_ANSI_n, cube and gray ramp). fn palette(index: u8) [3]u8 { if (index < 16) { const values = [16]u32{ c.OT_COLOR_ANSI_0, c.OT_COLOR_ANSI_1, c.OT_COLOR_ANSI_2, c.OT_COLOR_ANSI_3, c.OT_COLOR_ANSI_4, c.OT_COLOR_ANSI_5, c.OT_COLOR_ANSI_6, c.OT_COLOR_ANSI_7, c.OT_COLOR_ANSI_8, c.OT_COLOR_ANSI_9, c.OT_COLOR_ANSI_10, c.OT_COLOR_ANSI_11, c.OT_COLOR_ANSI_12, c.OT_COLOR_ANSI_13, c.OT_COLOR_ANSI_14, c.OT_COLOR_ANSI_15, }; const value = values[index]; return .{ @truncate(value >> 16), @truncate(value >> 8), @truncate(value) }; } if (index < 232) { const cube: u32 = index - 16; return .{ cubeLevel(cube / 36), cubeLevel((cube / 6) % 6), cubeLevel(cube % 6) }; } const gray: u8 = @intCast(c.OT_COLOR_GRAY_BASE + (@as(u32, index) - 232) * c.OT_COLOR_GRAY_STEP); return .{ gray, gray, gray }; } fn cubeLevel(n: u32) u8 { return if (n == 0) 0 else @intCast(c.OT_COLOR_CUBE_BASE + c.OT_COLOR_CUBE_STEP * n); } fn distance(color: [4]u16, other: [3]u8) u32 { var sum: u32 = 0; for (0..3) |i| { const d = @as(i32, color[i] & 0xff) - @as(i32, other[i]); sum += @intCast(d * d); } return sum; } /// Whether the VT shows the frame colour as the Session writes it at this depth: terminal /// default for a default or (background) transparent colour, the palette slot for an indexed /// one, the exact RGB in true colour, and a nearest palette entry in 256 colours. fn colorShows(color: [4]u16, shown: vt.Style.Color, background: bool, depth: Depth) bool { const intent = color[1] >> c.OT_COLOR_META_SHIFT; if (intent == c.OT_COLOR_DEFAULT or (background and color[3] & 0xff == 0)) return shown == .none; if (intent == c.OT_COLOR_INDEXED) return shown == .palette and shown.palette == color[0] >> c.OT_COLOR_META_SHIFT; switch (depth) { .truecolor => return shown == .rgb and shown.rgb.r == color[0] & 0xff and shown.rgb.g == color[1] & 0xff and shown.rgb.b == color[2] & 0xff, .ansi256 => { if (shown != .palette) return false; var best: u32 = std.math.maxInt(u32); for (0..256) |index| best = @min(best, distance(color, palette(@intCast(index)))); return distance(color, palette(shown.palette)) == best; }, } } /// UTF-8 of a VT cell's grapheme, a space for an empty cell. fn cellText(cell: vt.PageList.Cell, out: []u8) []const u8 { const codepoint = cell.cell.codepoint(); var len: usize = std.unicode.utf8Encode(if (codepoint == 0) ' ' else codepoint, out) catch 0; if (cell.cell.hasGrapheme()) if (cell.node.page().lookupGrapheme(cell.cell)) |rest| for (rest) |extra| { len += std.unicode.utf8Encode(extra, out[len..]) catch 0; }; return out[0..len]; } /// A screen row's text without trailing blanks, skipping the cells a wide glyph covers. fn rowText(arena: std.mem.Allocator, screen: *vt.Screen, y: usize) ![]const u8 { var text: std.ArrayList(u8) = .empty; for (0..screen.pages.cols) |x| { const cell = screen.pages.getCell(.{ .screen = .{ .x = @intCast(x), .y = @intCast(y) } }) orelse break; if (cell.cell.wide == .spacer_tail or cell.cell.wide == .spacer_head) continue; var bytes: [64]u8 = undefined; try text.appendSlice(arena, cellText(cell, &bytes)); } return std.mem.trimEnd(u8, text.items, " "); } fn historyRows(screen: *vt.Screen) usize { return screen.pages.total_rows - screen.pages.rows; } /// One Session with its Ghostty VT and its offscreen source buffer. const Twin = struct { session: c.ot_handle, source: c.ot_handle, terminal: *vt.Terminal, stream: vt.TerminalStream, fn drain(self: *Twin, context: *ot.ContextHandle) !void { var chunk: [8192]u8 = undefined; while (true) { var ticket: c.ot_output_ticket = undefined; try ok(ot.ot_session_read_output(context, &self.session, &chunk, chunk.len, &ticket)); if (ticket.byte_count == 0) return; self.stream.nextSlice(chunk[0..ticket.byte_count]); try ok(ot.ot_session_complete_output(context, &self.session, &ticket, 1)); } } }; const Harness = struct { pub const Command = Op; depth: Depth, pub fn generate(_: *Harness, arena: std.mem.Allocator, random: std.Random, steps: usize) ![]Op { const commands = try arena.alloc(Op, steps); for (commands) |*command| { const x = random.int(u8); const y = random.int(u8); command.* = switch (random.uintLessThan(u8, 100)) { 0...21 => .{ .text = .{ .x = x, .y = y, .text = random.uintLessThan(u8, texts.len), .fg = random.uintLessThan(u8, colors.len), .bg = random.uintLessThan(u8, colors.len), .attributes = random.int(u8) } }, 22...31 => .{ .cell = .{ .x = x, .y = y, .char = random.intRangeAtMost(u8, '!', '~'), .fg = random.uintLessThan(u8, colors.len), .bg = random.uintLessThan(u8, colors.len), .attributes = random.int(u8) } }, 32...37 => .{ .fill = .{ .x = x, .y = y, .w = random.uintLessThan(u8, 8), .h = random.uintLessThan(u8, 4), .bg = random.uintLessThan(u8, colors.len) } }, 38...43 => .{ .cursor = .{ .x = x, .y = y, .visible = random.uintLessThan(u8, 3) != 0 } }, 44...46 => .{ .resize = random.uintLessThan(u8, widths.len) }, 47...54 => .{ .screen = .{ .mode = random.enumValue(Mode), .footer = random.uintLessThan(u8, footers.len) } }, 55...69 => .{ .output = random.uintLessThan(u8, lines.len) }, else => .{ .frame = random.uintLessThan(u8, 8) == 0 }, }; } return commands; } pub fn simplify(_: *Harness, arena: std.mem.Allocator, command: Op) ![]const Op { return switch (command) { .text => |value| if (value.attributes != 0 or value.fg != 0 or value.bg != 0) try arena.dupe(Op, &.{.{ .text = .{ .x = value.x, .y = value.y, .text = value.text, .fg = 0, .bg = 0, .attributes = 0 } }}) else &.{}, .cell => |value| if (value.attributes != 0 or value.fg != 0 or value.bg != 0) try arena.dupe(Op, &.{.{ .cell = .{ .x = value.x, .y = value.y, .char = value.char, .fg = 0, .bg = 0, .attributes = 0 } }}) else &.{}, .frame => |force| if (force) try arena.dupe(Op, &.{.{ .frame = false }}) else &.{}, else => &.{}, }; } pub fn format(_: *Harness, command: Op, writer: *std.Io.Writer) void { writer.print("{any}", .{command}) catch {}; } pub fn run(self: *Harness, arena: std.mem.Allocator, commands: []const Op) !?model.Failure { var options = record(c.ot_context_options); options.object_capacity = 64; options.render_cells_max = 4096; var context: ?*ot.ContextHandle = null; try ok(ot.ot_context_create(&options, &context)); defer std.testing.expectEqual(c.OT_OK, ot.ot_context_destroy(context.?)) catch unreachable; var state: Run = .{ .context = context.?, .arena = arena, .depth = self.depth }; var made: usize = 0; defer for (state.twins[0..made]) |*twin| { _ = ot.ot_session_cancel(state.context, &twin.session); std.testing.expectEqual(c.OT_OK, ot.ot_session_destroy(state.context, &twin.session)) catch unreachable; std.testing.expectEqual(c.OT_OK, ot.ot_buffer_destroy(state.context, &twin.source)) catch unreachable; twin.stream.deinit(); twin.terminal.deinit(std.testing.allocator); }; for (&state.twins) |*twin| { try state.initTwin(twin); made += 1; } for (commands, 0..) |command, step| { const property = try state.apply(command) orelse continue; if (model.fail(property, step)) |failure| return failure; } return null; } }; const Run = struct { context: *ot.ContextHandle, arena: std.mem.Allocator, depth: Depth, twins: [2]Twin = undefined, width_method: u32 = 0, mode: Mode = .main, width: u32 = widths[0], footer: u32 = footers[0], cursor: ?[2]u32 = null, /// Every line written into split scrollback that the VT still holds above the footer or in /// its history, oldest first. history: std.ArrayList([]const u8) = .empty, /// Lines published since the split scrollback was last reset, and whether the last one left /// the output cursor on a fresh line. published: u32 = 0, tail: bool = false, /// Split scrollback kept while the alternate screen shows. parked: bool = false, pending: std.ArrayList(u8) = .empty, now_ns: u64 = 0, fn height(self: *const Run) u32 { return if (self.mode == .split) self.footer else rows; } fn pinned(self: *const Run) u32 { return rows - self.footer; } /// Rows above the footer that hold split output, the fresh tail line included. fn visible(self: *const Run) u32 { return @min(self.published + @intFromBool(self.tail), self.pinned()); } /// Lines of history that show above the footer (the tail line is not one). fn visibleLines(self: *const Run) u32 { const shown = self.visible(); return shown - @intFromBool(self.tail and shown > 0); } fn initTwin(self: *Run, twin: *Twin) !void { var options = record(c.ot_session_options); options.chunk_size = 4096; options.span_capacity = 64; options.max_bytes = 256 * 1024; options.control_capacity = c.OT_SESSION_CONTROL_PACKET_BYTES; try ok(ot.ot_session_create(self.context, &options, &twin.session)); var environment: std.ArrayList(u8) = .empty; const entries: []const [2][]const u8 = switch (self.depth) { .truecolor => &.{ .{ "TERM", "xterm-256color" }, .{ "COLORTERM", "truecolor" } }, .ansi256 => &.{.{ "TERM", "xterm-256color" }}, }; for (entries) |entry| { for (entry) |part| try environment.appendSlice(self.arena, std.mem.asBytes(&@as(u32, @intCast(part.len)))); for (entry) |part| try environment.appendSlice(self.arena, part); } var renderer = record(c.ot_session_renderer_env_options); renderer.width = self.width; renderer.height = rows; renderer.remote_mode = c.OT_SESSION_REMOTE_REMOTE; renderer.entry_count = @intCast(entries.len); renderer.byte_count = @intCast(environment.items.len); try ok(ot.ot_session_attach_renderer_with_env(self.context, &twin.session, &renderer, environment.items.ptr)); var root: c.ot_handle = undefined; try ok(ot.ot_scene_create_node(self.context, &twin.session, c.OT_SCENE_ROOT, 1, &root)); twin.terminal = try self.arena.create(vt.Terminal); twin.terminal.* = try .init(std.testing.io, std.testing.allocator, .{ .cols = @intCast(self.width), .rows = rows, .max_scrollback_bytes = null }); twin.stream = twin.terminal.vtStream(); // Grapheme clustering, as the renderer assumes. twin.stream.nextSlice("\x1b[?2027h"); const terminal = record(c.ot_session_terminal_options); try ok(ot.ot_session_setup_terminal(self.context, &twin.session, &terminal)); try self.pump(twin); var phase: u32 = 0; try ok(ot.ot_session_get_terminal_state(self.context, &twin.session, &phase)); if (phase != c.OT_TERMINAL_ACTIVE) return error.TerminalNotActive; var capabilities = record(c.ot_session_capabilities); try ok(ot.ot_session_get_capabilities(self.context, &twin.session, &capabilities)); self.width_method = capabilities.width_method; var buffer = record(c.ot_buffer_options); buffer.width = self.width; buffer.height = rows; buffer.width_method = self.width_method; try ok(ot.ot_buffer_create(self.context, &buffer, &twin.source)); var clear = drawRecord(c.ot_buffer_draw_clear, c.OT_BUFFER_DRAW_CLEAR, 0); clear.background = black; try self.draw(twin.source, &clear.header, ""); } fn pump(self: *Run, twin: *Twin) !void { for (0..256) |_| { var result = record(c.ot_session_pump_result); try ok(ot.ot_session_pump(self.context, &twin.session, self.now_ns, 1, &result)); switch (result.status) { c.OT_PUMP_OUTPUT_PENDING => try twin.drain(self.context), c.OT_PUMP_WAIT_UNTIL => self.now_ns = result.deadline_ns, c.OT_PUMP_AGAIN => {}, else => return, } } return error.PumpDidNotSettle; } fn draw(self: *Run, target: c.ot_handle, header: *const c.ot_buffer_draw_header, text: []const u8) !void { try ok(ot.ot_buffer_draw(self.context, &target, null, header, null, if (text.len == 0) null else text.ptr, @intCast(text.len), null, 0)); } fn drawText(self: *Run, target: c.ot_handle, x: i32, y: i32, text: []const u8, fg: [4]u16, bg: [4]u16, attributes: u32) !void { var value = drawRecord(c.ot_buffer_draw_text_record, c.OT_BUFFER_DRAW_TEXT, c.OT_BUFFER_DRAW_HAS_BACKGROUND); value.x = x; value.y = y; value.attributes = attributes; value.foreground = fg; value.background = bg; try self.draw(target, &value.header, text); } /// Switches screen and frame size together; a smaller frame clamps the cursor for good. fn setScreen(self: *Run, alternate: bool, width: u32, trailing: []const u8) !void { if (self.cursor) |*cursor| cursor.* = .{ @min(cursor[0], width), @min(cursor[1], self.height()) }; for (&self.twins) |*twin| { try ok(ot.ot_session_set_screen(self.context, &twin.session, @intFromBool(alternate), width, self.height(), if (trailing.len == 0) null else trailing.ptr, @intCast(trailing.len))); try twin.drain(self.context); try ok(ot.ot_buffer_resize(self.context, &twin.source, width, self.height())); } } fn splitControl(self: *Run, command: u32, arguments: []const u32) !void { var control = record(c.ot_split_control); control.command = command; @memcpy(control.arguments[0..arguments.len], arguments); for (&self.twins) |*twin| { var offset: u32 = 0; try ok(ot.ot_session_split_control(self.context, &twin.session, &control, &offset)); } } /// Split output leaves the viewport: only lines already in history stay. fn dropVisible(self: *Run) void { self.history.shrinkRetainingCapacity(self.history.items.len - self.visibleLines()); self.published = 0; self.tail = false; } /// Applies one command; the name of a property it broke, or null. fn apply(self: *Run, command: Op) !?[]const u8 { switch (command) { .text => |value| { for (&self.twins) |*twin| try self.drawText(twin.source, @as(i32, @intCast(value.x % (self.width + 2))) - 2, @intCast(value.y % self.height()), texts[value.text], colors[value.fg], colors[value.bg], value.attributes); model.count("text"); }, .cell => |value| { var cell = drawRecord(c.ot_buffer_draw_cell, c.OT_BUFFER_DRAW_CELL, 0); cell.x = @intCast(value.x % self.width); cell.y = @intCast(value.y % self.height()); cell.character = value.char; cell.attributes = value.attributes; cell.foreground = colors[value.fg]; cell.background = colors[value.bg]; for (&self.twins) |*twin| try self.draw(twin.source, &cell.header, ""); model.count("cell"); }, .fill => |value| { var fill = drawRecord(c.ot_buffer_draw_fill, c.OT_BUFFER_DRAW_FILL, 0); fill.x = @intCast(value.x % self.width); fill.y = @intCast(value.y % self.height()); fill.width = value.w; fill.height = value.h; fill.background = colors[value.bg]; for (&self.twins) |*twin| try self.draw(twin.source, &fill.header, ""); model.count("fill"); }, .cursor => |value| { var update = std.mem.zeroes(c.ot_session_cursor_update); update.fields = c.OT_CURSOR_POSITION; update.x = @intCast(1 + value.x % self.width); update.y = @intCast(1 + value.y % self.height()); update.visible = @intFromBool(value.visible); var control = record(c.ot_session_control_options); control.kind = c.OT_CONTROL_CURSOR; for (&self.twins) |*twin| try ok(ot.ot_session_control(self.context, &twin.session, &control, std.mem.asBytes(&update), @sizeOf(c.ot_session_cursor_update))); self.cursor = if (value.visible) .{ @intCast(update.x), @intCast(update.y) } else null; model.count("cursor"); }, .resize => |index| { const width = widths[index]; // A narrower terminal reflows the hidden main screen behind the alternate one, which // no output can prevent; there the model only widens. if (width == self.width or (self.mode == .alternate and width < self.width)) return null; // Blank the rows that reflow could wrap: the frame, from the footer down in split. var trailing: [32]u8 = undefined; const clear = if (self.mode == .split) try std.fmt.bufPrint(&trailing, "\x1b[0m\x1b[{d};1H\x1b[J", .{self.visible() + 1}) else "\x1b[0m\x1b[H\x1b[2J"; try self.setScreen(self.mode == .alternate, width, clear); for (&self.twins) |*twin| try twin.terminal.resize(std.testing.allocator, .{ .cols = @intCast(width), .rows = rows }); self.width = width; model.count("resize"); }, .screen => |value| { if (value.mode == self.mode) return null; try self.switchMode(value.mode, footers[value.footer]); model.count(@tagName(value.mode)); }, .output => |index| { if (self.mode != .split or self.pending.items.len == c.OT_SPLIT_SNAPSHOTS_MAX) return null; try self.pending.append(self.arena, index); model.count("output"); }, .frame => |force| return self.frame(force), } return null; } fn switchMode(self: *Run, next: Mode, footer: u32) !void { var trailing: [32]u8 = undefined; switch (self.mode) { .split => { const top = self.visible() + 1; // Queued lines go out with a split frame only. self.pending.clearRetainingCapacity(); self.mode = next; if (next == .alternate) { try self.setScreen(true, self.width, ""); try self.splitControl(3, &.{0}); self.parked = true; } else { try self.setScreen(false, self.width, try std.fmt.bufPrint(&trailing, "\x1b[0m\x1b[{d};1H\x1b[J", .{top})); try self.splitControl(0, &.{ 0, 0 }); try self.splitControl(3, &.{0}); self.dropVisible(); } }, .alternate => if (next == .split and self.parked) { self.mode = next; try self.setScreen(false, self.width, ""); try self.splitControl(1, &.{self.pinned()}); self.parked = false; model.count("unpark"); } else if (next == .split) { try self.enterSplit(footer); } else { self.mode = next; try self.setScreen(false, self.width, ""); if (self.parked) { // The main frame covers the parked footer and the split output above it. try self.splitControl(0, &.{ 0, 0 }); try self.splitControl(3, &.{0}); self.dropVisible(); self.parked = false; } }, .main => if (next == .split) try self.enterSplit(footer) else { self.mode = next; try self.setScreen(true, self.width, ""); }, } } /// A fresh split footer at the top of a cleared viewport. fn enterSplit(self: *Run, footer: u32) !void { self.mode = .split; self.footer = footer; try self.setScreen(false, self.width, "\x1b[0m\x1b[H\x1b[2J"); try self.splitControl(0, &.{ 0, self.pinned() }); self.parked = false; self.published = 0; self.tail = false; } /// Paints the source into a scene draft, reads the draft's cells, and presents it on both /// twins (the reference forced to a full repaint), then checks the properties. fn frame(self: *Run, force: bool) !?[]const u8 { var cells: [2]Cells = undefined; for (&self.twins, 0..) |*twin, index| { var request = record(c.ot_scene_frame_request); try ok(ot.ot_scene_paint(self.context, &twin.session, &black, 0, 0, &request)); if (request.kind != c.OT_SCENE_FRAME_DONE) return error.FrameNotDone; try ok(ot.ot_scene_frame_draw_buffer(self.context, &twin.session, &request, &twin.source, 0, 0)); cells[index] = try self.copy(twin, &request); const forced: u32 = @intFromBool(force or index == reference); var status: u32 = 0; if (self.mode == .split) { var snapshots: [c.OT_SPLIT_SNAPSHOTS_MAX]c.ot_split_snapshot = undefined; const count = self.pending.items.len; for (self.pending.items[0..count], snapshots[0..count]) |line, *snapshot| { var options = record(c.ot_buffer_options); options.width = lines[line][1]; options.height = 1; options.width_method = self.width_method; try ok(ot.ot_buffer_create(self.context, &options, &snapshot.buffer)); try self.drawText(snapshot.buffer, 0, 0, lines[line][0], colors[0], black, 0); snapshot.row_columns = lines[line][1]; snapshot.flags = 3; } defer for (snapshots[0..count]) |snapshot| std.testing.expectEqual(c.OT_OK, ot.ot_buffer_destroy(self.context, &snapshot.buffer)) catch unreachable; try ok(ot.ot_session_render_split(self.context, &twin.session, &request, &snapshots, @intCast(count), self.pinned(), forced, &status)); } else { try ok(ot.ot_scene_frame_commit(self.context, &twin.session, &request, forced, &status)); } if (status == c.OT_RENDER_FAILED or status == c.OT_RENDER_SKIPPED) return error.FrameNotPresented; try twin.drain(self.context); } for (self.pending.items) |line| try self.history.append(self.arena, lines[line][0]); self.published += @intCast(self.pending.items.len); self.tail = self.tail or self.pending.items.len > 0; self.pending.clearRetainingCapacity(); model.count(if (force) "force" else "frame"); for (&self.twins, cells) |*twin, expected| { if (try self.cellsDiffer(twin.terminal, expected)) return "cells"; if (self.cursorDiffers(twin.terminal)) return "cursor"; if (try self.historyDiffers(twin.terminal)) return "history"; } if (try self.screensDiffer()) return "repaint"; return null; } fn copy(self: *Run, twin: *Twin, request: *const c.ot_scene_frame_request) !Cells { var options = record(c.ot_buffer_options); options.width = self.width; options.height = self.height(); options.width_method = self.width_method; var target: c.ot_handle = undefined; try ok(ot.ot_buffer_create(self.context, &options, &target)); defer std.testing.expectEqual(c.OT_OK, ot.ot_buffer_destroy(self.context, &target)) catch unreachable; try ok(ot.ot_scene_frame_copy_buffer(self.context, &twin.session, request, &target)); var lease = record(c.ot_buffer_lease_snapshot); try ok(ot.ot_buffer_acquire_lease(self.context, &target, &lease)); defer std.testing.expectEqual(c.OT_OK, ot.ot_buffer_lease_release(self.context, &lease.lease)) catch unreachable; const count = lease.width * lease.height; const lengths = try self.arena.alloc(u8, count); var bytes: [8192]u8 = undefined; var written: u32 = 0; try ok(ot.ot_buffer_lease_write_resolved_chars(self.context, &lease.lease, &bytes, bytes.len, 0, lengths.ptr, count, &written)); const result: Cells = .{ .width = lease.width, .height = lease.height, .text = try self.arena.alloc([]const u8, count), .fg = try self.arena.dupe([4]u16, @as([*]const [4]u16, @ptrFromInt(lease.fg_ptr))[0..count]), .bg = try self.arena.dupe([4]u16, @as([*]const [4]u16, @ptrFromInt(lease.bg_ptr))[0..count]), .attributes = try self.arena.dupe(u32, @as([*]const u32, @ptrFromInt(lease.attributes_ptr))[0..count]), }; var at: usize = 0; for (result.text, lengths) |*text, length| { text.* = try self.arena.dupe(u8, bytes[at..][0..length]); at += length; } return result; } /// The VT's active screen shows the frame at the footer's row: each cell's grapheme and /// width, background, foreground where a glyph or a line shows it, and attributes. fn cellsDiffer(self: *Run, terminal: *vt.Terminal, expected: Cells) !bool { model.count("cells"); const top = if (self.mode == .split) self.visible() else 0; const screen = terminal.screens.active; for (0..expected.height) |y| for (0..expected.width) |x| { const index = y * expected.width + x; const cell = screen.pages.getCell(.{ .active = .{ .x = @intCast(x), .y = @intCast(top + y) } }) orelse return report(x, y, "missing"); const text = expected.text[index]; if (text.len == 0) { if (cell.cell.wide != .spacer_tail) return report(x, y, "width"); continue; } var bytes: [64]u8 = undefined; const shown = cellText(cell, &bytes); if (!std.mem.eql(u8, text, shown)) { std.debug.print("expected '{s}', VT shows '{s}'\n", .{ text, shown }); return report(x, y, "char"); } const wide = x + 1 < expected.width and expected.text[index + 1].len == 0; if (wide != (cell.cell.wide == .wide)) return report(x, y, "wide"); const style = cell.style(); if (!colorShows(expected.bg[index], style.bg_color, true, self.depth)) return report(x, y, "bg"); const attributes = expected.attributes[index] & c.OT_ATTR_BASE_MASK; const lined = attributes & (c.OT_ATTR_UNDERLINE | c.OT_ATTR_STRIKETHROUGH | c.OT_ATTR_INVERSE) != 0; if ((!std.mem.eql(u8, text, " ") or lined) and !colorShows(expected.fg[index], style.fg_color, false, self.depth)) return report(x, y, "fg"); const flags = style.flags; const shown_attributes: u32 = @as(u32, @intFromBool(flags.bold)) * c.OT_ATTR_BOLD | @as(u32, @intFromBool(flags.faint)) * c.OT_ATTR_DIM | @as(u32, @intFromBool(flags.italic)) * c.OT_ATTR_ITALIC | @as(u32, @intFromBool(flags.underline != .none)) * c.OT_ATTR_UNDERLINE | @as(u32, @intFromBool(flags.blink)) * c.OT_ATTR_BLINK | @as(u32, @intFromBool(flags.inverse)) * c.OT_ATTR_INVERSE | @as(u32, @intFromBool(flags.invisible)) * c.OT_ATTR_HIDDEN | @as(u32, @intFromBool(flags.strikethrough)) * c.OT_ATTR_STRIKETHROUGH; if (shown_attributes != attributes) return report(x, y, "attributes"); }; return false; } fn report(x: usize, y: usize, field: []const u8) bool { std.debug.print("frame cell {d},{d}: {s}\n", .{ x, y, field }); return true; } /// The VT cursor shows where the intent puts it, below split output, or is hidden. fn cursorDiffers(self: *Run, terminal: *vt.Terminal) bool { model.count("cursor shown"); const shown = terminal.modes.get(.cursor_visible); const position = self.cursor orelse return shown; const top = if (self.mode == .split) self.visible() else 0; const cursor = terminal.screens.active.cursor; const x = position[0] - 1; const y = position[1] - 1 + top; if (!shown or cursor.x != x or cursor.y != y) { std.debug.print("cursor: expected {d},{d}, VT {d},{d} visible {}\n", .{ x, y, cursor.x, cursor.y, shown }); return true; } return false; } /// The main screen's history and the split output above the footer hold, in order, the /// lines written into scrollback; while the alternate screen shows, the history does. fn historyDiffers(self: *Run, terminal: *vt.Terminal) !bool { model.count("history"); const screen = terminal.screens.all.get(.primary).?; var shown: std.ArrayList([]const u8) = .empty; const above: usize = if (self.mode == .split) self.visible() else 0; if (historyRows(screen) > 0) model.count("history rows"); for (0..historyRows(screen) + above) |y| try shown.append(self.arena, try rowText(self.arena, screen, y)); var expected: std.ArrayList([]const u8) = .empty; try expected.appendSlice(self.arena, self.history.items); if (self.mode == .split and self.tail and self.visible() > 0) try expected.append(self.arena, ""); if (self.mode == .alternate and self.parked) expected.shrinkRetainingCapacity(self.history.items.len - self.visibleLines()); if (shown.items.len == expected.items.len) { for (shown.items, expected.items) |a, b| { if (!std.mem.eql(u8, a, b)) break; } else return false; } std.debug.print("history: VT {d} rows, expected {d}\n", .{ shown.items.len, expected.items.len }); for (shown.items) |row| std.debug.print(" VT '{s}'\n", .{row}); for (expected.items) |row| std.debug.print(" model '{s}'\n", .{row}); return true; } /// The incremental and the full-repaint VTs show the same cells, styles, cursor and history. fn screensDiffer(self: *Run) !bool { model.count("repaint"); const terminals = [2]*vt.Terminal{ self.twins[0].terminal, self.twins[1].terminal }; if (terminals[0].screens.active_key != terminals[1].screens.active_key) return reportRepaint("screen"); const visibility = terminals[0].modes.get(.cursor_visible); if (visibility != terminals[1].modes.get(.cursor_visible)) return reportRepaint("cursor visibility"); // A hidden cursor's position shows nowhere. const cursors = [2]vt.Screen.Cursor{ terminals[0].screens.active.cursor, terminals[1].screens.active.cursor }; if (visibility and (cursors[0].x != cursors[1].x or cursors[0].y != cursors[1].y)) return reportRepaint("cursor"); for ([_]vt.ScreenSet.Key{ .primary, .alternate }) |key| { const screen = terminals[0].screens.all.get(key) orelse continue; const other = terminals[1].screens.all.get(key) orelse return reportRepaint("screens"); if (screen.pages.total_rows != other.pages.total_rows) return reportRepaint("rows"); for (0..screen.pages.total_rows) |y| for (0..screen.pages.cols) |x| { const point: vt.point.Point = .{ .screen = .{ .x = @intCast(x), .y = @intCast(y) } }; const a = screen.pages.getCell(point).?; const b = other.pages.getCell(point).?; var bytes: [2][64]u8 = undefined; if (!std.mem.eql(u8, cellText(a, &bytes[0]), cellText(b, &bytes[1])) or a.cell.wide != b.cell.wide or !std.meta.eql(a.style(), b.style())) { std.debug.print("repaint: {s} screen cell {d},{d} differs\n", .{ @tagName(key), x, y }); return true; } }; } return false; } fn reportRepaint(what: []const u8) bool { std.debug.print("repaint: {s} differs\n", .{what}); return true; } }; test "Output VT ABI: VT rows equal the frame, history survives mode changes, incremental equals full" { for ([_]Depth{ .truecolor, .ansi256 }) |depth| { var harness: Harness = .{ .depth = depth }; try model.check(Harness, &harness, .{ .seeds = 32, .steps = 96 }); } }