//! The scene contract through the C ABI alone, so it can check any library that exports //! opentui.h. A seeded script of scene commands runs on a candidate Session and on a reference //! Session forced to the full path (OT_SCENE_DEBUG_FULL_FRAME). After every frame they agree //! on status, cells, hits, bytes and layouts. While no scroll node shows (its offset and bars //! depend on history), a fresh Session built from the model's log agrees on cells, hits and //! layouts too. A following scroll view pinned to its end sits at its max after every frame. //! The sibling paint-order table that Core and Rust run holds here, incremental and fresh. const std = @import("std"); const c = @import("context_abi_c"); const model = @import("model.zig"); /// The library under test. Every call goes through this namespace, the 31 functions of opentui.h /// the twin needs; another library that exports the header replaces it 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_lease_release = abi.ot_buffer_lease_release; pub const ot_context_create = abi.ot_context_create; pub const ot_context_destroy = abi.ot_context_destroy; pub const ot_scene_clear_children = abi.ot_scene_clear_children; pub const ot_scene_create_node = abi.ot_scene_create_node; pub const ot_scene_destroy_node = abi.ot_scene_destroy_node; pub const ot_scene_flush = abi.ot_scene_flush; 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_get_layout = abi.ot_scene_get_layout; pub const ot_scene_get_scroll = abi.ot_scene_get_scroll; pub const ot_scene_get_stats = abi.ot_scene_get_stats; pub const ot_scene_hit_test = abi.ot_scene_hit_test; 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_debug_flags = abi.ot_scene_set_debug_flags; pub const ot_scene_set_focus = abi.ot_scene_set_focus; pub const ot_scene_set_paint = abi.ot_scene_set_paint; 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 = abi.ot_session_attach_renderer; 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_read_output = abi.ot_session_read_output; pub const ot_session_resize_renderer = abi.ot_session_resize_renderer; }; const slots = 10; const root = slots; const detach = slots + 1; const candidate = 0; const reference = 1; const black = [4]u16{ 0, 0, 0, 255 }; const colors = [_][4]u16{ .{ 0, 0, 0, 0 }, .{ 200, 0, 0, 255 }, .{ 0, 0, 200, 255 }, .{ 0, 120, 0, 128 } }; const texts = [_][]const u8{ "", "a", "hello", "wrap me now", "\u{754c}x", "one\ntwo", "\tz" }; const sizes = [_][2]u32{ .{ 16, 6 }, .{ 12, 4 }, .{ 20, 8 } }; const Style = struct { group: u8, kind: u8, edge: u8 = c.OT_EDGE_NONE, unit: u8 = c.OT_UNIT_UNDEFINED, value: f32, flags: u8 = 0 }; const styles = [_]Style{ .{ .group = c.OT_STYLE_DIMENSION, .kind = c.OT_DIMENSION_WIDTH, .unit = c.OT_UNIT_POINT, .value = 4, .flags = c.OT_STYLE_DISABLE_FLEX_SHRINK }, .{ .group = c.OT_STYLE_DIMENSION, .kind = c.OT_DIMENSION_HEIGHT, .unit = c.OT_UNIT_POINT, .value = 2, .flags = c.OT_STYLE_DISABLE_FLEX_SHRINK }, .{ .group = c.OT_STYLE_VALUE, .kind = c.OT_STYLE_VALUE_WIDTH, .unit = c.OT_UNIT_POINT, .value = 9 }, .{ .group = c.OT_STYLE_VALUE, .kind = c.OT_STYLE_VALUE_WIDTH, .unit = c.OT_UNIT_PERCENT, .value = 50 }, .{ .group = c.OT_STYLE_VALUE, .kind = c.OT_STYLE_VALUE_WIDTH, .unit = c.OT_UNIT_AUTO, .value = 0 }, .{ .group = c.OT_STYLE_VALUE, .kind = c.OT_STYLE_VALUE_HEIGHT, .unit = c.OT_UNIT_POINT, .value = 5 }, .{ .group = c.OT_STYLE_ENUM, .kind = c.OT_STYLE_ENUM_FLEX_DIRECTION, .value = c.OT_FLEX_DIRECTION_ROW }, .{ .group = c.OT_STYLE_ENUM, .kind = c.OT_STYLE_ENUM_FLEX_DIRECTION, .value = c.OT_FLEX_DIRECTION_COLUMN }, .{ .group = c.OT_STYLE_ENUM, .kind = c.OT_STYLE_ENUM_POSITION_TYPE, .value = c.OT_POSITION_ABSOLUTE }, .{ .group = c.OT_STYLE_ENUM, .kind = c.OT_STYLE_ENUM_POSITION_TYPE, .value = c.OT_POSITION_RELATIVE }, .{ .group = c.OT_STYLE_VALUE, .kind = c.OT_STYLE_VALUE_POSITION, .edge = c.OT_EDGE_LEFT, .unit = c.OT_UNIT_POINT, .value = 2 }, .{ .group = c.OT_STYLE_VALUE, .kind = c.OT_STYLE_VALUE_POSITION, .edge = c.OT_EDGE_TOP, .unit = c.OT_UNIT_POINT, .value = 1 }, .{ .group = c.OT_STYLE_VALUE, .kind = c.OT_STYLE_VALUE_PADDING, .edge = c.OT_EDGE_ALL, .unit = c.OT_UNIT_POINT, .value = 1 }, .{ .group = c.OT_STYLE_VALUE, .kind = c.OT_STYLE_VALUE_MARGIN, .edge = c.OT_EDGE_LEFT, .unit = c.OT_UNIT_POINT, .value = 1 }, .{ .group = c.OT_STYLE_ENUM, .kind = c.OT_STYLE_ENUM_OVERFLOW, .value = c.OT_OVERFLOW_HIDDEN }, .{ .group = c.OT_STYLE_ENUM, .kind = c.OT_STYLE_ENUM_OVERFLOW, .value = c.OT_OVERFLOW_VISIBLE }, .{ .group = c.OT_STYLE_ENUM, .kind = c.OT_STYLE_ENUM_DISPLAY, .value = c.OT_DISPLAY_NONE }, .{ .group = c.OT_STYLE_ENUM, .kind = c.OT_STYLE_ENUM_DISPLAY, .value = c.OT_DISPLAY_FLEX }, .{ .group = c.OT_STYLE_FLOAT, .kind = c.OT_STYLE_FLOAT_FLEX_GROW, .value = 1 }, .{ .group = c.OT_STYLE_FLOAT, .kind = c.OT_STYLE_FLOAT_FLEX_SHRINK, .value = 0 }, }; /// Node operands are raw draws that pick() maps onto the live slots when the script runs, so /// a shrunk script stays meaningful. const Op = union(enum) { create: struct { text: bool }, destroy: u8, move: struct { node: u8, parent: u8, index: u8 }, clear: u8, paint: struct { node: u8, seed: u32 }, flush: struct { node: u8, seed: u32 }, style: struct { node: u8, style: u8 }, text: struct { node: u8, text: u8 }, focus: struct { node: u8, focused: bool }, scroll: struct { node: u8, culling: bool, bars: u8 }, /// Makes a node taller than a scroll view and appends it to the view's content. fill: struct { node: u8, child: u8 }, scroll_to: struct { node: u8, y: f64, reapply: bool }, resize: u8, frame, }; /// What the fresh Session replays for a node, in order. const Setter = union(enum) { paint: u32, flush: u32, style: u8, text: u8, scroll: Scroll }; const Scroll = struct { culling: bool, bars: u8 }; /// A view that follows its bottom and scrolls only vertically. fn scrollOf(value: Scroll) c.ot_scene_scroll_options { var options = record(c.ot_scene_scroll_options); options.axes = c.OT_SCENE_SCROLL_Y; options.follow = c.OT_SCENE_SCROLL_FOLLOW_BOTTOM; options.culling = @intFromBool(value.culling); for (&options.bars) |*bar| bar.thickness = 1; options.bars[1].policy = value.bars; options.bars[1].track_background = colors[2]; return options; } /// Styles a scroll view and its content use: 2 rows high (no shrink), and 5 rows high. const view_height = 1; const tall = 5; const Node = struct { handles: [2]c.ot_handle, text: bool, num: u32, parent: ?usize = null, log: std.ArrayList(Setter) = .empty, scroll: ?Scroll = null, /// A following view whose last explicit scroll (or none) went to its end. pinned: bool = false, hidden: bool = false, }; 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; } } fn paintOf(seed: u32) c.ot_scene_paint_options { var prng = std.Random.DefaultPrng.init(seed); const random = prng.random(); var paint = record(c.ot_scene_paint_options); paint.z_index = random.intRangeAtMost(i32, -1, 2); paint.opacity = if (random.uintLessThan(u8, 4) == 0) 0.5 else 1; paint.translate_x = @floatFromInt(random.intRangeAtMost(i32, -1, 1) * @intFromBool(random.boolean())); paint.translate_y = @floatFromInt(random.intRangeAtMost(i32, -1, 1) * @intFromBool(random.boolean())); paint.border_sides = if (random.boolean()) 15 else random.uintLessThan(u32, 16); paint.should_fill = @intFromBool(random.boolean()); paint.background = colors[random.uintLessThan(usize, colors.len)]; paint.border_color = colors[random.uintLessThan(usize, colors.len)]; paint.border_style = random.uintLessThan(u32, 4); paint.focusable = @intFromBool(random.boolean()); paint.focused_border_color = .{ 0, 170, 255, 255 }; return paint; } /// One staged property record: z, background, both, or a style. fn flushOf(bytes: *[48]u8, node: c.ot_handle, seed: u32) []const u8 { @memset(bytes, 0); var payload: [16]u8 = @splat(0); const z: i32 = @as(i32, @intCast(seed % 3)) - 1; const background = colors[(seed / 4) % colors.len]; const style = styles[(seed / 4) % styles.len]; const property: c.ot_scene_style_property = .{ .group = style.group, .kind = style.kind, .edge = style.edge, .unit = style.unit, .flags = style.flags, .value = style.value, .reserved = 0 }; @memcpy(payload[0..4], std.mem.asBytes(&z)); @memcpy(payload[4..12], std.mem.asBytes(&background)); const fields: u32, const length: usize, const offset: usize = switch (seed % 4) { 0 => .{ c.OT_SCENE_PROPERTY_Z_INDEX, 4, 0 }, 1 => .{ c.OT_SCENE_PROPERTY_BACKGROUND, 8, 4 }, 2 => .{ c.OT_SCENE_PROPERTY_Z_INDEX | c.OT_SCENE_PROPERTY_BACKGROUND, 12, 0 }, else => blk: { @memcpy(payload[0..16], std.mem.asBytes(&property)); break :blk .{ c.OT_SCENE_PROPERTY_STYLE, 16, 0 }; }, }; const size = std.mem.alignForward(u32, 24 + @as(u32, @intCast(length)), 8); const header: c.ot_scene_property_update = .{ .node = node, .fields = fields, .size_bytes = size }; @memcpy(bytes[0..24], std.mem.asBytes(&header)); @memcpy(bytes[24..][0..length], payload[offset..][0..length]); return bytes[0..size]; } /// Whether a flush seed or style index sets DISPLAY, and to NONE. fn display(style: Style) ?bool { if (style.group != c.OT_STYLE_ENUM or style.kind != c.OT_STYLE_ENUM_DISPLAY) return null; return style.value == c.OT_DISPLAY_NONE; } /// The cells, hits and bytes of one presented frame. const Frame = struct { chars: []u32, attributes: []u32, /// Foregrounds, then backgrounds. colors: [][4]u16, hits: []u32, bytes: []u8, fn sameCells(self: Frame, other: Frame) bool { return std.mem.eql(u32, self.chars, other.chars) and std.mem.eql(u32, self.attributes, other.attributes) and std.mem.eql(u8, std.mem.sliceAsBytes(self.colors), std.mem.sliceAsBytes(other.colors)); } }; const Scene = struct { context: *ot.ContextHandle, session: c.ot_handle, root: c.ot_handle, fn init(context: *ot.ContextHandle, size: [2]u32) !Scene { var options = record(c.ot_session_options); options.chunk_size = 8192; options.span_capacity = 8; options.max_bytes = 65536; var self: Scene = .{ .context = context, .session = undefined, .root = undefined }; try ok(ot.ot_session_create(context, &options, &self.session)); errdefer self.deinit(); var renderer = record(c.ot_session_renderer_options); renderer.width = size[0]; renderer.height = size[1]; renderer.remote = 1; try ok(ot.ot_session_attach_renderer(context, &self.session, &renderer)); try ok(ot.ot_scene_create_node(context, &self.session, c.OT_SCENE_ROOT, 1, &self.root)); return self; } fn deinit(self: Scene) void { std.testing.expectEqual(c.OT_OK, ot.ot_session_destroy(self.context, &self.session)) catch unreachable; } /// Paints, copies the draft's cells, presents it, and reads every cell's hit. A frame lease /// would end retained paint, so the draft is copied into a buffer of its size. fn present(self: Scene, arena: std.mem.Allocator, size: [2]u32) !Frame { var request = record(c.ot_scene_frame_request); try ok(ot.ot_scene_paint(self.context, &self.session, &black, 1, 0, &request)); if (request.kind != c.OT_SCENE_FRAME_DONE) return error.FrameNotDone; var options = record(c.ot_buffer_options); options.width = size[0]; options.height = size[1]; var copy: c.ot_handle = undefined; try ok(ot.ot_buffer_create(self.context, &options, ©)); defer std.testing.expectEqual(c.OT_OK, ot.ot_buffer_destroy(self.context, ©)) catch unreachable; try ok(ot.ot_scene_frame_copy_buffer(self.context, &self.session, &request, ©)); var lease = record(c.ot_buffer_lease_snapshot); try ok(ot.ot_buffer_acquire_lease(self.context, ©, &lease)); const count = lease.width * lease.height; var frame: Frame = .{ .chars = try arena.dupe(u32, @as([*]const u32, @ptrFromInt(lease.char_ptr))[0..count]), .attributes = try arena.dupe(u32, @as([*]const u32, @ptrFromInt(lease.attributes_ptr))[0..count]), .colors = try arena.alloc([4]u16, count * 2), .hits = try arena.alloc(u32, count), .bytes = &.{}, }; @memcpy(frame.colors[0..count], @as([*]const [4]u16, @ptrFromInt(lease.fg_ptr))[0..count]); @memcpy(frame.colors[count..], @as([*]const [4]u16, @ptrFromInt(lease.bg_ptr))[0..count]); try ok(ot.ot_buffer_lease_release(self.context, &lease.lease)); var status: u32 = undefined; try ok(ot.ot_scene_frame_commit(self.context, &self.session, &request, 0, &status)); if (status == c.OT_RENDER_FAILED or status == c.OT_RENDER_SKIPPED) return error.FrameNotPresented; var bytes: std.ArrayList(u8) = .empty; var chunk: [4096]u8 = undefined; while (true) { var ticket: c.ot_output_ticket = undefined; try ok(ot.ot_session_read_output(self.context, &self.session, &chunk, chunk.len, &ticket)); if (ticket.byte_count == 0) break; try bytes.appendSlice(arena, chunk[0..ticket.byte_count]); try ok(ot.ot_session_complete_output(self.context, &self.session, &ticket, 1)); } frame.bytes = bytes.items; for (frame.hits, 0..) |*hit, cell| try ok(ot.ot_scene_hit_test(self.context, &self.session, @intCast(cell % lease.width), @intCast(cell / lease.width), hit)); return frame; } }; const Harness = struct { pub const Command = Op; 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.int(u8); command.* = switch (random.uintLessThan(u8, 100)) { 0...9 => .{ .create = .{ .text = random.uintLessThan(u8, 3) == 0 } }, 10...12 => .{ .destroy = node }, 13...26 => .{ .move = .{ .node = node, .index = random.uintLessThan(u8, 4), .parent = switch (random.uintLessThan(u8, 10)) { 0...4 => root, 5 => detach, else => random.uintLessThan(u8, slots), } } }, 27...28 => .{ .clear = if (random.boolean()) root else random.uintLessThan(u8, slots) }, 29...37 => .{ .paint = .{ .node = node, .seed = random.int(u32) } }, 38...44 => .{ .flush = .{ .node = node, .seed = random.int(u32) } }, 45...59 => .{ .style = .{ .node = node, .style = random.uintLessThan(u8, styles.len) } }, 60...66 => .{ .text = .{ .node = node, .text = random.uintLessThan(u8, texts.len) } }, 67...69 => .{ .focus = .{ .node = node, .focused = random.uintLessThan(u8, 4) != 0 } }, 70...72 => .{ .scroll = .{ .node = node, .culling = random.boolean(), .bars = random.uintLessThan(u8, 3) } }, 73...77 => .{ .scroll_to = .{ .node = node, .reapply = random.boolean(), .y = switch (random.uintLessThan(u8, 3)) { 0 => std.math.inf(f64), else => @floatFromInt(random.uintLessThan(u8, 4)), } } }, 78...79 => .{ .resize = random.uintLessThan(u8, sizes.len) }, 80...85 => .{ .fill = .{ .node = node, .child = random.int(u8) } }, else => .frame, }; } return commands; } pub fn simplify(_: *Harness, arena: std.mem.Allocator, command: Op) ![]const Op { return switch (command) { .paint => |value| if (value.seed != 0) try arena.dupe(Op, &.{.{ .paint = .{ .node = value.node, .seed = 0 } }}) else &.{}, .move => |value| if (value.index != 0) try arena.dupe(Op, &.{.{ .move = .{ .node = value.node, .parent = value.parent, .index = 0 } }}) else &.{}, .text => |value| if (value.text > 1) try arena.dupe(Op, &.{.{ .text = .{ .node = value.node, .text = 1 } }}) else &.{}, else => &.{}, }; } pub fn format(_: *Harness, command: Op, writer: *std.Io.Writer) void { writer.print("{any}", .{command}) catch {}; } pub fn run(_: *Harness, arena: std.mem.Allocator, commands: []const Op) !?model.Failure { var options = record(c.ot_context_options); options.object_capacity = 256; 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, .scenes = .{ try Scene.init(context.?, sizes[0]), try Scene.init(context.?, sizes[0]) } }; try ok(ot.ot_scene_set_debug_flags(context.?, &state.scenes[reference].session, c.OT_SCENE_DEBUG_FULL_FRAME)); 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, scenes: [2]Scene, nodes: [slots]?Node = @splat(null), /// Children in order; index root holds the root's. children: [slots + 1]std.ArrayList(usize) = @splat(.empty), focused: ?usize = null, size: [2]u32 = sizes[0], next_num: u32 = 10, fn handle(self: *const Run, slot: usize, twin: usize) c.ot_handle { return if (slot == root) self.scenes[twin].root else self.nodes[slot].?.handles[twin]; } /// The draw-th live slot, or null when none lives. fn pick(self: *const Run, draw: u8) ?usize { var live: usize = 0; for (self.nodes) |node| live += @intFromBool(node != null); if (live == 0) return null; var left = draw % live; for (self.nodes, 0..) |node, slot| if (node != null) { if (left == 0) return slot; left -= 1; }; unreachable; } /// The draw-th live slot that passes the test, or null when none does. fn pickWhere(self: *const Run, draw: u8, comptime passes: fn (*const Run, usize) bool) ?usize { var count: usize = 0; for (self.nodes, 0..) |node, slot| count += @intFromBool(node != null and passes(self, slot)); if (count == 0) return null; var left = draw % count; for (self.nodes, 0..) |node, slot| if (node != null and passes(self, slot)) { if (left == 0) return slot; left -= 1; }; unreachable; } fn isScroll(self: *const Run, slot: usize) bool { return self.nodes[slot].?.scroll != null; } /// A box that can become a scroll node: no children, not one already. fn isEmptyBox(self: *const Run, slot: usize) bool { const node = self.nodes[slot].?; return !node.text and node.scroll == null and self.children[slot].items.len == 0; } /// Whether the node is attached under the root (and, with shown, no node on the way is hidden). fn attached(self: *const Run, slot: usize, shown: bool) bool { var cursor: usize = slot; for (0..slots + 1) |_| { if (cursor == root) return true; const node = self.nodes[cursor].?; if (shown and node.hidden) return false; cursor = node.parent orelse return false; } return false; } fn detachModel(self: *Run, slot: usize) void { const node = &self.nodes[slot].?; if (node.parent) |parent| { const list = &self.children[parent]; _ = list.orderedRemove(std.mem.indexOfScalar(usize, list.items, slot).?); } node.parent = null; } /// Runs one call on the node in both twins; null when their statuses differ. fn both(self: *Run, comptime call: anytype, slot: usize, extra: anytype) ?c.ot_status { var statuses: [2]c.ot_status = undefined; for (&statuses, 0..) |*status, twin| { const node = self.handle(slot, twin); status.* = @call(.auto, call, .{ self.context, &node } ++ extra); } return if (statuses[0] == statuses[1]) statuses[0] else null; } /// Applies one command; the name of a property it broke, or null. fn apply(self: *Run, command: Op) !?[]const u8 { switch (command) { .create => |value| { const slot = for (self.nodes, 0..) |node, index| { if (node == null) break index; } else return null; var handles: [2]c.ot_handle = undefined; for (&handles, self.scenes) |*out, scene| try ok(ot.ot_scene_create_node(self.context, &scene.session, if (value.text) c.OT_SCENE_TEXT else c.OT_SCENE_BOX, self.next_num, out)); self.nodes[slot] = .{ .handles = handles, .text = value.text, .num = self.next_num }; self.children[slot] = .empty; self.next_num += 1; model.count("create"); }, .destroy => |draw| { const slot = self.pick(draw) orelse return null; try ok(self.both(ot.ot_scene_destroy_node, slot, .{}) orelse return "status"); self.detachModel(slot); for (self.children[slot].items) |child| self.nodes[child].?.parent = null; self.nodes[slot] = null; if (self.focused == slot) self.focused = null; model.count("destroy"); }, .move => |value| { const slot = self.pick(value.node) orelse return null; const parent: ?usize = switch (value.parent) { root => root, detach => null, else => self.pick(value.parent) orelse return null, }; return self.moveTo(slot, parent, value.index); }, .clear => |draw| { const slot = if (draw == root) root else self.pick(draw) orelse return null; try ok(self.both(ot.ot_scene_clear_children, slot, .{}) orelse return "status"); for (self.children[slot].items) |child| self.nodes[child].?.parent = null; self.children[slot].clearRetainingCapacity(); model.count("clear"); }, .paint => |value| { const slot = self.pick(value.node) orelse return null; const paint = paintOf(value.seed); return self.setter(slot, .{ .paint = value.seed }, self.both(ot.ot_scene_set_paint, slot, .{&paint})); }, .flush => |value| { const slot = self.pick(value.node) orelse return null; var statuses: [2]c.ot_status = undefined; for (&statuses, 0..) |*status, twin| { var bytes: [48]u8 = undefined; const input = flushOf(&bytes, self.handle(slot, twin), value.seed); var applied: u32 = 0; status.* = ot.ot_scene_flush(self.context, input.ptr, @intCast(input.len), &applied); } return self.setter(slot, .{ .flush = value.seed }, if (statuses[0] == statuses[1]) statuses[0] else null); }, .style => |value| return self.style(self.pick(value.node) orelse return null, value.style), .text => |value| { const slot = self.pick(value.node) orelse return null; const bytes = texts[value.text]; return self.setter(slot, .{ .text = value.text }, self.both(ot.ot_scene_set_text, slot, .{ bytes.ptr, @as(u32, @intCast(bytes.len)) })); }, .focus => |value| { const slot = self.pick(value.node) orelse return null; const status = self.both(ot.ot_scene_set_focus, slot, .{@as(u32, @intFromBool(value.focused))}) orelse return "status"; if (status != c.OT_OK) return null; if (value.focused) self.focused = slot else if (self.focused == slot) self.focused = null; model.count("focus"); }, .scroll => |value| { const slot = self.pickWhere(value.node, isEmptyBox) orelse return null; const scroll: Scroll = .{ .culling = value.culling, .bars = value.bars }; const options = scrollOf(scroll); if (try self.setter(slot, .{ .scroll = scroll }, self.both(ot.ot_scene_set_scroll, slot, .{&options}))) |property| return property; const node = &self.nodes[slot].?; if (node.scroll == null) return null; // stuck starts true. node.pinned = true; if (try self.style(slot, view_height)) |property| return property; if (node.parent == null) return self.moveTo(slot, root, 0); }, .fill => |value| { const view = self.pickWhere(value.node, isScroll) orelse return null; const slot = self.pick(value.child) orelse return null; if (try self.style(slot, tall)) |property| return property; return self.moveTo(slot, view, @intCast(self.children[view].items.len)); }, .scroll_to => |value| { const slot = self.pickWhere(value.node, isScroll) orelse return null; const flags: u32 = if (value.reapply) c.OT_SCENE_SCROLL_REAPPLY else 0; const status = self.both(ot.ot_scene_scroll_to, slot, .{ 0, value.y, flags, null }) orelse return "status"; if (status != c.OT_OK) return null; // Only a scroll to the end is known to leave the view stuck. self.nodes[slot].?.pinned = std.math.isInf(value.y); model.count("scroll_to"); }, .resize => |index| { for (self.scenes) |scene| try ok(ot.ot_session_resize_renderer(self.context, &scene.session, sizes[index][0], sizes[index][1])); self.size = sizes[index]; model.count("resize"); }, .frame => return self.frame(), } return null; } fn style(self: *Run, slot: usize, index: u8) !?[]const u8 { const value = styles[index]; return self.setter(slot, .{ .style = index }, self.both(ot.ot_scene_set_style, slot, .{ value.group, value.kind, value.edge, value.unit, value.value, value.flags })); } /// Moves a node in both twins and, when they accept, in the model. fn moveTo(self: *Run, slot: usize, parent: ?usize, index: u8) !?[]const u8 { var statuses: [2]c.ot_status = undefined; for (&statuses, 0..) |*status, twin| { const node = self.handle(slot, twin); const target = if (parent) |p| self.handle(p, twin) else undefined; status.* = ot.ot_scene_move_node(self.context, &node, if (parent != null) &target else null, index); } if (statuses[0] != statuses[1]) return "status"; if (statuses[0] != c.OT_OK) return null; self.detachModel(slot); if (parent) |p| { try self.children[p].insert(self.arena, index, slot); self.nodes[slot].?.parent = p; } model.count(if (parent == null) "detach" else "move"); return null; } /// Logs an accepted setter for the fresh Session. fn setter(self: *Run, slot: usize, value: Setter, status: ?c.ot_status) !?[]const u8 { if ((status orelse return "status") != c.OT_OK) return null; const node = &self.nodes[slot].?; try node.log.append(self.arena, value); const hides = switch (value) { .style => |index| display(styles[index]), .flush => |seed| if (seed % 4 == 3) display(styles[(seed / 4) % styles.len]) else null, else => null, }; if (hides) |hidden| node.hidden = hidden; if (value == .scroll) node.scroll = value.scroll; model.count(@tagName(value)); return null; } /// The public layout of every attached (or shown) node in one twin, zeros for the others. fn layouts(self: *const Run, handles: anytype, shown: bool, out: *[slots]c.ot_scene_layout) !void { for (out, 0..) |*layout, slot| { layout.* = record(c.ot_scene_layout); if (self.nodes[slot] == null or !self.attached(slot, shown)) continue; try ok(ot.ot_scene_get_layout(self.context, &handles[slot], c.OT_LAYOUT_PUBLIC, layout)); } } fn twinHandles(self: *const Run, twin: usize) [slots]c.ot_handle { var out: [slots]c.ot_handle = undefined; for (self.nodes, &out) |node, *slot| if (node) |value| { slot.* = value.handles[twin]; }; return out; } fn frame(self: *Run) !?[]const u8 { const frames = [2]Frame{ try self.scenes[candidate].present(self.arena, self.size), try self.scenes[reference].present(self.arena, self.size) }; model.count("frame"); // Frames the candidate painted on the incremental path: some or no rows repainted. var stats = record(c.ot_scene_stats); try ok(ot.ot_scene_get_stats(self.context, &self.scenes[candidate].session, &stats)); if (stats.full_path_reasons == 0) model.count(if (stats.damage_rows == 0) "unchanged" else "partial"); if (!frames[0].sameCells(frames[1])) return "frame"; if (!std.mem.eql(u32, frames[0].hits, frames[1].hits)) return "hits"; if (!std.mem.eql(u8, frames[0].bytes, frames[1].bytes)) return "bytes"; var public: [2][slots]c.ot_scene_layout = undefined; for (&public, 0..) |*out, twin| try self.layouts(self.twinHandles(twin), false, out); if (!std.meta.eql(public[0], public[1])) return "layout"; for (self.nodes, 0..) |maybe, slot| { const node = maybe orelse continue; if (node.scroll == null or !node.pinned or !self.attached(slot, true)) continue; var state = record(c.ot_scene_scroll_state); try ok(ot.ot_scene_get_scroll(self.context, &node.handles[candidate], &state)); model.count("follow"); if (state.max[1] > 0) model.count("follow scrolled"); if (state.stuck != 1 or state.offset[1] != state.max[1]) return "follow"; } for (0..slots) |slot| if (self.nodes[slot] != null and self.inScroll(slot) and self.attached(slot, false)) { model.count("scroll layout"); break; }; return self.fresh(frames[0]); } /// Whether a scroll node lies strictly above the node. fn inScroll(self: *const Run, slot: usize) bool { var cursor = self.nodes[slot].?.parent; for (0..slots) |_| { const value = cursor orelse return false; if (value == root) return false; if (self.nodes[value].?.scroll != null) return true; cursor = self.nodes[value].?.parent; } return false; } /// A fresh Session built from the model's tree and setter logs shows the same frame. With a /// scroll view attached, only the layout: its offset is history, and so are auto bars. fn fresh(self: *Run, expected: Frame) !?[]const u8 { var scrolls = false; for (self.nodes, 0..) |node, slot| if (node != null and node.?.scroll != null and self.attached(slot, false)) { if (node.?.scroll.?.bars == c.OT_SCENE_SCROLL_BAR_AUTO) return null; scrolls = true; }; const scene = try Scene.init(self.context, self.size); defer scene.deinit(); var handles: [slots]c.ot_handle = undefined; if (!try self.build(scene, root, &handles)) return "fresh"; if (self.focused) |slot| if (self.attached(slot, false)) try ok(ot.ot_scene_set_focus(self.context, &handles[slot], 1)); const got = try scene.present(self.arena, self.size); model.count(if (scrolls) "fresh scroll layout" else "fresh"); if (!scrolls and (!got.sameCells(expected) or !std.mem.eql(u32, got.hits, expected.hits))) return "fresh frame"; // A hidden node reads the geometry of its last solve, which a fresh scene never had. var public: [2][slots]c.ot_scene_layout = undefined; try self.layouts(self.twinHandles(candidate), true, &public[0]); try self.layouts(handles, true, &public[1]); // Screen positions inside a scroll view move with its offset. if (scrolls) for (&public) |*twin| for (twin) |*layout| { layout.screen_x = 0; layout.screen_y = 0; }; if (!std.meta.eql(public[0], public[1])) return "fresh layout"; return null; } /// Creates the parent's children in the fresh scene, replays their logs, and attaches them. fn build(self: *const Run, scene: Scene, parent: usize, handles: *[slots]c.ot_handle) !bool { for (self.children[parent].items, 0..) |slot, index| { const node = self.nodes[slot].?; try ok(ot.ot_scene_create_node(self.context, &scene.session, if (node.text) c.OT_SCENE_TEXT else c.OT_SCENE_BOX, node.num, &handles[slot])); for (node.log.items) |value| { const status = switch (value) { .paint => |seed| ot.ot_scene_set_paint(self.context, &handles[slot], &paintOf(seed)), .flush => |seed| status: { var bytes: [48]u8 = undefined; const input = flushOf(&bytes, handles[slot], seed); var applied: u32 = 0; break :status ot.ot_scene_flush(self.context, input.ptr, @intCast(input.len), &applied); }, .style => |i| ot.ot_scene_set_style(self.context, &handles[slot], styles[i].group, styles[i].kind, styles[i].edge, styles[i].unit, styles[i].value, styles[i].flags), .text => |i| ot.ot_scene_set_text(self.context, &handles[slot], texts[i].ptr, @intCast(texts[i].len)), .scroll => |options| ot.ot_scene_set_scroll(self.context, &handles[slot], &scrollOf(options)), }; if (status != c.OT_OK) return false; } const target = if (parent == root) scene.root else handles[parent]; try ok(ot.ot_scene_move_node(self.context, &handles[slot], &target, @intCast(index))); if (!try self.build(scene, slot, handles)) return false; } return true; } }; test "Scene ABI: an incremental frame equals the full path and a fresh scene" { var harness: Harness = .{}; try model.check(Harness, &harness, .{ .seeds = 64, .steps = 128 }); } test "Scene ABI: sibling paint order and hits match the shared table, incremental and fresh" { const Row = struct { name: []const u8, before: []const u8, key: []const u8, after: []const u8, frame: []const u8, reparent: bool = false, raised: ?[]const u8 = null }; var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const rows = try std.json.parseFromSliceLeaky([]const Row, arena, @embedFile("sibling_paint_order"), .{}); try std.testing.expect(rows.len > 0); for (rows) |row| { for ([_]bool{ true, false }) |fresh| { var options = record(c.ot_context_options); options.object_capacity = 64; options.render_cells_max = 64; 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; const scene = try Scene.init(context.?, .{ 3, 1 }); defer scene.deinit(); var nodes: [3]c.ot_handle = undefined; for (&nodes, "ABC", 0..) |*node, key, index| { const width: u32 = @intCast(3 - index); try ok(ot.ot_scene_create_node(context.?, &scene.session, c.OT_SCENE_TEXT, @intCast(10 + index), node)); try ok(ot.ot_scene_set_text(context.?, node, &[3]u8{ key, key, key }, width)); try ok(ot.ot_scene_set_style(context.?, node, c.OT_STYLE_ENUM, c.OT_STYLE_ENUM_POSITION_TYPE, 0, 0, c.OT_POSITION_ABSOLUTE, 0)); try ok(ot.ot_scene_set_style(context.?, node, c.OT_STYLE_VALUE, c.OT_STYLE_VALUE_WIDTH, 0, c.OT_UNIT_POINT, @floatFromInt(width), 0)); try ok(ot.ot_scene_set_style(context.?, node, c.OT_STYLE_VALUE, c.OT_STYLE_VALUE_HEIGHT, 0, c.OT_UNIT_POINT, 1, 0)); if (row.raised != null and row.raised.?[0] == key) { var bytes: [48]u8 = undefined; // Seed 2 sets z 1 and a transparent background. const input = flushOf(&bytes, node.*, 2); var applied: u32 = 0; try ok(ot.ot_scene_flush(context.?, input.ptr, @intCast(input.len), &applied)); } } const keyed = struct { fn of(list: *[3]c.ot_handle, key: u8) *const c.ot_handle { return &list[std.mem.indexOfScalar(u8, "ABC", key).?]; } }.of; const offset: u32 = @intFromBool(row.reparent); if (row.reparent) { var other: c.ot_handle = undefined; try ok(ot.ot_scene_create_node(context.?, &scene.session, c.OT_SCENE_BOX, 20, &other)); try ok(ot.ot_scene_set_style(context.?, &other, c.OT_STYLE_VALUE, c.OT_STYLE_VALUE_WIDTH, 0, c.OT_UNIT_POINT, 0, 0)); try ok(ot.ot_scene_set_style(context.?, &other, c.OT_STYLE_VALUE, c.OT_STYLE_VALUE_HEIGHT, 0, c.OT_UNIT_POINT, 0, 0)); try ok(ot.ot_scene_move_node(context.?, &other, &scene.root, 0)); if (!fresh) try ok(ot.ot_scene_move_node(context.?, keyed(&nodes, row.key[0]), &other, 0)); } for (if (fresh) row.after else row.before, 0..) |key, index| try ok(ot.ot_scene_move_node(context.?, keyed(&nodes, key), &scene.root, offset + @as(u32, @intCast(index)))); if (!fresh) { _ = try scene.present(arena, .{ 3, 1 }); const at: u32 = @intCast(std.mem.indexOfScalar(u8, row.after, row.key[0]).?); try ok(ot.ot_scene_move_node(context.?, keyed(&nodes, row.key[0]), &scene.root, offset + at)); } const frame = try scene.present(arena, .{ 3, 1 }); var seen: [2][3]u8 = undefined; for (0..3) |x| { seen[0][x] = @intCast(frame.chars[x]); seen[1][x] = if (frame.hits[x] >= 10 and frame.hits[x] < 13) "ABC"[frame.hits[x] - 10] else '?'; } for (seen) |observed| std.testing.expectEqualStrings(row.frame, &observed) catch |err| { std.debug.print("sibling paint order row '{s}', fresh {}\n", .{ row.name, fresh }); return err; }; } } }