//! Terminal image placement through the C ABI alone, so the same model can later check another //! library that exports opentui.h. A seeded script moves, resizes, crops, clips, restacks and //! removes image nodes, scrolls a scroll view that holds images, resizes the terminal, switches //! between the main screen, the alternate screen and a split footer, suspends and resumes, clears //! the terminal and presents frames, with every image on Kitty graphics or on Sixel. //! //! The oracle reads the Session's bytes. A Ghostty VT tracks the cursor, the screens, scrolling //! and the cells; its build has no Kitty graphics, so a test-side interpreter keeps what a Kitty //! terminal keeps for each screen: transmitted images (a=t: id and pixel size; a new transmit //! of an id drops its placements), placements (a=p at the cursor, anchored to their cell so they //! scroll with the text, replaced by the same image and placement id), deletes (a=d, d=i and d=I), //! and what the kitty terminal does on ESC[2J (placements on screen go, images without one are //! freed) and on entering the alternate screen (its images go). A Sixel image (DCS q) at the //! cursor marks the cells its raster size covers in the VT with a private-use character naming //! the draw, so later text and erasures replace it as they replace the image's pixels. //! //! After every frame each visible image shows exactly once on each cell it owns, from its node's //! current image, crop and fit, and no other cell shows an image. 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 image = @import("../context-image-abi.zig"); const output = @import("../context-output-abi.zig"); pub const ContextHandle = abi.ContextHandle; 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_context_create = abi.ot_context_create; pub const ot_context_destroy = abi.ot_context_destroy; pub const ot_image_create_pixels = image.ot_image_create_pixels; pub const ot_image_destroy = abi.ot_image_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_get_layout = abi.ot_scene_get_layout; pub const ot_scene_move_node = abi.ot_scene_move_node; pub const ot_scene_paint = abi.ot_scene_paint; pub const ot_scene_scroll_to = abi.ot_scene_scroll_to; pub const ot_scene_set_crop = abi.ot_scene_set_crop; pub const ot_scene_set_image = abi.ot_scene_set_image; pub const ot_scene_set_scroll = abi.ot_scene_set_scroll; pub const ot_scene_set_style = abi.ot_scene_set_style; pub const ot_scene_set_text = abi.ot_scene_set_text; 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_create = abi.ot_session_create; pub const ot_session_destroy = abi.ot_session_destroy; pub const ot_session_get_renderer_state = abi.ot_session_get_renderer_state; 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_resize_renderer = abi.ot_session_resize_renderer; pub const ot_session_resume = abi.ot_session_resume; pub const ot_session_set_image_resolution = abi.ot_session_set_image_resolution; 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; pub const ot_session_suspend = abi.ot_session_suspend; pub const ot_session_write = abi.ot_session_write; }; /// 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 = 10; const widths = [_]u32{ 24, 16, 20 }; const footers = [_]u32{ 4, 6 }; /// Pixels per cell, as the Session's image resolution says. const cell = [2]u32{ 8, 16 }; /// Each image has its own pixel size, so a transmit names its image. Every node shows at most /// 1.9 source pixels per cell pixel on each axis: the renderer then transmits the image itself, /// never a scaled copy, and a placement's source rectangle is in the image's pixels. const image_sizes = [_][2]u32{ .{ 40, 32 }, .{ 48, 40 }, .{ 56, 24 }, .{ 32, 48 } }; const node_widths = [_]u32{ 4, 6, 8 }; const node_heights = [_]u32{ 2, 3 }; const viewports = [_]u32{ 2, 3, 4 }; /// The scroll view's left, top and width, and the spacer height that makes its content taller /// than any viewport. const view = [3]u32{ 2, 3, 12 }; const content_height = 8; const lines = [_]struct { []const u8, u32 }{ .{ "one", 3 }, .{ "two 2", 5 }, .{ "three", 5 } }; const black = [4]u16{ 0, 0, 0, 255 }; const images = 3; const overlay = 3; const scroll = 4; const spacer = 5; const Protocol = enum { kitty, sixel }; const Mode = enum { main, alternate, split }; const Parent = enum { none, root, scroll }; const Op = union(enum) { /// Inserts an image node (or, at the root, the overlay text) at a child index. attach: struct { node: u8, scroll: bool, index: u8 }, detach: u8, place: struct { node: u8, x: u8, y: u8 }, size: struct { node: u8, w: u8, h: u8 }, image: struct { node: u8, image: u8 }, fit: struct { node: u8, cover: bool }, crop: struct { node: u8, crop: u8 }, scroll: u8, viewport: u8, resize: u8, screen: struct { mode: Mode, footer: u8 }, output: u8, pause, clear, frame: bool, }; const Rect = struct { x: i64 = 0, y: i64 = 0, w: i64 = 0, h: i64 = 0, fn intersect(a: Rect, b: Rect) Rect { const x = @max(a.x, b.x); const y = @max(a.y, b.y); return .{ .x = x, .y = y, .w = @max(0, @min(a.x + a.w, b.x + b.w) - x), .h = @max(0, @min(a.y + a.h, b.y + b.h) - y) }; } fn empty(self: Rect) bool { return self.w <= 0 or self.h <= 0; } fn contains(self: Rect, x: i64, y: i64) bool { return x >= self.x and x < self.x + self.w and y >= self.y and y < self.y + self.h; } }; 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; } fn ok(status: c.ot_status) !void { if (status != c.OT_OK) { std.debug.print("ABI status {d}\n", .{status}); return error.AbiStatus; } } /// The source region a crop selects, in the image's pixels; null shows the whole image. fn cropRegion(index: u8, size: [2]u32) ?[4]u32 { const w = size[0]; const h = size[1]; return switch (index) { 0 => null, 1 => .{ 0, 0, w / 2, h }, 2 => .{ w / 2, h / 2, w - w / 2, h - h / 2 }, else => .{ w / 8, h / 8, w * 3 / 4, h * 3 / 4 }, }; } /// One image placement a Kitty terminal holds, anchored to the cell it was put at. Where /// placements overlap, the higher z shows. const Placement = struct { image: u32, id: u32, z: i64, /// How often its screen had been left when it was put. epoch: u32, pin: *vt.Pin, /// Where kitty keeps it after a resize left its column outside the screen. fixed: ?[2]i64 = null, cols: u32, rows: u32, source: [4]u32, }; const Graphics = struct { images: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty, placements: std.ArrayList(Placement) = .empty, /// How often another screen became active instead. left: u32 = 0, }; /// Where a Sixel draw landed, in active cells when it was drawn, and its pixel size. const SixelDraw = struct { col: i64, row: i64, width: u32, height: u32 }; const sentinel_base: u21 = 0xF0000; /// The VT and the graphics interpreter beside it. const Term = struct { arena: std.mem.Allocator, terminal: *vt.Terminal, stream: vt.TerminalStream, graphics: std.EnumArray(vt.ScreenSet.Key, Graphics) = .initFill(.{}), /// A chunked transmit not finished yet. loading: ?struct { id: u32, size: [2]u32 } = null, /// Pixel sizes of the images transmitted since the last frame check. transmits: std.ArrayList([2]u32) = .empty, /// Puts that named an image the screen does not hold, since the last frame check. lost_puts: u32 = 0, sixels: std.ArrayList(SixelDraw) = .empty, /// ESC[2J frees images left without a placement, as kitty and Ghostty do. erase_frees: bool = true, fn screen(self: *Term) *vt.Screen { return self.terminal.screens.active; } /// The placement's top-left cell in active coordinates; a row above the active area is /// negative. fn origin(self: *Term, key: vt.ScreenSet.Key, placement: Placement) ?[2]i64 { if (placement.fixed) |at| return at; const pages = &(self.terminal.screens.get(key) orelse return null).pages; const at = pages.pointFromPin(.screen, placement.pin.*) orelse return null; const top = pages.pointFromPin(.screen, pages.getTopLeft(.active)) orelse return null; return .{ at.screen.x, @as(i64, at.screen.y) - top.screen.y }; } fn dropWhere(self: *Term, key: vt.ScreenSet.Key, image: ?u32, id: ?u32, visible_only: bool) void { const graphics = self.graphics.getPtr(key); var index: usize = 0; while (index < graphics.placements.items.len) { const placement = graphics.placements.items[index]; const shown = if (self.origin(key, placement)) |at| at[1] + placement.rows > 0 else false; if ((image == null or placement.image == image.?) and (id == null or placement.id == id.?) and (!visible_only or shown)) { _ = graphics.placements.orderedRemove(index); if (self.terminal.screens.get(key)) |owner| owner.pages.untrackPin(placement.pin); } else index += 1; } } fn placed(graphics: *const Graphics, image: u32) bool { for (graphics.placements.items) |placement| { if (placement.image == image) return true; } return false; } /// Feeds the bytes one drain read: complete sequences, so no state carries over. fn feed(self: *Term, bytes: []const u8) !void { var plain: usize = 0; var i: usize = 0; while (i + 1 < bytes.len) { if (bytes[i] != 0x1b) { i += 1; continue; } switch (bytes[i + 1]) { '_', 'P' => { const end = std.mem.indexOfPos(u8, bytes, i + 2, "\x1b\\") orelse return error.UnterminatedString; const body = bytes[i + 2 .. end]; const is_kitty = bytes[i + 1] == '_' and body.len > 0 and body[0] == 'G'; const is_sixel = bytes[i + 1] == 'P' and isSixel(body); if (is_kitty or is_sixel) { self.stream.nextSlice(bytes[plain..i]); if (is_kitty) try self.kitty(body[1..]) else try self.sixel(body); plain = end + 2; } i = end + 2; }, '[' => { var j = i + 2; while (j < bytes.len and (bytes[j] < 0x40 or bytes[j] > 0x7e)) j += 1; if (j == bytes.len) return error.UnterminatedSequence; const params = bytes[i + 2 .. j]; const erase = bytes[j] == 'J' and (std.mem.eql(u8, params, "2") or std.mem.eql(u8, params, "3")); const switches = (bytes[j] == 'h' or bytes[j] == 'l') and params.len > 0 and params[0] == '?'; if (erase or switches) { const before = self.terminal.screens.active_key; self.stream.nextSlice(bytes[plain .. j + 1]); plain = j + 1; const key = self.terminal.screens.active_key; const graphics = self.graphics.getPtr(key); if (key != before) self.graphics.getPtr(before).left += 1; if (erase) { self.dropWhere(key, null, null, true); var unplaced: std.ArrayList(u32) = .empty; var ids = graphics.images.keyIterator(); while (ids.next()) |id| if (!placed(graphics, id.*)) try unplaced.append(self.arena, id.*); if (self.erase_frees) { for (unplaced.items) |id| _ = graphics.images.remove(id); } } else if (key == .alternate and before != .alternate) { self.dropWhere(key, null, null, false); graphics.images.clearRetainingCapacity(); } } i = j + 1; }, else => i += 2, } } self.stream.nextSlice(bytes[plain..]); } fn isSixel(body: []const u8) bool { for (body) |byte| switch (byte) { '0'...'9', ';' => {}, 'q' => return true, else => return false, }; return false; } /// One Kitty graphics command: its keys, then the payload after ';'. fn kitty(self: *Term, command: []const u8) !void { const keys_end = std.mem.indexOfScalar(u8, command, ';') orelse command.len; var action: u8 = 0; var delete: u8 = 0; var values: [128]?i64 = @splat(null); var it = std.mem.splitScalar(u8, command[0..keys_end], ','); while (it.next()) |pair| { if (pair.len < 3 or pair[1] != '=' or pair[0] >= 128) return error.GraphicsKey; switch (pair[0]) { 'a' => action = pair[2], 'd' => delete = pair[2], // The transmission medium; only direct data comes with a size the model reads. 't' => if (pair[2] != 'd') return error.GraphicsMedium, else => values[pair[0]] = try std.fmt.parseInt(i64, pair[2..], 10), } } const key = self.terminal.screens.active_key; const graphics = self.graphics.getPtr(key); const value = struct { fn of(all: [128]?i64, name: u8) u32 { return @intCast(all[name] orelse 0); } }.of; switch (action) { 't', 0 => { if (action == 't') { if (value(values, 'f') == 100 or values['o'] != null) return error.GraphicsFormat; self.loading = .{ .id = value(values, 'i'), .size = .{ value(values, 's'), value(values, 'v') } }; } const loading = self.loading orelse return error.GraphicsChunk; if (value(values, 'm') == 1) return; self.loading = null; self.dropWhere(key, loading.id, null, false); try graphics.images.put(self.arena, loading.id, loading.size); try self.transmits.append(self.arena, loading.size); }, 'p' => { const image = value(values, 'i'); if (!graphics.images.contains(image)) { self.lost_puts += 1; return; } self.dropWhere(key, image, value(values, 'p'), false); const at = self.screen().cursor; const pin = self.screen().pages.pin(.{ .active = .{ .x = at.x, .y = at.y } }) orelse return error.GraphicsCursor; try graphics.placements.append(self.arena, .{ .image = image, .id = value(values, 'p'), .z = values['z'] orelse 0, .epoch = graphics.left, .pin = try self.screen().pages.trackPin(pin), .cols = value(values, 'c'), .rows = value(values, 'r'), .source = .{ value(values, 'x'), value(values, 'y'), value(values, 'w'), value(values, 'h') }, }); }, 'd' => { const image = value(values, 'i'); if (delete != 'i' and delete != 'I') return error.GraphicsDelete; self.dropWhere(key, image, if (values['p'] != null) value(values, 'p') else null, false); if (delete == 'I' and !placed(graphics, image)) _ = graphics.images.remove(image); }, // A support query stores nothing. 'q' => {}, else => return error.GraphicsAction, } } /// A Sixel image at the cursor: its raster attributes give its pixel size. The cells it /// covers get the private-use character of this draw, written with the cursor saved. fn sixel(self: *Term, body: []const u8) !void { const q = std.mem.indexOfScalar(u8, body, 'q').?; if (q + 1 >= body.len or body[q + 1] != '"') return error.SixelRaster; var numbers: [4]u32 = undefined; var it = std.mem.splitScalar(u8, body[q + 2 ..], ';'); for (&numbers) |*number| { const text = it.next() orelse return error.SixelRaster; var end: usize = 0; while (end < text.len and std.ascii.isDigit(text[end])) end += 1; number.* = try std.fmt.parseInt(u32, text[0..end], 10); } const at = self.screen().cursor; const draw: SixelDraw = .{ .col = at.x, .row = at.y, .width = numbers[2], .height = numbers[3] }; const generation = self.sixels.items.len; try self.sixels.append(self.arena, draw); var bytes: std.ArrayList(u8) = .empty; try bytes.appendSlice(self.arena, "\x1b7"); var mark: [4]u8 = undefined; const mark_len = try std.unicode.utf8Encode(sentinel_base + @as(u21, @intCast(generation)), &mark); const cols = self.screen().pages.cols; for (0..(draw.height + cell[1] - 1) / cell[1]) |dy| { const y = draw.row + @as(i64, @intCast(dy)); if (y >= rows) break; try bytes.print(self.arena, "\x1b[{d};{d}H", .{ y + 1, draw.col + 1 }); for (0..(draw.width + cell[0] - 1) / cell[0]) |dx| { if (draw.col + @as(i64, @intCast(dx)) >= cols) break; try bytes.appendSlice(self.arena, mark[0..mark_len]); } } try bytes.appendSlice(self.arena, "\x1b8"); self.stream.nextSlice(bytes.items); } /// Ghostty reflows the main screen when it narrows and moves placements with their text. /// Kitty keeps them at their cell when only the width changes; with keep, they stay. fn resize(self: *Term, width: u32, keep: bool) !void { var kept: std.ArrayList(struct { vt.ScreenSet.Key, usize, [2]i64 }) = .empty; for ([_]vt.ScreenSet.Key{ .primary, .alternate }) |key| { for (self.graphics.get(key).placements.items, 0..) |placement, index| { if (self.origin(key, placement)) |at| try kept.append(self.arena, .{ key, index, at }); } } try self.terminal.resize(std.testing.allocator, .{ .cols = @intCast(width), .rows = rows }); if (!keep) return; for (kept.items) |entry| { const key, const index, const at = entry; const placement = &self.graphics.getPtr(key).placements.items[index]; placement.fixed = null; const now = self.origin(key, placement.*) orelse continue; if (std.meta.eql(now, at) or at[1] < 0) continue; // Known defect, gated: the renderer does not place unchanged Kitty images again // after a resize. The rows "... (known, gated)" keep the case. model.count("gated resize"); const pages = &self.terminal.screens.get(key).?.pages; const pin = pages.pin(.{ .active = .{ .x = @intCast(@min(at[0], width - 1)), .y = @intCast(at[1]) } }) orelse continue; pages.untrackPin(placement.pin); placement.pin = try pages.trackPin(pin); if (at[0] >= width) placement.fixed = at; } } /// The Sixel draw whose character a cell shows, if any. fn sixelAt(self: *Term, x: usize, y: usize) ?u32 { const at = self.screen().pages.getCell(.{ .active = .{ .x = @intCast(x), .y = @intCast(y) } }) orelse return null; const codepoint = at.cell.codepoint(); if (codepoint < sentinel_base or codepoint >= sentinel_base + self.sixels.items.len) return null; return codepoint - sentinel_base; } }; const Node = struct { handle: c.ot_handle = undefined, parent: Parent = .none, w: u32 = node_widths[0], h: u32 = node_heights[0], image: u8 = 0, cover: bool = false, crop: u8 = 0, /// The crop in source pixels, as set; it stays when the image changes. region: [4]u32 = .{ 0, 0, 0, 0 }, /// The image and the source pixels its visible cells showed in the last frame, if any. content: ?struct { u8, [4]i64 } = null, /// The first Sixel draw that can show the node's current content. fresh_from: u32 = 0, /// Paint index and image in the last presented frame. last: ?struct { index: u32, image: u8 } = null, /// The crop, or the whole image when it is unset or does not lie inside the image. fn shownRegion(self: Node) [4]u32 { const size = image_sizes[self.image]; const r = self.region; const inside = r[2] != 0 and r[0] + r[2] <= size[0] and r[1] + r[3] <= size[1]; return if (inside) r else .{ 0, 0, size[0], size[1] }; } }; const Harness = struct { pub const Command = Op; protocol: Protocol, /// Whether the known defects are gated (see Run.gated). gated: bool = true, 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 node = random.uintLessThan(u8, images); command.* = switch (random.uintLessThan(u8, 100)) { 0...7 => .{ .attach = .{ .node = random.uintLessThan(u8, images + 1), .scroll = random.boolean(), .index = random.uintLessThan(u8, 6) } }, 8...11 => .{ .detach = random.uintLessThan(u8, images + 1) }, 12...23 => .{ .place = .{ .node = random.uintLessThan(u8, images + 1), .x = random.int(u8), .y = random.int(u8) } }, 24...29 => .{ .size = .{ .node = node, .w = random.uintLessThan(u8, node_widths.len), .h = random.uintLessThan(u8, node_heights.len) } }, 30...34 => .{ .image = .{ .node = node, .image = random.uintLessThan(u8, image_sizes.len) } }, 35...38 => .{ .fit = .{ .node = node, .cover = random.boolean() } }, 39...43 => .{ .crop = .{ .node = node, .crop = random.uintLessThan(u8, 4) } }, 44...50 => .{ .scroll = random.uintLessThan(u8, content_height) }, 51...53 => .{ .viewport = random.uintLessThan(u8, viewports.len) }, 54...56 => .{ .resize = random.uintLessThan(u8, widths.len) }, 57...62 => .{ .screen = .{ .mode = random.enumValue(Mode), .footer = random.uintLessThan(u8, footers.len) } }, 63...66 => .{ .output = random.uintLessThan(u8, lines.len) }, 67...68 => .pause, 69...70 => .clear, else => .{ .frame = random.uintLessThan(u8, 8) == 0 }, }; } return commands; } pub fn simplify(_: *Harness, arena: std.mem.Allocator, command: Op) ![]const Op { return switch (command) { .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, .protocol = self.protocol, .gated = self.gated }; defer state.deinit(); try state.init(); 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, protocol: Protocol, session: ?c.ot_handle = null, root: c.ot_handle = undefined, term: ?Term = null, pixels: std.ArrayList(c.ot_handle) = .empty, nodes: [6]Node = @splat(.{}), /// Paint order of the root's and the scroll view's children. children: [2]std.ArrayList(u8) = .{ .empty, .empty }, mode: Mode = .main, width: u32 = widths[0], footer: u32 = footers[0], published: u32 = 0, tail: bool = false, parked: bool = false, pending: std.ArrayList(u8) = .empty, /// The screen changed under the images (screen switch or resume): every image may upload. invalidated: bool = true, /// The host cleared the terminal: the next frame is forced. cleared: bool = false, now_ns: u64 = 0, /// Known defects the walks step around; each has a row "(known, gated)" that fails once it /// is fixed: placements left on a screen the renderer switched away from, images a forced /// frame places again without sending them after the host cleared the screen, and Kitty /// images not placed again after a resize moved them. gated: bool, 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()); } fn sessionHandle(self: *const Run) *const c.ot_handle { return &self.session.?; } fn init(self: *Run) !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; var session: c.ot_handle = undefined; try ok(ot.ot_session_create(self.context, &options, &session)); self.session = session; var environment: std.ArrayList(u8) = .empty; const entries = [_][2][]const u8{ .{ "TERM", "xterm-256color" }, .{ "COLORTERM", "truecolor" } }; 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 = entries.len; renderer.byte_count = @intCast(environment.items.len); try ok(ot.ot_session_attach_renderer_with_env(self.context, self.sessionHandle(), &renderer, environment.items.ptr)); try self.resolution(); try ok(ot.ot_scene_create_node(self.context, self.sessionHandle(), c.OT_SCENE_ROOT, 1, &self.root)); const terminal = try self.arena.create(vt.Terminal); terminal.* = try .init(std.testing.io, std.testing.allocator, .{ .cols = @intCast(self.width), .rows = rows, .max_scrollback_bytes = null }); self.term = .{ .arena = self.arena, .terminal = terminal, .stream = terminal.vtStream() }; // Grapheme clustering, as the renderer assumes. self.term.?.stream.nextSlice("\x1b[?2027h"); const setup = record(c.ot_session_terminal_options); try ok(ot.ot_session_setup_terminal(self.context, self.sessionHandle(), &setup)); try self.pump(c.OT_TERMINAL_ACTIVE); for (image_sizes, 0..) |size, index| { const bytes = try self.arena.alloc(u8, size[0] * size[1] * 4); for (bytes, 0..) |*byte, at| byte.* = @truncate(at * 7 + index * 61); var handle: c.ot_handle = undefined; try ok(ot.ot_image_create_pixels(self.context, bytes.ptr, bytes.len, size[0], size[1], size[0] * 4, c.OT_IMAGE_RGBA8, c.OT_IMAGE_ALPHA_OPAQUE, &handle)); try self.pixels.append(self.arena, handle); } for (&self.nodes, 0..) |*node, index| { const kind: u32 = switch (index) { overlay => c.OT_SCENE_TEXT, scroll, spacer => c.OT_SCENE_BOX, else => c.OT_SCENE_IMAGE, }; try ok(ot.ot_scene_create_node(self.context, self.sessionHandle(), kind, @intCast(10 + index), &node.handle)); } const view_node = self.nodes[scroll].handle; var scroll_options = record(c.ot_scene_scroll_options); scroll_options.axes = c.OT_SCENE_SCROLL_Y; for (&scroll_options.bars) |*bar| { bar.thickness = 1; bar.policy = c.OT_SCENE_SCROLL_BAR_NEVER; } try ok(ot.ot_scene_set_scroll(self.context, &view_node, &scroll_options)); try self.absolute(view_node); try self.position(view_node, view[0], view[1]); try self.dimensions(view_node, view[2], viewports[1]); const spacer_node = self.nodes[spacer].handle; try self.style(spacer_node, c.OT_STYLE_DIMENSION, c.OT_DIMENSION_WIDTH, c.OT_EDGE_NONE, c.OT_UNIT_POINT, 1, c.OT_STYLE_DISABLE_FLEX_SHRINK); try self.style(spacer_node, c.OT_STYLE_DIMENSION, c.OT_DIMENSION_HEIGHT, c.OT_EDGE_NONE, c.OT_UNIT_POINT, content_height, c.OT_STYLE_DISABLE_FLEX_SHRINK); try ok(ot.ot_scene_move_node(self.context, &spacer_node, &view_node, 0)); try self.children[1].append(self.arena, spacer); try ok(ot.ot_scene_move_node(self.context, &view_node, &self.root, 0)); try self.children[0].append(self.arena, scroll); const overlay_node = self.nodes[overlay].handle; try ok(ot.ot_scene_set_text(self.context, &overlay_node, "##", 2)); try self.absolute(overlay_node); try self.dimensions(overlay_node, 2, 1); for (self.nodes[0..images], 0..) |*node, index| { node.image = @intCast(index); try self.absolute(node.handle); try self.setImage(@intCast(index)); try self.dimensions(node.handle, node.w, node.h); } // Two images at the root and one in the scroll view, the overlay above them. try self.position(self.nodes[0].handle, 1, 0); try self.attach(0, .root, 9); try self.position(self.nodes[1].handle, 14, 5); try self.attach(1, .root, 9); try self.position(self.nodes[2].handle, 1, 1); try self.attach(2, .scroll, 9); try self.position(overlay_node, 2, 1); try self.attach(overlay, .root, 9); } fn deinit(self: *Run) void { if (self.session) |*session| { _ = ot.ot_session_cancel(self.context, session); std.testing.expectEqual(c.OT_OK, ot.ot_session_destroy(self.context, session)) catch unreachable; } for (self.pixels.items) |*handle| std.testing.expectEqual(c.OT_OK, ot.ot_image_destroy(self.context, handle)) catch unreachable; if (self.term) |*term| { term.stream.deinit(); term.terminal.deinit(std.testing.allocator); } } fn style(self: *Run, node: c.ot_handle, group: u32, kind: u32, edge: u32, unit: u32, value: f32, flags: u32) !void { try ok(ot.ot_scene_set_style(self.context, &node, group, kind, edge, unit, value, flags)); } fn absolute(self: *Run, node: c.ot_handle) !void { try self.style(node, c.OT_STYLE_ENUM, c.OT_STYLE_ENUM_POSITION_TYPE, c.OT_EDGE_NONE, 0, c.OT_POSITION_ABSOLUTE, 0); } fn position(self: *Run, node: c.ot_handle, x: u32, y: u32) !void { try self.style(node, c.OT_STYLE_VALUE, c.OT_STYLE_VALUE_POSITION, c.OT_EDGE_LEFT, c.OT_UNIT_POINT, @floatFromInt(x), 0); try self.style(node, c.OT_STYLE_VALUE, c.OT_STYLE_VALUE_POSITION, c.OT_EDGE_TOP, c.OT_UNIT_POINT, @floatFromInt(y), 0); } fn dimensions(self: *Run, node: c.ot_handle, w: u32, h: u32) !void { try self.style(node, c.OT_STYLE_VALUE, c.OT_STYLE_VALUE_WIDTH, c.OT_EDGE_NONE, c.OT_UNIT_POINT, @floatFromInt(w), 0); try self.style(node, c.OT_STYLE_VALUE, c.OT_STYLE_VALUE_HEIGHT, c.OT_EDGE_NONE, c.OT_UNIT_POINT, @floatFromInt(h), 0); } fn resolution(self: *Run) !void { try ok(ot.ot_session_set_image_resolution(self.context, self.sessionHandle(), self.width, rows, self.width * cell[0], rows * cell[1])); } fn pump(self: *Run, phase: u32) !void { for (0..256) |_| { var result = record(c.ot_session_pump_result); try ok(ot.ot_session_pump(self.context, self.sessionHandle(), self.now_ns, 1, &result)); switch (result.status) { c.OT_PUMP_OUTPUT_PENDING => try self.drain(), c.OT_PUMP_WAIT_UNTIL => self.now_ns = result.deadline_ns, c.OT_PUMP_AGAIN => {}, else => { var current: u32 = 0; try ok(ot.ot_session_get_terminal_state(self.context, self.sessionHandle(), ¤t)); if (current != phase) return error.TerminalPhase; return; }, } } return error.PumpDidNotSettle; } fn drain(self: *Run) !void { var bytes: std.ArrayList(u8) = .empty; var chunk: [8192]u8 = undefined; while (true) { var ticket: c.ot_output_ticket = undefined; try ok(ot.ot_session_read_output(self.context, self.sessionHandle(), &chunk, chunk.len, &ticket)); if (ticket.byte_count == 0) break; try bytes.appendSlice(self.arena, chunk[0..ticket.byte_count]); try ok(ot.ot_session_complete_output(self.context, self.sessionHandle(), &ticket, 1)); } try self.term.?.feed(bytes.items); } fn setImage(self: *Run, slot: u8) !void { const node = &self.nodes[slot]; const protocol: u32 = if (self.protocol == .kitty) c.OT_IMAGE_PROTOCOL_KITTY else c.OT_IMAGE_PROTOCOL_SIXEL; try ok(ot.ot_scene_set_image(self.context, &node.handle, &self.pixels.items[node.image], if (node.cover) c.OT_IMAGE_COVER else c.OT_IMAGE_FILL, protocol, null)); } fn detach(self: *Run, slot: u8) !void { const node = &self.nodes[slot]; if (node.parent == .none) return; const list = &self.children[@intFromBool(node.parent == .scroll)]; _ = list.orderedRemove(std.mem.indexOfScalar(u8, list.items, slot).?); try ok(ot.ot_scene_move_node(self.context, &node.handle, null, 0)); node.parent = .none; } /// Detaches the node, then inserts it at the index among the parent's other children. fn attach(self: *Run, slot: u8, parent: Parent, index: u8) !void { try self.detach(slot); const list = &self.children[@intFromBool(parent == .scroll)]; const at = @min(index, list.items.len); const target = if (parent == .scroll) self.nodes[scroll].handle else self.root; try ok(ot.ot_scene_move_node(self.context, &self.nodes[slot].handle, &target, @intCast(at))); try list.insert(self.arena, at, slot); self.nodes[slot].parent = parent; } /// Applies one command; the name of a property it broke, or null. fn apply(self: *Run, command: Op) !?[]const u8 { switch (command) { .attach => |value| { // The overlay stays at the root. const parent: Parent = if (value.scroll and value.node < images) .scroll else .root; try self.attach(value.node, parent, value.index); model.count("attach"); }, .detach => |slot| { if (self.nodes[slot].parent == .none) return null; try self.detach(slot); model.count("detach"); }, .place => |value| { const inside = self.nodes[value.node].parent == .scroll; try self.position(self.nodes[value.node].handle, value.x % (if (inside) view[2] else self.width), value.y % (if (inside) content_height else rows)); model.count("place"); }, .size => |value| { const node = &self.nodes[value.node]; node.w = node_widths[value.w]; node.h = node_heights[value.h]; try self.dimensions(node.handle, node.w, node.h); model.count("size"); }, .image => |value| { if (self.nodes[value.node].image == value.image) return null; self.nodes[value.node].image = value.image; try self.setImage(value.node); model.count("image"); }, .fit => |value| { if (self.nodes[value.node].cover == value.cover) return null; self.nodes[value.node].cover = value.cover; try self.setImage(value.node); model.count("fit"); }, .crop => |value| { const node = &self.nodes[value.node]; if (node.crop == value.crop) return null; node.crop = value.crop; try self.setCrop(value.node); model.count("crop"); }, .scroll => |y| { var state = record(c.ot_scene_scroll_state); try ok(ot.ot_scene_scroll_to(self.context, &self.nodes[scroll].handle, 0, @floatFromInt(y), 0, &state)); model.count("scroll"); }, .viewport => |index| { try self.dimensions(self.nodes[scroll].handle, view[2], viewports[index]); model.count("viewport"); }, .resize => |index| { // A split footer resizes through the host's transition logic, outside the library. const width = widths[index]; if (width == self.width or self.mode == .split) return null; try ok(ot.ot_session_resize_renderer(self.context, self.sessionHandle(), width, rows)); try self.drain(); try self.term.?.resize(width, self.gated); self.width = width; // The main screen behind the alternate one reflows out of sight: the host gives up // the parked split footer (renderer.ts processResize). self.parked = false; try self.resolution(); model.count("resize"); }, .screen => |value| { if (value.mode == self.mode) return null; try self.switchMode(value.mode, footers[value.footer]); self.invalidated = true; 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"); }, .pause => { if (self.mode == .split) return null; try ok(ot.ot_session_suspend(self.context, self.sessionHandle())); try self.pump(c.OT_TERMINAL_SUSPENDED); model.count("suspend"); // Suspension deletes every Kitty image; Sixel pixels stay until text covers them. if (self.protocol == .kitty) { const term = &self.term.?; const key = term.terminal.screens.active_key; const graphics = term.graphics.get(key); for (graphics.placements.items) |placement| { if (self.leftover(graphics, placement)) continue; const at = term.origin(key, placement) orelse continue; if (at[1] + placement.rows > 0) return self.reportCell("suspend", @intCast(at[0]), @intCast(@max(0, at[1])), "a placement stays after suspend"); } } try ok(ot.ot_session_resume(self.context, self.sessionHandle())); try self.pump(c.OT_TERMINAL_ACTIVE); self.invalidated = true; }, .clear => { if (self.mode == .split) return null; try ok(ot.ot_session_write(self.context, self.sessionHandle(), "\x1b[H\x1b[2J", 7)); // Known defect, gated: a forced frame places Kitty images again without sending // them, and the clear freed them. The rows "... (known, gated)" keep the case. self.term.?.erase_frees = !self.gated; defer self.term.?.erase_frees = true; try self.drain(); if (self.gated and self.protocol == .kitty) model.count("gated clear"); self.cleared = true; model.count("clear"); }, .frame => |force| return self.frame(force), } return null; } fn setCrop(self: *Run, slot: u8) !void { const node = &self.nodes[slot]; node.region = cropRegion(node.crop, image_sizes[node.image]) orelse .{ 0, 0, 0, 0 }; try ok(ot.ot_scene_set_crop(self.context, &node.handle, node.region[0], node.region[1], node.region[2], node.region[3])); } fn setScreen(self: *Run, alternate: bool, trailing: []const u8) !void { try ok(ot.ot_session_set_screen(self.context, self.sessionHandle(), @intFromBool(alternate), self.width, self.height(), if (trailing.len == 0) null else trailing.ptr, @intCast(trailing.len))); try self.drain(); } 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); var offset: u32 = 0; try ok(ot.ot_session_split_control(self.context, self.sessionHandle(), &control, &offset)); } /// The host's screen transitions (renderer.ts), as the output VT model drives them. fn switchMode(self: *Run, next: Mode, footer: u32) !void { var trailing: [32]u8 = undefined; switch (self.mode) { .split => { const top = self.visible() + 1; self.pending.clearRetainingCapacity(); self.mode = next; if (next == .alternate) { try self.setScreen(true, ""); try self.splitControl(3, &.{0}); self.parked = true; } else { try self.setScreen(false, 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.published = 0; self.tail = false; } }, .alternate => if (next == .split and self.parked) { self.mode = next; try self.setScreen(false, ""); try self.splitControl(1, &.{self.pinned()}); self.parked = false; } else if (next == .split) { try self.enterSplit(footer); } else { self.mode = next; try self.setScreen(false, ""); if (self.parked) { try self.splitControl(0, &.{ 0, 0 }); try self.splitControl(3, &.{0}); self.published = 0; self.tail = false; self.parked = false; } }, .main => if (next == .split) try self.enterSplit(footer) else { self.mode = next; try self.setScreen(true, ""); }, } } fn enterSplit(self: *Run, footer: u32) !void { self.mode = .split; self.footer = footer; try self.setScreen(false, "\x1b[0m\x1b[H\x1b[2J"); try self.splitControl(0, &.{ 0, self.pinned() }); self.parked = false; self.published = 0; self.tail = false; } fn layout(self: *Run, slot: usize) !Rect { var value = record(c.ot_scene_layout); try ok(ot.ot_scene_get_layout(self.context, &self.nodes[slot].handle, c.OT_LAYOUT_PAINT, &value)); return .{ .x = @intFromFloat(value.screen_x), .y = @intFromFloat(value.screen_y), .w = @intFromFloat(value.width), .h = @intFromFloat(value.height) }; } /// The source rectangle a node shows, in its image's pixels: the crop (the whole image when /// it is unset or does not lie inside), narrowed by cover to the node's pixel aspect around /// its center. fn source(self: *const Run, slot: usize, box: Rect) [4]f64 { const node = self.nodes[slot]; const region = node.shownRegion(); var result = [4]f64{ @floatFromInt(region[0]), @floatFromInt(region[1]), @floatFromInt(region[2]), @floatFromInt(region[3]) }; if (node.cover) { const aspect = @as(f64, @floatFromInt(box.w * cell[0])) / @as(f64, @floatFromInt(box.h * cell[1])); if (result[2] / result[3] > aspect) { const w = @round(result[3] * aspect); result[0] += @floor((result[2] - w) / 2); result[2] = w; } else { const h = @round(result[2] / aspect); result[1] += @floor((result[3] - h) / 2); result[3] = h; } } return result; } /// The source pixels under the node's visible cells: from the first pixel the first cell /// touches to the last the last cell touches. fn visibleSource(self: *const Run, slot: usize, box: Rect, area: Rect) [4]i64 { const source_rect = self.source(slot, box); var result: [4]i64 = undefined; for (0..2) |axis| { const start: i64 = @intFromFloat(source_rect[axis]); const span: i64 = @intFromFloat(source_rect[axis + 2]); const cells = if (axis == 0) box.w else box.h; const from = (if (axis == 0) area.x - box.x else area.y - box.y); const to = from + (if (axis == 0) area.w else area.h); result[axis] = start + @divFloor(from * span, cells); result[axis + 2] = start + @divFloor(to * span + cells - 1, cells); } return result; } /// Paints and presents a frame, then checks what the terminal shows against the scene. fn frame(self: *Run, force: bool) !?[]const u8 { var request = record(c.ot_scene_frame_request); try ok(ot.ot_scene_paint(self.context, self.sessionHandle(), &black, 0, 0, &request)); if (request.kind != c.OT_SCENE_FRAME_DONE) return error.FrameNotDone; // Which image owns each frame cell, in paint order: later images and the overlay's // glyphs cover earlier images. const screen: Rect = .{ .w = self.width, .h = self.height() }; const clip = screen.intersect(try self.layout(scroll)); var boxes: [images]Rect = @splat(.{}); var shown: [images]Rect = @splat(.{}); const owner = try self.arena.alloc(?u8, self.width * self.height()); @memset(owner, null); var order: std.ArrayList(u8) = .empty; for (self.children[0].items) |slot| { if (slot == scroll) { for (self.children[1].items) |inner| if (inner < images) try order.append(self.arena, inner); } else try order.append(self.arena, slot); } var drawn: u32 = 0; var uploads: std.ArrayList([2]u32) = .empty; for (order.items) |slot| { const box = try self.layout(slot); const area = box.intersect(if (slot < images and self.nodes[slot].parent == .scroll) clip else screen); if (area.empty()) continue; var y = area.y; while (y < area.y + area.h) : (y += 1) { var x = area.x; while (x < area.x + area.w) : (x += 1) owner[@intCast(y * self.width + x)] = if (slot < images) slot else null; } if (slot >= images) continue; const node = &self.nodes[slot]; boxes[slot] = box; shown[slot] = area; // Kitty image ids follow paint order: an image uploads when it is new at its index, // or after the screen changed or the host cleared it (the clear freed the images). if (self.invalidated or self.cleared or node.last == null or node.last.?.index != drawn or node.last.?.image != node.image) { try uploads.append(self.arena, image_sizes[node.image]); } drawn += 1; } // A Sixel shows the content it was drawn with: one drawn before the shown part changed // is stale. for (self.nodes[0..images], 0..) |*node, slot| { if (shown[slot].empty()) { node.content = null; continue; } const content = .{ node.image, self.visibleSource(slot, boxes[slot], shown[slot]) }; if (node.content == null or !std.meta.eql(node.content.?, content)) node.fresh_from = @intCast(self.term.?.sixels.items.len); node.content = content; } const forced: u32 = @intFromBool(force or self.cleared); 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; try ok(ot.ot_buffer_create(self.context, &options, &snapshot.buffer)); var text = std.mem.zeroes(c.ot_buffer_draw_text_record); text.header = .{ .struct_size = @sizeOf(c.ot_buffer_draw_text_record), .abi_version = c.OT_CONTEXT_ABI_VERSION, .operation = c.OT_BUFFER_DRAW_TEXT, .flags = 0 }; text.foreground = .{ 255, 255, 255, 255 }; try ok(ot.ot_buffer_draw(self.context, &snapshot.buffer, null, &text.header, null, lines[line][0].ptr, @intCast(lines[line][0].len), null, 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, self.sessionHandle(), &request, &snapshots, @intCast(count), self.pinned(), forced, &status)); } else { try ok(ot.ot_scene_frame_commit(self.context, self.sessionHandle(), &request, forced, &status)); } if (status == c.OT_RENDER_FAILED or status == c.OT_RENDER_SKIPPED) return error.FrameNotPresented; try self.drain(); self.published += @intCast(self.pending.items.len); self.tail = self.tail or self.pending.items.len > 0; self.pending.clearRetainingCapacity(); var state = record(c.ot_session_renderer_state); try ok(ot.ot_session_get_renderer_state(self.context, self.sessionHandle(), &state)); if (state.image_uploads_pending != 0) return error.UploadDeferred; model.count(if (force) "force" else "frame"); self.invalidated = false; self.cleared = false; drawn = 0; for (self.nodes[0..images]) |*node| node.last = null; for (order.items) |slot| if (slot < images) { self.nodes[slot].last = if (shown[slot].empty()) null else .{ .index = drawn, .image = self.nodes[slot].image }; if (!shown[slot].empty()) drawn += 1; }; const top = if (self.mode == .split) self.visible() else 0; return switch (self.protocol) { .kitty => self.checkKitty(owner, &boxes, top, uploads.items), .sixel => self.checkSixel(owner, &shown, top), }; } /// Known defect, gated: the renderer keeps no image state per screen, so what it placed on a /// screen it switched away from stays there. The rows "... (known, gated)" keep the cases. fn leftover(self: *const Run, graphics: Graphics, placement: Placement) bool { if (!self.gated or placement.epoch == graphics.left) return false; model.count("gated left screen"); return true; } /// Explains a failure, except in the rows that expect one. fn say(self: *const Run, comptime text: []const u8, args: anytype) void { if (self.gated) std.debug.print(text, args); } fn ownerAt(self: *const Run, owner: []const ?u8, top: u32, x: usize, y: usize) ?u8 { if (y < top or y >= top + self.height()) return null; return owner[(y - top) * self.width + x]; } fn checkKitty(self: *Run, owner: []const ?u8, boxes: *const [images]Rect, top: u32, uploads: []const [2]u32) !?[]const u8 { const term = &self.term.?; defer { term.transmits.clearRetainingCapacity(); term.lost_puts = 0; } model.count("kitty checks"); if (term.lost_puts != 0) { self.say("{d} puts name an image the screen does not hold\n", .{term.lost_puts}); return "put"; } // A transmit the frame did not need: no image new at its paint index, and the screen // did not change under the images. var allowed: std.ArrayList([2]u32) = .empty; try allowed.appendSlice(self.arena, uploads); for (term.transmits.items) |size| { for (allowed.items, 0..) |candidate, index| { if (std.meta.eql(candidate, size)) { _ = allowed.swapRemove(index); break; } } else { self.say("transmit of a {d}x{d} image the frame did not need\n", .{ size[0], size[1] }); return "upload"; } } const key = term.terminal.screens.active_key; const graphics = term.graphics.get(key); for (0..rows) |y| for (0..self.width) |x| { // The placement on top shows; two at one z stack in no defined order. var covering: ?Placement = null; var at: [2]i64 = undefined; var count: u32 = 0; var tied = false; for (graphics.placements.items) |placement| { const origin = term.origin(key, placement) orelse continue; const area: Rect = .{ .x = origin[0], .y = origin[1], .w = placement.cols, .h = placement.rows }; if (!area.contains(@intCast(x), @intCast(y))) continue; if (self.leftover(graphics, placement)) continue; count += 1; if (covering) |other| { tied = tied or other.z == placement.z; if (other.z > placement.z) continue; } covering = placement; at = origin; } const slot = self.ownerAt(owner, top, x, y) orelse { if (count != 0) return self.reportCell("stale", x, y, "a placement covers a cell no image owns"); continue; }; if (count == 0) return self.reportCell("missing", x, y, "no placement covers an image's cell"); if (tied) return self.reportCell("duplicate", x, y, "two placements at one z cover one cell"); const placement = covering.?; if (!std.meta.eql(graphics.images.get(placement.image).?, image_sizes[self.nodes[slot].image])) return self.reportCell("content", x, y, "the placement shows another image"); // The source pixel at the cell's center, as the placement maps it and as the node // shows it; clipping and runs round each edge by under a pixel. const box = boxes[slot]; const want = self.source(slot, box); const fx: f64 = @floatFromInt(x); const fy: f64 = @floatFromInt(y); const shown_x = @as(f64, @floatFromInt(placement.source[0])) + (fx + 0.5 - @as(f64, @floatFromInt(at[0]))) * @as(f64, @floatFromInt(placement.source[2])) / @as(f64, @floatFromInt(placement.cols)); const shown_y = @as(f64, @floatFromInt(placement.source[1])) + (fy + 0.5 - @as(f64, @floatFromInt(at[1]))) * @as(f64, @floatFromInt(placement.source[3])) / @as(f64, @floatFromInt(placement.rows)); const want_x = want[0] + (fx + 0.5 - @as(f64, @floatFromInt(box.x))) * want[2] / @as(f64, @floatFromInt(box.w)); const want_y = want[1] + (fy - @as(f64, @floatFromInt(top)) + 0.5 - @as(f64, @floatFromInt(box.y))) * want[3] / @as(f64, @floatFromInt(box.h)); if (@abs(shown_x - want_x) > 2 or @abs(shown_y - want_y) > 2) { self.say("source pixel at the cell's center: shown {d:.1},{d:.1}, node {d:.1},{d:.1}\n", .{ shown_x, shown_y, want_x, want_y }); return self.reportCell("crop", x, y, "the placement shows another part of the image"); } }; return null; } fn checkSixel(self: *Run, owner: []const ?u8, shown: *const [images]Rect, top: u32) ?[]const u8 { const term = &self.term.?; model.count("sixel checks"); for (0..rows) |y| for (0..self.width) |x| { const generation = term.sixelAt(x, y); const slot = self.ownerAt(owner, top, x, y) orelse { if (generation != null) return self.reportCell("stale", x, y, "Sixel pixels on a cell no image owns"); continue; }; const index = generation orelse return self.reportCell("missing", x, y, "no Sixel pixels on an image's cell"); const draw = term.sixels.items[index]; const area = shown[slot]; if (draw.col != area.x or draw.row != area.y + top or draw.width != area.w * cell[0] or draw.height != area.h * cell[1]) { self.say("drawn at {d},{d}, {d}x{d} px; the image shows at {d},{d}, {d}x{d} cells\n", .{ draw.col, draw.row, draw.width, draw.height, area.x, area.y + top, area.w, area.h }); return self.reportCell("position", x, y, "the cell shows a Sixel drawn for another place or size"); } if (index < self.nodes[slot].fresh_from) return self.reportCell("content", x, y, "the cell shows a Sixel drawn before the image's content changed"); }; return null; } fn reportCell(self: *const Run, property: []const u8, x: usize, y: usize, text: []const u8) []const u8 { self.say("{s}: {s} at cell {d},{d}\n", .{ property, text, x, y }); return property; } }; test "Image placement: after any invalidation each visible image shows once at its cells, nothing stale" { for ([_]Protocol{ .kitty, .sixel }) |protocol| { var harness: Harness = .{ .protocol = protocol }; try model.check(Harness, &harness, .{ .seeds = 32, .steps = 64 }); } } test "Image placement: placements left on a screen, lost after a clear, moved by a resize (known, gated)" { const Row = struct { property: []const u8, commands: []const Op }; const known = [_]Row{ // The images placed on the main screen stay there: suspend deletes them on the alternate. .{ .property = "suspend", .commands = &.{ .{ .frame = false }, .{ .screen = .{ .mode = .alternate, .footer = 0 } }, .pause } }, // ESC[2J freed the images; the forced frame places them without sending them. .{ .property = "put", .commands = &.{ .{ .frame = false }, .clear, .{ .frame = false } } }, // Narrowing reflows the main screen and moves the placements; the frame leaves them. .{ .property = "stale", .commands = &.{ .{ .frame = false }, .{ .crop = .{ .node = 0, .crop = 3 } }, .{ .resize = 2 }, .{ .frame = false } } }, }; var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); for (known) |row| { var gated: Harness = .{ .protocol = .kitty }; try std.testing.expectEqual(null, try gated.run(arena_state.allocator(), row.commands)); var open: Harness = .{ .protocol = .kitty, .gated = false }; const failure = try open.run(arena_state.allocator(), row.commands) orelse return error.KnownDefectFixed; try std.testing.expectEqualStrings(row.property, failure.property); } }