diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-09 00:52:52 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-09 01:28:28 -0300 |
| commit | 5157579ff7f9ae0cfc3c7629e953da05bce340fc (patch) | |
| tree | 02147789efdcea998981efcfe05d4bcb3e9bb7b0 /src/gui/gui.zig | |
| parent | 4c4b9bf54d77dbc0f9f4e2619746908e501c6001 (diff) | |
| download | pardes-5157579ff7f9ae0cfc3c7629e953da05bce340fc.tar.gz pardes-5157579ff7f9ae0cfc3c7629e953da05bce340fc.zip | |
tests: at the end of their files: every top-level test block of the 46 files that had one mid-file (the locality analysis's 45 and test/hxdiff.zig; gui.zig, macos.zig, look, host_io, 9p_io, terminal, tui, mouse, fs, replica, layout among them, 11,429 test lines), with the functions only tests call, moved after the file's code in their order, a mechanical move (.scratch/suites/tests_to_end.py), zig fmt'd; the unit suites pass as before (tui 1486/1487, gui 1536/1537, core 956/956 on both), macos.zig only parse-checked here
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge
Diffstat (limited to 'src/gui/gui.zig')
| -rw-r--r-- | src/gui/gui.zig | 4358 |
1 files changed, 2179 insertions, 2179 deletions
diff --git a/src/gui/gui.zig b/src/gui/gui.zig index b7ba1fb7..212fe5ad 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -198,36 +198,6 @@ comptime { @export(&font_heap.free, .{ .name = "ui_free" }); } -test "FreeType and HarfBuzz allocate from the gui allocator and give it all back" { - // HarfBuzz's process-wide objects come from the default heap, as in runNative. - const primer = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - c.ui_font_prime(primer); - c.ui_font_free(primer); - font_allocator = std.testing.allocator; - defer font_allocator = std.heap.smp_allocator; - - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var mask: [64 * 64]u8 = undefined; - try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, 27, c.ui_font_glyph(font, 'g'), 1, &mask, 64, 32, 48, 0, 32, 30)); - try std.testing.expectEqual(@as(c_int, 0), c.ui_font_substitutes(font, c.ui_font_glyph(font, '-'))); - - // A font with ligatures runs the whole HarfBuzz pass. - const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); - defer std.testing.allocator.free(bytes); - const maple = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; - defer c.ui_font_free(maple); - var cell_w: c_int = 0; - var cell_h: c_int = 0; - var ascent: c_int = 0; - c.ui_font_cell_metrics(maple, 27, &cell_w, &cell_h, &ascent); - const text = [_]u32{ 'a', '-', '>', 'b', '=', '=' }; - var shaped: [text.len]c.UIShapedCell = undefined; - c.ui_font_shape(maple, 27, cell_w, &text, text.len, &shaped); - try std.testing.expectEqual(@as(u8, 2), shaped[1].span); - try std.testing.expectEqual(@as(u8, 2), shaped[4].span); -} - /// What SDL allocates from, on its own threads as well as the render thread: /// the gui's gpa, through the shared C heap, which is thread-safe in every /// build. runNative hands everything back and calls SDL_Quit on the way out. @@ -251,84 +221,6 @@ const font_px_step: f32 = 2.0; const font_px_min: f32 = 8.0; const font_px_max: f32 = 72.0; -test "every font size step moves the cell, and the ends are reachable exactly" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var px = font_px_min + font_px_step; - while (px <= font_px_max) : (px += 1.0) { - var cw: c_int = 0; - var ch: c_int = 0; - var asc: c_int = 0; - var pw: c_int = 0; - var ph: c_int = 0; - c.ui_font_cell_metrics(font, px, &cw, &ch, &asc); - c.ui_font_cell_metrics(font, px - font_px_step, &pw, &ph, &asc); - try std.testing.expect(cw > pw and ch > ph); - } - try std.testing.expectEqual(font_px_max, std.math.clamp(font_px_max + font_px_step, font_px_min, font_px_max)); - try std.testing.expectEqual(font_px_min, std.math.clamp(font_px_min - font_px_step, font_px_min, font_px_max)); -} - -test "FreeType atlas raster is grayscale, bounded, and clears blank cells" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - const h = c.ui_font_glyph(font, 'H'); - try std.testing.expect(h != 0); - try std.testing.expectEqual(@as(u32, 0), c.ui_font_glyph(font, 0x10ffff)); - - const size: f32 = 13.0; - var cell_w: c_int = 0; - var cell_h: c_int = 0; - var ascent: c_int = 0; - c.ui_font_cell_metrics(font, size, &cell_w, &cell_h, &ascent); - try std.testing.expect(cell_w > 0 and cell_w <= 128); - try std.testing.expect(cell_h > 0 and cell_h <= 128); - - const stride: c_int = 128; - var bitmap: [128 * 128]u8 = @splat(0xaa); - try std.testing.expectEqual( - @as(c_int, 1), - c.ui_font_raster(font, size, h, 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), - ); - - var ink: usize = 0; - var soft: usize = 0; - var regular_coverage: usize = 0; - for (0..@intCast(cell_h)) |y| { - for (0..@intCast(cell_w)) |x| { - const coverage = bitmap[y * @as(usize, @intCast(stride)) + x]; - if (coverage > 0) ink += 1; - if (coverage > 0 and coverage < 255) soft += 1; - regular_coverage += coverage; - } - } - try std.testing.expect(ink > 0); - try std.testing.expect(soft > 0); - // Synthetic bold thickens the outline inside the same cell. - try std.testing.expectEqual( - @as(c_int, 1), - c.ui_font_raster(font, size, h, 1, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), - ); - var bold_coverage: usize = 0; - for (0..@intCast(cell_h)) |y| { - for (0..@intCast(cell_w)) |x| bold_coverage += bitmap[y * @as(usize, @intCast(stride)) + x]; - for (bitmap[y * @as(usize, @intCast(stride)) + @as(usize, @intCast(cell_w)) ..][0..@intCast(stride - cell_w)]) |guard| - try std.testing.expectEqual(@as(u8, 0xaa), guard); - } - try std.testing.expect(bold_coverage > regular_coverage); - - try std.testing.expectEqual( - @as(c_int, 0), - c.ui_font_raster(font, size, c.ui_font_glyph(font, ' '), 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), - ); - for (0..@intCast(cell_h)) |y| - for (0..@intCast(cell_w)) |x| - try std.testing.expectEqual( - @as(u8, 0), - bitmap[y * @as(usize, @intCast(stride)) + x], - ); -} - const InkBounds = struct { min_x: usize, min_y: usize, max_x: usize, max_y: usize }; fn inkBounds(bitmap: []const u8, stride: usize, w: usize, h: usize) ?InkBounds { @@ -345,75 +237,6 @@ fn inkBounds(bitmap: []const u8, stride: usize, w: usize, h: usize) ?InkBounds { return bounds; } -test "tagline glyph shrinks into its own cell and stays vertically centered" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - - const body_px: f32 = 27.0; - var cell_w: c_int = 1; - var cell_h: c_int = 1; - var body_ascent: c_int = 1; - c.ui_font_cell_metrics(font, body_px, &cell_w, &cell_h, &body_ascent); - const tag = taglineRaster(font, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent); - try std.testing.expect(tag.px < body_px); - try std.testing.expect(tag.width < @as(u32, @intCast(cell_w))); - - const stride: c_int = 128; - var body: [128 * 128]u8 = @splat(0); - var tagline: [128 * 128]u8 = @splat(0); - const h = c.ui_font_glyph(font, 'H'); - try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, body_px, h, 0, &body, stride, cell_w, cell_h, 0, cell_w, body_ascent)); - try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, tag.px, h, 0, &tagline, stride, @intCast(tag.width), @intCast(tag.height), 0, @intCast(tag.width), tag.baseline)); - const b = inkBounds(&body, @intCast(stride), @intCast(cell_w), @intCast(cell_h)).?; - const t = inkBounds(&tagline, @intCast(stride), @intCast(tag.width), @intCast(tag.height)).?; - try std.testing.expect(t.max_x - t.min_x < b.max_x - b.min_x); - try std.testing.expect(t.max_y - t.min_y < b.max_y - b.min_y); - const body_center_x: isize = @intCast(b.min_x + b.max_x); - const tag_center_x: isize = @intCast(t.min_x + t.max_x); - const body_center_y: isize = @intCast(b.min_y + b.max_y); - const centered_top: isize = @intCast((@as(u32, @intCast(cell_h)) - tag.height) / 2); - const tag_center_y: isize = @as(isize, @intCast(t.min_y + t.max_y)) + centered_top * 2; - const body_slot_center: isize = @intCast(@as(u32, @intCast(cell_w)) - 1); - const tag_slot_center: isize = @intCast(tag.width - 1); - try std.testing.expect(@abs((tag_center_x - tag_slot_center) - (body_center_x - body_slot_center)) <= 2); - try std.testing.expect(@abs(tag_center_y - body_center_y) <= 4); - try std.testing.expect(tag.height < @as(u32, @intCast(cell_h))); -} - -test "tagline percentage changes measured band height without body metrics" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var cell_w: c_int = 1; - var cell_h: c_int = 1; - var ascent: c_int = 1; - c.ui_font_cell_metrics(font, 27.0, &cell_w, &cell_h, &ascent); - const small = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 40); - const configured = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 82); - const full = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 100); - try std.testing.expect(small.width < configured.width); - try std.testing.expect(configured.width <= full.width); - try std.testing.expectEqual(@as(u32, @intCast(cell_w)), full.width); - try std.testing.expect(small.height < configured.height); - try std.testing.expect(configured.height <= full.height); - try std.testing.expect(full.height <= @as(u32, @intCast(cell_h))); -} - -test "installed Nerd Symbols fallback covers Yazi directory icons" { - try std.testing.expectEqualStrings("SymbolsNerdFont-Regular", fonts.fallback_names[2]); - - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const candidate = for (fonts.fallbacks(arena_state.allocator())) |font| { - if (std.mem.eql(u8, font.name, "SymbolsNerdFont-Regular")) break font; - } else return; - - const bytes = try filesystem.readFile(std.testing.allocator, candidate.path); - defer std.testing.allocator.free(bytes); - const face = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; - defer c.ui_font_free(face); - try std.testing.expect(c.ui_font_glyph(face, 0xe5ff) != 0); -} - const CellInstance = extern struct { x0: f32, y0: f32, @@ -466,13 +289,6 @@ const PreparedImage = struct { texture: *c.SDL_GPUTexture, }; -test "the shader instance ABI: the flags after the colours, the clip after them" { - try std.testing.expectEqual(@as(usize, 76), @sizeOf(CellInstance)); - try std.testing.expectEqual(@as(usize, 56), @offsetOf(CellInstance, "effect")); - try std.testing.expectEqual(@as(usize, 60), @offsetOf(CellInstance, "clip_x0")); - try std.testing.expectEqual(@as(usize, 32), @sizeOf(ImageInstance)); -} - fn updateCoreResize(core: *pardes.Pardes, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) bool { core.update(resizeOf(core.view(), cols, rows, cell_w, cell_h, tag_w, tag_h) orelse return false); return true; @@ -673,180 +489,6 @@ fn sdlWake(_: ?*anyopaque) void { const PipeTasks = selection_pipe.Tasks; const output_capacity = Queue.output_capacity; -test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); - try std.testing.expect(host_io.writeFd(child.file.handle, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n")); - var bytes: std.ArrayList(u8) = .empty; - defer bytes.deinit(gpa); - var eof = false; - const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; - while (!eof and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - for (batch.slice()) |msg| switch (msg) { - .output => |o| { - try std.testing.expect(!eof); - try bytes.appendSlice(gpa, o.bytes); - }, - .eof => |e| { - try std.testing.expect(e.failure == null); - eof = true; - }, - else => return error.UnexpectedMessage, - }; - if (!eof) try std.testing.io.sleep(.fromMilliseconds(1), .awake); - } - try std.testing.expect(eof); - try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null); - shell.closePty(0); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expect(ptys[0] == null or ptys[0].?.reader == null); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); -} - -test "GUI PTY Restore joins a real reader waiting for queue space" { - const gpa = std.testing.allocator; - var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - try dump.dumpState(core); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - queue.acceptReader(1, 1); - for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 1, .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); - try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); - try host_io.PtyTests.waitBlocked(&queue); - const old_serial = core.panes[0].?.serial; - const replacement = try dump.restore(core, core.dump_out.?, "test"); - shell.stopPtys(); - core.deinit(); - core = replacement; - shell.core = replacement; - // The dump's pane, its serial too; its old shell stopped all the same. - try std.testing.expectEqual(old_serial, core.panes[0].?.serial); - try std.testing.expectEqual(@as(usize, 0), queue.waiting); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); - queue.cancelReader(1, 1); - queue.acceptReader(0, gens[0]); - queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); - try std.testing.expect(queue.pushOutput(0, gens[0], try gpa.dupe(u8, "fresh"))); - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 1), batch.len); - try std.testing.expectEqualStrings("fresh", batch.items[0].output.bytes); -} - -test "GUI PTY deletion joins an idle reader and its shell is reaped by exit" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); - try core.removePane(0, null); - shell.reconcilePtys(); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expectEqual(@as(usize, 0), queue.waiting); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); - shell.shutdownPtys(); - try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(child.pid, null, libc.W.NOHANG)); - try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1)); -} - -test "GUI PTY file watcher stops and joins without closing its watched descriptor" { - if (!file_watch.supported) return error.SkipZigTest; - const gpa = std.testing.allocator; - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - const fd = file_watch.init(true); - if (fd < 0) return error.WatchInitFailed; - defer _ = libc.close(fd); - const stop = try stopPipe(); - defer for (stop) |pipe_fd| { - _ = libc.close(pipe_fd); - }; - const thread = try std.Thread.spawn(.{}, watchThread, .{ fd, stop[0], &queue }); - _ = host_io.writeFd(stop[1], "x"); - thread.join(); - try std.testing.expect(libc.fcntl(fd, libc.F.GETFD) >= 0); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); -} - -test "GUI completion failure survives backlog and leaves the document unchanged" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("abc"); - pane.body.cur_col = 1; - core.lspRequest(core.view().active, .completion, ""); - const id = core.lsp_ask.wait.?.id; - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = id }; - defer queue.deinit(); - queue.acceptReader(0, 1); - for (0..output_capacity) |_| queue.push(.{ .output = .{ - .pane = 0, - .gen = 1, - .bytes = try gpa.dupe(u8, "output"), - } }); - queue.push(.{ .lsp = .{ .id = id, .rows = null } }); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var shell: Shell = undefined; - shell.core = core; - shell.queue = &queue; - shell.gpa = gpa; - shell.lsp_allocator = gpa; - shell.gens = &gens; - shell.ptys = &ptys; - shell.drainQueue(); - try std.testing.expect(core.lsp_ask.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); -} - fn stopPipe() ![2]c_int { var fds: [2]c_int = undefined; if (libc.pipe(&fds) != 0) return error.PipeFailed; @@ -873,65 +515,6 @@ fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { } } -test "GUI worker setup failures finish matching LSP and pipe requests" { - const gpa = std.testing.allocator; - var failing_vtable = std.testing.io.vtable.*; - failing_vtable.concurrent = std.Io.failingConcurrent; - const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable }; - for (0..2) |failure| { - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("abc"); - var failing = std.testing.FailingAllocator.init(gpa, .{ - .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), - }); - var queue: Queue = .{ - .io = std.testing.io, - .gpa = gpa, - .lsp_allocator = failing.allocator(), - }; - defer queue.deinit(); - var tasks: PipeTasks = .{}; - core.lspRequest(core.view().active, .status, ""); - const req: host_io.Lsp.Request = .{ - .id = core.lsp_ask.wait.?.id, - .kind = .status, - .pane = @intCast(core.view().active), - .offset = 0, - .arg = "", - }; - if (failure == 0) { - queue.lsp_id = req.id -% 1; - queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "old queued result") } }); - queue.startLsp(core, req); - try std.testing.expectEqual(req.id, queue.lsp_id.?); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - queue.push(.{ .lsp = .{ .id = req.id -% 1, .rows = try gpa.dupe(u8, "late old result") } }); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - } else { - var shell: Shell = undefined; - shell.core = core; - shell.threads_ok = false; - lsp(&shell, req); - } - try std.testing.expect(core.lsp_ask.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - - pane.body.cur_col = 2; - pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - core.update(.{ .key = .{ .cp = '|' } }); - core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); - core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = core.pipe.wait.?.id; - selection_pipe.start(failing_io, failing.allocator(), core, &tasks, pipe_id, &queue, Queue.pushPipe); - try std.testing.expect(core.pipe.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(queue.lsp_task == null); - try std.testing.expectEqual(@as(usize, 0), tasks.len); - try std.testing.expectEqual(@as(usize, 0), queue.len); - } -} - const Gui = struct { window: *c.SDL_Window, device: *c.SDL_GPUDevice, @@ -1217,16 +800,6 @@ fn windowPointToPixels(geometry: WindowGeometry, x: f32, y: f32) Point { }; } -test "high-density window coordinates map once to render pixels" { - const geometry: WindowGeometry = .{ - .window_w = 560, - .window_h = 360, - .pixel_w = 1120, - .pixel_h = 720, - }; - try std.testing.expectEqual(Point{ .x = 700, .y = 240 }, windowPointToPixels(geometry, 350, 120)); -} - fn fixedCellLayout(g: *const Gui) CellLayout { return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 }; } @@ -2413,72 +1986,6 @@ fn postKey(in: *Input, key: vaxis.Key, text: []const u8) void { in.post(ev); } -test "the GUI's stdin keys reach a terminal pane as the tty's do: F5, Insert and the keypad's Up" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - var in: Input = .{ .core = core }; - var parser: vaxis.Parser = .{}; - var bytes: []const u8 = "\x1b[15~\x1b[2~\x1b[57419u"; - while (bytes.len > 0) { - const result = try parser.parse(bytes, gpa); - bytes = bytes[result.n..]; - if (result.event) |event| switch (event) { - .key_press => |key| postKey(&in, key, key.text orelse ""), - else => {}, - }; - } - var written: std.Io.Writer.Allocating = .init(gpa); - defer written.deinit(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings("\x1b[15~\x1b[2~\x1b[A", written.written()); -} - -test "the window's function and editing keys reach a terminal as its cursor keys' mode and keyboard flags say" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - var in: Input = .{ .core = core }; - var written: std.Io.Writer.Allocating = .init(gpa); - defer written.deinit(); - const Case = struct { modes: []const u8, sym: c.SDL_Keycode, mod: c.SDL_Keymod = 0, sent: []const u8 }; - const cases = [_]Case{ - .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[A" }, - .{ .modes = "", .sym = c.SDLK_HOME, .sent = "\x1b[H" }, - .{ .modes = "", .sym = c.SDLK_F1, .sent = "\x1bOP" }, - .{ .modes = "", .sym = c.SDLK_F5, .sent = "\x1b[15~" }, - .{ .modes = "", .sym = c.SDLK_F12, .mod = c.SDL_KMOD_LSHIFT, .sent = "\x1b[24;2~" }, - .{ .modes = "", .sym = c.SDLK_INSERT, .sent = "\x1b[2~" }, - // DECCKM: less, vim, htop. - .{ .modes = "\x1b[?1h", .sym = c.SDLK_UP, .sent = "\x1bOA" }, - .{ .modes = "", .sym = c.SDLK_END, .sent = "\x1bOF" }, - .{ .modes = "", .sym = c.SDLK_LEFT, .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[1;5D" }, - // codex's kitty flags (>7u): Ctrl-C and Alt-a are unambiguous. - // (A bare Escape at a shell prompt is pardes's way out of raw input.) - .{ .modes = "\x1b[?1l\x1b[>7u", .sym = 'c', .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[99;5u" }, - .{ .modes = "", .sym = 'a', .mod = c.SDL_KMOD_LALT, .sent = "\x1b[97;3u" }, - // With event types asked for (2), an arrow says it is a press, as - // ghostty says it. - .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[1;1:1A" }, - }; - for (cases) |case| { - core.update(.{ .output = .{ .pane = 0, .bytes = case.modes } }); - while (core.nextEffect()) |_| {} - keyDown(&in, case.sym, case.mod); - written.clearRetainingCapacity(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings(case.sent, written.written()); - } -} - const Input = struct { core: *pardes.Pardes, /// The shell whose window this is (views.zig: its view is `gview`). @@ -2791,11 +2298,6 @@ fn keyDown(in: *Input, sym: c.SDL_Keycode, mod: c.SDL_Keymod) void { in.post(.{ .key = .{ .cp = cp, .ctrl = ctrl, .alt = alt, .shift = shift } }); } -fn pixelCell(px: f32, cell: u32) u16 { - const idx = @floor(@max(px, 0) / @as(f32, @floatFromInt(@max(cell, 1)))); - return @intFromFloat(@min(idx, 10_000)); -} - fn gridCellAtDimensions( core: *const pardes.Pardes, x: f32, @@ -2834,59 +2336,6 @@ fn gridCellAtPixels(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32) M return point; } -test "tagline pointer mapping retains physical grips and carries logical text coordinates" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - core.update(.{ .resize = .{ .cols = 60, .rows = 12 } }); - core.update(.{ .command = "Newcol" }); - core.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 12 }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - _ = try core.render(arena.allocator()); - - const r = core.view().rects[core.view().active]; - const body_w: f32 = 10; - const body_h: f32 = 20; - const tag_w: f32 = 8; - const tag_y = r.y; - const x = @as(f32, @floatFromInt(r.x + pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; - - const tag = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); - try std.testing.expectEqual(pixelCell(x, 10), tag.col); - try std.testing.expectEqual(tag_y, tag.row); - try std.testing.expectEqual(@as(u16, 3), tag.tag_hit.?.col); - try std.testing.expectEqual(pardes.TagKind.pane, tag.tag_hit.?.kind); - const grip = gridCellAtDimensions(core, @as(f32, @floatFromInt(r.x + config.GUTTER)) * body_w - 0.1, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); - try std.testing.expect(grip.tag_hit == null); - try std.testing.expectEqual(r.x + config.GUTTER - 1, grip.col); - - const body_y = tag_y + core.panes[core.view().active].?.tag_rows; // a long tag wraps - const body = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(body_y)) + 0.5) * body_h, body_w, body_h, tag_w); - try std.testing.expectEqual(pixelCell(x, 10), body.col); - try std.testing.expectEqual(body_y, body.row); - try std.testing.expect(body.tag_hit == null); - - // The workspace tag's text starts TAG_TEXT_INSET cells in, as a pane's. - const x_top = @as(f32, @floatFromInt(pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; - const topbar = gridCellAtDimensions(core, x_top, 0.5 * body_h, body_w, body_h, tag_w); - try std.testing.expectEqual(pixelCell(x_top, 10), topbar.col); - try std.testing.expectEqual(@as(u16, 3), topbar.tag_hit.?.col); - try std.testing.expectEqual(pardes.TagKind.workspace, topbar.tag_hit.?.kind); -} - -test "a click at the window's corner lands in the corner cell" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - var g = testGui(10, 20, 6, 12); - const geometry: WindowGeometry = .{ .window_w = 400, .window_h = 240, .pixel_w = 800, .pixel_h = 480 }; - const last = mouseCellWithGeometry(&g, core, 399.9, 239.9, geometry); - try std.testing.expectEqual(@as(u16, 79), last.col); - try std.testing.expectEqual(@as(u16, 23), last.row); - const first = mouseCellWithGeometry(&g, core, 0, 0, geometry); - try std.testing.expectEqual(@as(u16, 0), first.col); - try std.testing.expectEqual(@as(u16, 0), first.row); -} - /// A wheel turned over grid cell `mc` (SDL's sign: up positive): the /// part of dispatch after the pointer is placed, so a test can turn it. fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { @@ -3842,17 +3291,6 @@ pub const Blink = struct { } }; -test "a blink holds while typing, eases at its edges and stops when idle" { - const ms = std.time.ns_per_ms; - try std.testing.expectEqual(@as(f32, 1), Blink.at(100 * ms, 0).alpha); - const out = Blink.at(Blink.hold_ns + Blink.half_ns + 100 * ms, 0); - try std.testing.expectEqual(@as(f32, 0), out.alpha); - const edge = Blink.at(Blink.hold_ns + Blink.half_ns - Blink.edge_ns / 2, 0); - try std.testing.expect(edge.edge and edge.alpha > 0.2 and edge.alpha < 0.8); - try std.testing.expectEqual(@as(?u64, null), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).next_ns); - try std.testing.expectEqual(@as(f32, 1), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).alpha); -} - fn blinkNow(g: *const Gui, on: bool) ?Blink { if (g.no_blink or !on or !g.caret.placed) return null; if (c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_INPUT_FOCUS == 0) return null; @@ -3885,33 +3323,6 @@ fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void { "background transparency requires a native Wayland or alpha-capable SDL window"); } -test "background opacity acknowledges success and rolls back unsupported surfaces" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - var applied: u8 = 100; - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 70")); - try std.testing.expect(core.settings.window_opacity_pending); - finishWindowOpacity(core, &applied, null); - try std.testing.expectEqual(@as(u8, 70), applied); - try std.testing.expect(!core.settings.window_opacity_pending); - - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); - finishWindowOpacity(core, &applied, "background transparency requires an alpha-capable SDL window"); - try std.testing.expectEqual(@as(u8, 70), applied); - try std.testing.expectEqual(applied, core.settings.window_opacity); - try std.testing.expect(!core.settings.window_opacity_pending); - const pane = core.panes[0].?; - try std.testing.expectEqualStrings("WindowOpacity: background transparency requires an alpha-capable SDL window", pane.msg[0..pane.msg_len]); - - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); - try std.testing.expect(core.settings.window_opacity_pending); - finishWindowOpacity(core, &applied, null); - try std.testing.expectEqual(@as(u8, 40), applied); - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 100")); - finishWindowOpacity(core, &applied, null); - try std.testing.expectEqual(@as(u8, 100), applied); -} - fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { const s = shellOf(ctx); const core = s.core; @@ -4120,38 +3531,6 @@ fn readClipboard(ctx: ?*anyopaque) void { shellOf(ctx).core.update(.{ .paste = text }); } -test "the clipboard pasted into a terminal reaches its pty as xterm pastes: bracketed when asked, no ESC[201~ smuggled through" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); - defer core.deinit(); - var shell: Shell = undefined; - shell.core = core; - var sent: std.ArrayList(u8) = .empty; - defer sent.deinit(gpa); - const take = struct { - fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - while (core_.nextEffect()) |effect| { - if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); - } - return out.items; - } - }.f; - _ = try take(core, &sent); - // The clipboard is SDL's own with no display to hold one. - _ = c.SDL_SetHint(c.SDL_HINT_VIDEO_DRIVER, "dummy"); - defer _ = c.SDL_ResetHint(c.SDL_HINT_VIDEO_DRIVER); - if (!c.SDL_InitSubSystem(c.SDL_INIT_VIDEO)) return error.SkipZigTest; - defer c.SDL_QuitSubSystem(c.SDL_INIT_VIDEO); - putClipboard(gpa, "ls\x1b[201~; rm -rf ~\nx"); - readClipboard(&shell); - try std.testing.expectEqualStrings("ls [201~; rm -rf ~\rx", try take(core, &sent)); - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - _ = try take(core, &sent); - readClipboard(&shell); - try std.testing.expectEqualStrings("\x1b[200~ls [201~; rm -rf ~\nx\x1b[201~", try take(core, &sent)); -} - fn openLink(ctx: ?*anyopaque, url: []const u8) void { _ = ctx; look.openLink(url); // desktop browser @@ -4260,60 +3639,6 @@ fn applyScrollDelta(lag: f32, delta: f32) struct { lag: f32, rows: i32 } { return .{ .lag = l, .rows = rows }; } -test "fractional wheel delta moves the picture by the same fraction" { - const delta = accumulateWheelDelta(0, -0.125); - const s = applyScrollDelta(0, delta); - const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; - try std.testing.expectEqual(@as(f32, 0.125), delta); - try std.testing.expectEqual(@as(f32, 0.125), picture); - try std.testing.expectEqual(@as(i32, 1), s.rows); - try std.testing.expectEqual(@as(f32, -0.875), s.lag); -} - -test "repeated fractional deltas cross exactly one core row" { - var core_row: i32 = 0; - var lag: f32 = 0; - var crossed: u32 = 0; - for (0..8) |_| { - const s = applyScrollDelta(lag, 0.125); - core_row += s.rows; - crossed += @intCast(@abs(s.rows)); - lag = s.lag; - } - try std.testing.expectEqual(@as(u32, 1), crossed); - try std.testing.expectEqual(@as(i32, 1), core_row); - try std.testing.expectEqual(@as(f32, 0), lag); -} - -test "wheel magnitude is preserved without quantization" { - const delta = accumulateWheelDelta(0, -2.75); - const s = applyScrollDelta(0, delta); - const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; - try std.testing.expectEqual(@as(f32, 2.75), delta); - try std.testing.expectEqual(@as(f32, 2.75), picture); - try std.testing.expectEqual(@as(i32, 3), s.rows); - try std.testing.expectEqual(@as(f32, -0.25), s.lag); - try std.testing.expectEqual(@as(f32, 0), accumulateWheelDelta(0, std.math.inf(f32))); - - const bounded = boundScrollDelta(0, 3.0e38, 24); - const safe = applyScrollDelta(0, bounded); - try std.testing.expectEqual(@as(f32, 24), bounded); - try std.testing.expectEqual(@as(i32, 24), safe.rows); -} - -test "fractional scroll reversals preserve signed distance" { - var core_row: i32 = 0; - const forward = applyScrollDelta(0, 0.375); - core_row += forward.rows; - try std.testing.expectEqual(@as(f32, 0.375), @as(f32, @floatFromInt(core_row)) + forward.lag); - - const reverse = applyScrollDelta(forward.lag, -0.125); - core_row += reverse.rows; - try std.testing.expectEqual(@as(i32, -1), reverse.rows); - try std.testing.expectEqual(@as(f32, 0.25), @as(f32, @floatFromInt(core_row)) + reverse.lag); - try std.testing.expect(reverse.lag >= 0 and reverse.lag < 1); -} - /// A mouse wheel's step as whole lines (down positive), or null for a /// touchpad's fraction, which follows the finger as it is. fn notchOf(raw_y: f32, integer_y: i32) ?i32 { @@ -4321,125 +3646,6 @@ fn notchOf(raw_y: f32, integer_y: i32) ?i32 { return @intFromFloat(std.math.clamp(-raw_y, -64, 64)); } -test "a wheel's notch is whole lines, a touchpad's fraction is not" { - try std.testing.expectEqual(@as(?i32, 1), notchOf(-1, -1)); - try std.testing.expectEqual(@as(?i32, -3), notchOf(3, 3)); - try std.testing.expectEqual(@as(?i32, null), notchOf(-0.25, 0)); - try std.testing.expectEqual(@as(?i32, null), notchOf(-1.5, -1)); - try std.testing.expectEqual(@as(?i32, null), notchOf(std.math.nan(f32), 1)); -} - -test "a click over codex in a terminal reaches its pty with its modifiers; Shift swaps B1 to pardes and B2 to the program" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); - defer core.deinit(); - var frame: std.heap.ArenaAllocator = .init(gpa); - defer frame.deinit(); - _ = try core.render(frame.allocator()); - var in: Input = .{ .core = core }; - var sent: std.ArrayList(u8) = .empty; - defer sent.deinit(gpa); - const take = struct { - fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - while (core_.nextEffect()) |effect| { - if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); - } - return out.items; - } - }.f; - _ = try take(core, &sent); - const pane = core.panes[0].?; - const r = core.view().rects[0]; - const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; - const next: MouseCell = .{ .col = mc.col + 1, .row = mc.row }; - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); - _ = try take(core, &sent); - in.post(.{ .mouse = pointerMouse(.none, .motion, mc, .{}) }); - try std.testing.expectEqualStrings("\x1b[<35;6;4M", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .ctrl = true }) }); - try std.testing.expectEqualStrings("\x1b[<16;6;4M", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.left, .drag, next, .{}) }); - try std.testing.expectEqualStrings("\x1b[<32;7;4M", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.left, .release, next, .{}) }); - try std.testing.expectEqualStrings("\x1b[<0;7;4m", try take(core, &sent)); - // Shift-B1 is pardes's select; B2 is pardes's execute and Shift-B2 - // the program's, reported without the Shift. - in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .shift = true }) }); - in.post(.{ .mouse = pointerMouse(.left, .release, mc, .{ .shift = true }) }); - try std.testing.expectEqualStrings("", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{}) }); - in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{}) }); - try std.testing.expectEqualStrings("", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{ .shift = true }) }); - in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{ .shift = true }) }); - try std.testing.expectEqualStrings("\x1b[<1;6;4M\x1b[<1;6;4m", try take(core, &sent)); -} - -test "a wheel over codex in a terminal reaches its pty as the mouse reports it asked for" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); - defer core.deinit(); - var frame: std.heap.ArenaAllocator = .init(gpa); - defer frame.deinit(); - _ = try core.render(frame.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - var in: Input = .{ .core = core }; - var sent: std.ArrayList(u8) = .empty; - defer sent.deinit(gpa); - const Sent = struct { - fn take(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - while (core_.nextEffect()) |effect| { - if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); - } - return out.items; - } - }; - _ = try Sent.take(core, &sent); - const pane = core.panes[0].?; - const r = core.view().rects[0]; - const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; - // What codex 0.159's chat sets on start. - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h\x1b[>7u\x1b[?1004h\x1b[?1049h\x1b[?1007l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); - _ = try Sent.take(core, &sent); - // A notch up, then a fast turn of three down: each its report, none - // left behind for a glide. - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); - try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); - wheelAt(&g, &in, .{ .y = -3, .integer_y = -3 }, mc); - try std.testing.expectEqualStrings(std.mem.asBytes(&@as([3][10]u8, @splat("\x1b[<65;6;4M".*))), try Sent.take(core, &sent)); - try std.testing.expectEqual(@as(i32, 0), g.scroll_notch); - try std.testing.expect(g.scroll_pane == null); - // A touchpad's fractions add up to a turn. - wheelAt(&g, &in, .{ .y = 0.5 }, mc); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - wheelAt(&g, &in, .{ .y = 0.5 }, mc); - try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); - // Alt is meta, 8; Shift keeps the turn pardes's own, a glide. - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .alt = true } }, mc); - try std.testing.expectEqualStrings("\x1b[<72;6;4M", try Sent.take(core, &sent)); - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .shift = true } }, mc); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); - stepGlide(&g, core); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - resetScroll(&g); - // Its sign-in screen: mouse off, alternate scroll on, so arrow keys. - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1007h" } }); - _ = try Sent.take(core, &sent); - wheelAt(&g, &in, .{ .y = -1, .integer_y = -1 }, mc); - try std.testing.expectEqualStrings("\x1b[B", try Sent.take(core, &sent)); - // Back on the main screen a shell's wheel is ours: a notch to glide, - // nothing to the pty. - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049l" } }); - _ = try Sent.take(core, &sent); - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); -} - const Glide = pardes.glide.Glide; /// Feeds a wheel's notches to the core, and keeps what moved the view for @@ -4489,68 +3695,6 @@ fn glideFrame(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface) v g.glide_wheeled = null; } -test "a notch scrolls the core at once and the picture glides after it, a wrapped line's rows at a time" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - // Lines of two rows each at this width, numbered so no two rows match. - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..60) |i| { - try text.print(gpa, "{d:0>4} ", .{i}); - try text.appendNTimes(gpa, 'a' + @as(u8, @intCast(i % 26)), 100); - try text.append(gpa, '\n'); - } - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const ms = std.time.ns_per_ms; - var now: u64 = std.time.ns_per_s; - core.advance(now); - var s = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - const r = core.view().rects[core.view().active]; - g.scroll_pane = core.view().active; - g.scroll_col = r.x + 10; - g.scroll_row = r.y + r.h - 2; - const body_y = core.bodyTop(core.panes[core.view().active].?, r); - const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y + 1) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); - defer gpa.free(row_before); - // The window has drawn the view once (Glide.frame finds a view that moved). - g.now_ns = now; - glideFrame(&g, gpa, s); - // One notch down: the core is a line on at once. - g.scroll_notch = 1; - const scrolled = core.panes[core.view().active].?.scroll(); - stepGlide(&g, core); - try std.testing.expectEqual(scrolled + 1, core.panes[core.view().active].?.scroll()); - _ = arena.reset(.retain_capacity); - s = try core.render(arena.allocator()); - glideFrame(&g, gpa, s); - // The window's own motion: it draws its frames while it moves. - try std.testing.expect(frontendMoving(&g)); - // Its two rows: the picture two rows behind, the rows that left kept, - // nearest first. - try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.follow.offset, 1e-4); - try std.testing.expectEqual(@as(u16, 2), g.glide.nabove); - try std.testing.expect(pardes.glide.sameRow(g.glide.above[0 .. r.w - config.GUTTER], row_before)); - // Frame by frame it comes back, never past, and settles. - var frames: usize = 0; - while (g.glide.moving()) : (frames += 1) { - now += 7 * ms; - core.advance(now); - stepGlide(&g, core); - g.now_ns = now; - glideFrame(&g, gpa, s); - try std.testing.expect(g.glide.follow.offset <= 1e-4); - if (frames > 200) return error.NeverSettled; - } - try std.testing.expect(frames > 5); - try std.testing.expectEqual(@as(f32, 0), g.glide.follow.offset); - try std.testing.expect(!frontendMoving(&g)); -} - /// The window's loop over a text pane under a wheel, as waitInput and the /// pump run it but with no window: a frame's turns (wheelAt), pollFrame's /// stepScroll, and a frame drawn only when one is owed (the core's @@ -4604,177 +3748,6 @@ const WheelRun = struct { } }; -fn wheelRunFile(gpa: std.mem.Allocator) !*pardes.Pardes { - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - errdefer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..400) |i| try text.print(gpa, "{d:0>4} a line of the file\n", .{i}); - _ = try core.setTestFile(text.items); - for ("200G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); - return core; -} - -test "a fractional wheel turn that brings the picture back onto the core's row is drawn: the window never rests on a frame half a row off" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - // A high-resolution wheel's half notches (SDL's y, up positive), a - // frame each: the first scrolls the core a line and leaves the picture - // half a row behind it; the second takes the picture onto it. - for (0..2) |_| { - try wr.frame(gpa, &.{-0.5}); - try std.testing.expectEqual(wr.picture(), wr.drawn); - } - try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); -} - -test "a wheel turned down then up never draws the picture moving against the turn" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - // Two half notches down (the picture back on the core's row), then - // quarter notches up, a frame each and frames between: each frame's - // picture is where the last left it or on the way the wheel turns, - // never back against it. - for ([_]struct { f32, usize }{ .{ -0.5, 2 }, .{ 0.25, 4 } }) |phase| { - const turn, const turns = phase; - for (0..turns + 4) |k| { - const was = wr.drawn; - try wr.frame(gpa, if (k < turns) &.{turn} else &.{}); - const moved = wr.drawn - was; - try std.testing.expect(moved * -turn >= -1e-4); - } - } -} - -test "a fine wheel's turns that stop at a fraction leave the text on a whole row, and a turn mid-settle is not lost" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - const line = struct { - fn of(p: *pardes.Pardes) i64 { - return @intCast(p.panes[p.view().active].?.scroll()); - } - }.of; - const first = line(core); - // Three quarter notches down, a frame each: the core a line on, the - // picture a quarter row behind it. Then nothing: it eases onto the - // core's row (never back against the turns) and rests there, drawn. - for (0..3) |_| try wr.frame(gpa, &.{-0.25}); - try std.testing.expect(wr.g.scroll_lag != 0); - var frames: usize = 0; - while (wr.g.scroll_lag != 0) : (frames += 1) { - const was = wr.drawn; - try wr.frame(gpa, &.{}); - try std.testing.expect(wr.drawn >= was); - try std.testing.expect(frames < 20); - } - try std.testing.expectEqual(first + 1, line(core)); - try std.testing.expectEqual(wr.picture(), wr.drawn); - try std.testing.expectEqual(@as(f32, @floatFromInt(first + 1)), wr.drawn); - // Again, and a quarter notch more arrives mid-settle: it counts, and - // the settle ends on the row after it. - for (0..3) |_| try wr.frame(gpa, &.{-0.25}); - for (0..4) |_| try wr.frame(gpa, &.{}); - try std.testing.expect(wr.g.scroll_lag != 0); - try wr.frame(gpa, &.{-0.25}); - for (0..20) |_| try wr.frame(gpa, &.{}); - try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); - try std.testing.expectEqual(first + 3, line(core)); - try std.testing.expectEqual(@as(f32, @floatFromInt(first + 3)), wr.drawn); -} - -test "a bar cursor is drawn on its line while a wheel's fraction holds the text off its row, as a block is" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - core.settings.cursor_blink = false; - core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - defer wr.g.decor.deinit(gpa); - // Half a notch down: the core a line on, the text drawn half a row - // below its cells until the settle. - try wr.frame(gpa, &.{-0.5}); - try std.testing.expectEqual(@as(f32, -0.5), wr.g.scroll_lag); - _ = wr.arena.reset(.retain_capacity); - const s = try core.render(wr.arena.allocator()); - const cu = s.cursor.?; - try std.testing.expect(cu.bar); - const layout = fixedCellLayout(&wr.g); - const win_w: f32 = @floatFromInt(@as(u32, s.cols) * wr.g.cell_w); - const win_h: f32 = @floatFromInt(@as(u32, s.rows) * wr.g.cell_h); - wr.g.decor.clearRetainingCapacity(); - try cursorDecor(&wr.g, gpa, s, layout, win_w, win_h); - try std.testing.expectEqual(@as(usize, 1), wr.g.decor.items.len); - // Its top where its line's top is drawn (emitScrollRows: the row less - // the lag), not on its cell. - const top = (1 - wr.g.decor.items[0].y0) * win_h / 2; - try std.testing.expectApproxEqAbs((@as(f32, @floatFromInt(cu.y)) - wr.g.scroll_lag) * layout.h, top, 0.01); -} - -test "a wheel's caret rides with its line, the text's own glide, never a spring of its own" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..200) |i| try text.print(gpa, "line {d}\n", .{i}); - _ = try core.setTestFile(text.items); - core.settings.cursor_blink = false; - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var now: u64 = std.time.ns_per_s; - core.advance(now); - for ("10G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); - _ = try core.render(arena.allocator()); - now += std.time.ns_per_s; - core.advance(now); - _ = arena.reset(.retain_capacity); - var s = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - const r = core.view().rects[core.view().active]; - g.scroll_pane = core.view().active; - g.scroll_col = r.x + 10; - g.scroll_row = r.y + r.h - 2; - stepGlide(&g, core); - // The window has drawn the view once (Glide.frame finds a view that moved). - g.now_ns = now; - glideFrame(&g, gpa, s); - const before: f32 = @floatFromInt(s.cursor.?.y); - g.scroll_notch = 1; - stepGlide(&g, core); - var frames: usize = 0; - while (true) : (frames += 1) { - now += 7 * std.time.ns_per_ms; - core.advance(now); - _ = arena.reset(.retain_capacity); - s = try core.render(arena.allocator()); - g.now_ns = now; - glideFrame(&g, gpa, s); - seeCaret(&g, s, fixedCellLayout(&g), 480, now); - if (frames == 0) { - try std.testing.expect(g.glide.caret_rides); - // Where its line is drawn: on the row it was on, the cell a row up. - try std.testing.expectApproxEqAbs(before, caretRow(&g, s, now).?, 1e-3); - } - // Always exactly with its line, the cell less the text's offset. - try std.testing.expectApproxEqAbs(@as(f32, @floatFromInt(s.cursor.?.y)) - g.glide.follow.offset, caretRow(&g, s, now).?, 1e-3); - if (!g.glide.moving()) break; - stepGlide(&g, core); - if (frames > 200) return error.NeverSettled; - } - try std.testing.expectEqual(@as(f32, @floatFromInt(s.cursor.?.y)), caretRow(&g, s, now).?); -} - /// The scripted scroll sequence of the glide tests: a frame a 60 Hz /// refresh, as the paced loop draws them (waitInput, then stepGlide, the /// core's render and the frame's measure), an input on the frames `script` @@ -4831,122 +3804,6 @@ const GlideRun = struct { } }; -test "every scroll glides on one law: a half page, a page, the far jumps, a run of them retargeting" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - // Numbered lines no two alike, short enough never to wrap. - for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - core.advance(std.time.ns_per_s); - _ = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - const body_h: f32 = @floatFromInt(core.view().rects[core.view().active].h - core.panes[core.view().active].?.tag_rows); - const ctrl = struct { - fn key(cp: u21) pardes.Key { - return .{ .cp = cp, .ctrl = true }; - } - }; - const script = [_]GlideRun.Step{ - .{ .frame = 2, .key = ctrl.key('d') }, - .{ .frame = 40, .key = ctrl.key('f') }, - .{ .frame = 80, .key = .{ .cp = 'g', .text = "g" } }, - .{ .frame = 80, .key = .{ .cp = 'e', .text = "e" } }, - .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, - .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, - // Faster than they settle: each adds to the glide under way. - .{ .frame = 160, .key = ctrl.key('d') }, - .{ .frame = 165, .key = ctrl.key('d') }, - .{ .frame = 170, .key = ctrl.key('d') }, - .{ .frame = 175, .key = ctrl.key('d') }, - }; - var seq: GlideRun = .{}; - try seq.play(&g, core, gpa, &arena, &script, 240); - try seq.checkCaret(); - // Every one moves the picture on the frame it is drawn in, and the - // picture lags by what the core moved (a far jump, by one body). - var longest: usize = 0; - var shortest: usize = std.math.maxInt(usize); - for ([_]usize{ 2, 40, 80, 120 }) |at| { - const moved: f32 = @floatFromInt(@abs(seq.lines[at] - seq.lines[at - 1])); - try std.testing.expect(moved >= 1); - const lag = @abs(seq.offsets[at]); - try std.testing.expect(lag > 0.5 * @min(moved, body_h)); - try std.testing.expect(lag <= @min(moved, body_h) + 1e-3); - // Settles on the same law whatever the distance: a few frames for - // a half page, not many more for a jump of 3000 lines. - const frames = seq.settle(at); - longest = @max(longest, frames); - shortest = @min(shortest, frames); - try std.testing.expect(frames >= 8 and frames <= 24); - } - try std.testing.expect(longest - shortest <= 5); - // Readable: never more than a quarter of a body a frame once it moves. - for (1..seq.frames) |k| { - if (seq.lines[k] != seq.lines[k - 1]) continue; - try std.testing.expect(@abs(seq.offsets[k] - seq.offsets[k - 1]) <= body_h / 4 + 1e-3); - } - // The seq of half pages: one glide, never at rest between them, and - // done as soon after the last as one half page alone takes. - for (160..180) |k| try std.testing.expect(seq.offsets[k] != 0); - try std.testing.expect(seq.settle(175) <= seq.settle(2) + 4); -} - -test "a held key moves the view at the stream's own rate, never a bounce a line, and settles once it stops" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - core.advance(std.time.ns_per_s); - _ = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - // j held from the top: a repeat every second frame, the view following - // a line a repeat once the caret is at its last rows. - var script: [48]GlideRun.Step = undefined; - for (&script, 0..) |*step, i| step.* = .{ .frame = 20 + 2 * i, .key = .{ .cp = 'j', .text = "j" } }; - var seq: GlideRun = .{}; - try seq.play(&g, core, gpa, &arena, &script, 200); - // Inside the stream the picture moves every frame by about the same - // step: an input's rows over its spacing, not a spring's ease to each. - var least: f32 = std.math.inf(f32); - var most: f32 = 0; - for (90..110) |k| { - const step = (@as(f32, @floatFromInt(seq.lines[k])) + seq.offsets[k]) - (@as(f32, @floatFromInt(seq.lines[k - 1])) + seq.offsets[k - 1]); - least = @min(least, step); - most = @max(most, step); - } - try std.testing.expect(seq.lines[89] > 0 and least > 0.4 and most < 0.6); - // The caret stays on its row, the text moving under it: not a pixel's - // wobble (the glide's fractional lag never reaches it). - for (90..110) |k| try std.testing.expectEqual(seq.carets[89], seq.carets[k]); - // It comes to rest once the keys stop, never past its mark. - for (110..200) |k| try std.testing.expect(seq.offsets[k] <= 0); - try std.testing.expectEqual(@as(f32, 0), seq.offsets[199]); - // Ctrl-d held, then PageDown held: the caret keeps its row the whole - // way, the pages moving under it. - var pages: [40]GlideRun.Step = undefined; - for (&pages, 0..) |*step, i| step.* = .{ .frame = 10 + 2 * i, .key = if (i < 20) .{ .cp = 'd', .ctrl = true } else .{ .cp = pardes.Key.page_down } }; - var held: GlideRun = .{}; - try held.play(&g, core, gpa, &arena, &pages, 100); - try held.checkCaret(); - try seq.checkCaret(); - // (The first of each may move it, one ease: from the last row to where - // a half page keeps it, and from there to a page's.) - for (30..50) |k| try std.testing.expectEqual(held.carets[30], held.carets[k]); - for (70..90) |k| try std.testing.expectEqual(held.carets[70], held.carets[k]); -} - fn resetScroll(g: *Gui) void { g.scroll_pane = null; g.scroll_delta = 0; @@ -5153,33 +4010,6 @@ fn holdContext(g: *Gui, surface: *const pardes.Surface, id: usize, held: u16, bh return .{ .rows = rows, .lift = @as(f32, @floatFromInt(rows)) * (row_px - layout.h) }; } -test "a scroll's shifted rows start under the context rows, and its scissor below their band" { - var surface: pardes.Surface = .{}; - var g = testGui(10, 20, 6, 12); - g.scroll_rect = .{ .x = 0, .y = 0, .w = 40, .h = 20 }; - g.scroll_body_y = 1; - g.scroll_body_h = 19; - const layout: CellLayout = .{ .w = 10, .h = 20, .x_off = 0, .y_off = 0 }; - // On the grid, three body-high rows are held, and nothing moves up. - const grid = holdContext(&g, &surface, 0, 3, 19, layout); - try std.testing.expectEqual(@as(u16, 3), grid.rows); - try std.testing.expectEqual(@as(f32, 0), grid.lift); - const clip = scrollScissor(&g, layout, 400, 400); - try std.testing.expectEqual(@as(c_int, 20 + 3 * 20), clip.y); - try std.testing.expectEqual(@as(c_int, 16 * 20), clip.h); - // In a body layer they are tagline-high: the rows under them move up - // by what each is shorter, to where the layer draws them. - surface.body_layers[0].rows = 30; - surface.body_layers[0].context_rows = 3; - const layered = holdContext(&g, &surface, 0, 3, 19, layout); - try std.testing.expectEqual(@as(f32, 3 * (12 - 20)), layered.lift); - try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout, 400, 400).y); - // None held: the whole body moves. - surface.body_layers[0].rows = 0; - try std.testing.expectEqual(@as(u16, 0), holdContext(&g, &surface, 0, 0, 19, layout).rows); - try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout, 400, 400).y); -} - fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect { const r = g.scroll_rect; const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w; @@ -5786,120 +4616,10 @@ fn cellFontRole(cell: *const pardes.Cell) pardes.FontRole { return if (cell.default) .body else cell.style.font_role; } -test "concealed terminal text emits no ink on its ground" { - var g = testGui(10, 20, 6, 12); - var cell: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; - cell.text[0] = 'X'; - const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); - try std.testing.expectEqualDeep(g.space_slot, resolved.slot); - try std.testing.expectEqual(bg_default, resolved.bg); -} - -test "a block cursor's cell is drawn reversed: the cell's ink its ground, its ground its ink" { - var g = testGui(10, 20, 6, 12); - // A blank, so no glyph is looked up in this atlas-less Gui. - const cell: pardes.Cell = .{ - .text = .{ ' ', ' ', ' ', ' ', ' ', ' ', ' ' }, - .len = 1, - .default = false, - .style = .{ .fg = .{ .rgb = .{ 10, 20, 30 } }, .bg = .{ .rgb = .{ 200, 210, 220 } } }, - }; - const plain = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); - const cursor = resolveCell(&g, (&cell)[0..1], 0, 0, .body, true, bg_default); - try std.testing.expectEqual([3]u8{ 10, 20, 30 }, plain.fg); - try std.testing.expectEqual(plain.fg, cursor.bg); - try std.testing.expectEqual(plain.bg, cursor.fg); -} - fn cellInstanceCount(cell: *const pardes.Cell) u32 { return if (cellFontRole(cell) == .tagline) 2 else 1; } -fn tagLayerIn(layers: []const pardes.Layer, col: u16, row: u16) ?*const pardes.Layer { - for (layers) |*layer| { - const r = layer.viewport; - if (layer.rows > 0 and row >= r.y and row - r.y < layer.rows and col >= r.x and col - r.x < r.w) return layer; - } - return null; -} - -fn expectCoverIsScan(cover: []const Cover, cols: u16, rows: u16, body_layers: []const pardes.Layer, tag_layers: []const pardes.Layer) !void { - for (0..rows) |row| for (0..cols) |col| { - const scan = bodyLayerIn(body_layers, @intCast(col), @intCast(row)) != null or tagLayerIn(tag_layers, @intCast(col), @intCast(row)) != null; - try std.testing.expectEqual(scan, cover[row * cols + col].layer); - }; -} - -test "the layer cover is the per-cell layer scan, over a core's layouts and random layers" { - // A gui-shaped core: its tagline is narrower and shorter than the body, - // so tags and notices are layers. - const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 97, .rows = 31 }); - defer core.deinit(); - core.update(.{ .resize = .{ .cols = 97, .rows = 31, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 7, .tagline_h = 13 } } }); - for (1..4) |id| _ = try core.newShell(id, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - pardes.layout.insert(core, 1, 1, 2); - pardes.layout.insert(core, 0, 1, 3); - var cover: [97 * 31]Cover = undefined; - var notices = false; - for (0..32) |step| { - if (step & 3 == 0) try std.testing.expect(core.executeBuiltinLine(2, "Collapse")); - core.view().prefix = if (step & 4 != 0) .leader else .none; - if (step & 8 != 0) { - try std.testing.expect(core.executeBuiltinLine(0, "Msg a message chip over the body")); - try std.testing.expect(core.executeBuiltinLine(3, "Msg another")); - } - const s = try core.render(core.scratch.allocator()); - try std.testing.expectEqual(@as(usize, cover.len), @as(usize, s.cols) * s.rows); - @memset(&cover, .{ .layer = true, .floating = true, .grip = true, .focus = true }); // what an earlier frame left - coverFrame(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); - try expectCoverIsScan(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers()); - // A grip's cells know their way to its glyph, and the focused - // pane's tag rows are the focused ones. - for (s.regionList()) |region| { - if (region.kind != .grip) continue; - for (0..region.rect.w) |offset| { - const cell = cover[@as(usize, region.rect.y) * s.cols + region.rect.x + offset]; - try std.testing.expect(cell.grip); - try std.testing.expectEqual(offset, cell.grip_offset); - try std.testing.expectEqual(region.owner == core.view().active, cell.focus); - } - } - for (s.tagLayers()) |layer| notices = notices or (layer.rows != 0 and layer.kind == .notice); - } - try std.testing.expect(notices); - - // Random layers: overlapping, empty, past the grid's right and bottom - // edges, and at the top of u16, where x + w overflows it. - const gen = struct { - fn coordinate(random: std.Random, limit: u16) u16 { - if (random.uintLessThan(u8, 12) == 0) return std.math.maxInt(u16) - random.uintLessThan(u16, 3); - return random.uintAtMost(u16, limit + 3); - } - fn rect(random: std.Random, cols: u16, rows: u16) pardes.Rect { - return .{ .x = coordinate(random, cols), .y = coordinate(random, rows), .w = coordinate(random, cols), .h = coordinate(random, rows / 2) }; - } - }; - var prng = std.Random.DefaultPrng.init(0x6c61796572); - const random = prng.random(); - var body: [pardes.MAX_PANES]pardes.Layer = undefined; - var tag: [pardes.MAX_TAG_LAYERS]pardes.Layer = undefined; - var grid: [64 * 40]Cover = undefined; - for (0..3000) |_| { - const cols = random.intRangeAtMost(u16, 1, 64); - const rows = random.intRangeAtMost(u16, 1, 40); - const empty = random.intRangeAtMost(u8, 2, 5); // about one layer in `empty` is empty - for (&body) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; - for (&tag) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; - const bodies = body[0..random.uintAtMost(usize, body.len)]; - const tags = tag[0..random.uintAtMost(usize, tag.len)]; - const cells = grid[0 .. @as(usize, cols) * rows]; - @memset(cells, .{ .layer = random.boolean() }); - coverFrame(cells, cols, rows, bodies, tags, &.{}); - try expectCoverIsScan(cells, cols, rows, bodies, tags); - } -} - fn tagLayerCellCount(g: *const Gui, layer: *const pardes.Layer) u32 { const pixels = @as(u32, layer.viewport.w) * g.cell_w; return @min(layer.cols, (pixels + g.tagline_width - 1) / g.tagline_width); @@ -6177,121 +4897,6 @@ fn emitSurfaceCell( next.* += 1; } -test "every pixel of a grip column is band, button or ring, and the button sits over the scrollbar" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 20 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([60][5]u8, @splat("text\n".*)))); - pane.tag.own = try gpa.dupe(u8, "second\nthird"); - core.newScratchBelow(0); - for ([_]struct { w: u32, h: u32, tag: u32 }{ .{ .w = 10, .h = 20, .tag = 12 }, .{ .w = 17, .h = 35, .tag = 30 }, .{ .w = 9, .h = 19, .tag = 15 }, .{ .w = 12, .h = 24, .tag = 24 } }) |m| for ([_]usize{ 0, 1 }) |focus| for ([_]bool{ false, true }) |dirty| { - core.view().active = focus; - pane.file.?.revision = pane.file.?.saved_revision + @intFromBool(dirty); - core.sync(); - const s = try core.render(core.scratch.allocator()); - var g = testGui(m.w, m.h, m.w, m.tag); - defer g.decor.deinit(gpa); - const layout = fixedCellLayout(&g); - const win_w: f32 = @floatFromInt(60 * m.w); - const win_h: f32 = @floatFromInt(20 * m.h); - const cover = try gpa.alloc(Cover, @as(usize, s.cols) * s.rows); - defer gpa.free(cover); - coverFrame(cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, layout, win_w, win_h, true); - const grip = s.region(.grip, 0).?; - // The grip column's pixels, band first, then its cells, then decor. - const x_px: u32 = grip.rect.x * m.w; - const w_px: u32 = config.GUTTER * m.w; - const y_px: u32 = grip.rect.y * m.h; - const h_px: u32 = grip.rect.h * m.h; - const pixels = try gpa.alloc(?[3]f32, w_px * h_px); - defer gpa.free(pixels); - @memset(pixels, null); - const paint = struct { - fn quad(into: []?[3]f32, x0n: f32, y0n: f32, x1n: f32, y1n: f32, rgb: [3]f32, ww: f32, wh: f32, ox: u32, oy: u32, pw: u32, ph: u32) void { - const px0: i64 = @intFromFloat(@round((x0n + 1) / 2 * ww)); - const px1: i64 = @intFromFloat(@round((x1n + 1) / 2 * ww)); - const py0: i64 = @intFromFloat(@round((1 - y0n) / 2 * wh)); - const py1: i64 = @intFromFloat(@round((1 - y1n) / 2 * wh)); - var y = @max(py0, oy); - while (y < @min(py1, oy + ph)) : (y += 1) { - var x = @max(px0, ox); - while (x < @min(px1, ox + pw)) : (x += 1) into[@intCast((y - oy) * pw + (x - ox))] = rgb; - } - } - }; - var instances: [4]CellInstance = undefined; - for (0..grip.rect.h) |line| for (0..config.GUTTER) |dx| { - const col: u16 = grip.rect.x + @as(u16, @intCast(dx)); - const row: u16 = grip.rect.y + @as(u16, @intCast(line)); - const at = @as(usize, row) * s.cols; - var next: u32 = 0; - emitSurfaceCell(&g, &s.chrome, &instances, &next, col, row, layout, win_w, win_h, s.cells[at..][0..s.cols], cover[at..][0..s.cols], col, null, false, bg_default); - for (instances[0..next]) |i| paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); - }; - for (g.decor.items) |i| if (i.fr >= 1 and i.clip_x1 < i.clip_x0) paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); - const rgb = struct { - fn of(v: [3]u8) [3]f32 { - return .{ @as(f32, @floatFromInt(v[0])) / 255, @as(f32, @floatFromInt(v[1])) / 255, @as(f32, @floatFromInt(v[2])) / 255 }; - } - }.of; - const chrome = &s.chrome; - const band = if (focus == 0) chrome.tag_focus_bg else chrome.tag_bg; - // Band, fills, rings, the rules between stacked panes and under the - // tag, and the mode marks' ink (the grip's first cell's). - const ink = inkOn(gripFill(chrome, grip.active, grip.dirty)); - const allowed = [_][3]f32{ rgb(band), rgb(core.chromeTheme().box), rgb(pardes.draw.boxDirty(core)), rgb(chrome.grip_border), rgb(chrome.grip_focus_ring), rgb(chrome.border), rgb(ink), rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)) }; - for (pixels, 0..) |pixel, n| { - const got = pixel orelse return error.TestUnpaintedGripPixel; - const known = for (allowed) |a| { - if (std.meta.eql(a, got)) break true; - } else false; - // Under the first row there is no button: band and rules only. - if (n / w_px >= m.h and n / w_px < h_px - 1 and !std.meta.eql(got, rgb(band)) and !std.meta.eql(got, rgb(chrome.border))) - return error.TestButtonUnderFirstRow; - if (!known) std.debug.print("sliver {any} at {d},{d} of {d}x{d} (metrics {d}x{d}/{d}, focus {d}, dirty {}) page {any}\n", .{ got, n % w_px, n / w_px, w_px, h_px, m.w, m.h, m.tag, focus, dirty, s.chrome.page }); - try std.testing.expect(known); - } - // The rule under the tag runs unbroken across the grip column. - for (pixels[(h_px - 1) * w_px ..][0..w_px]) |pixel| - try std.testing.expectEqual(rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)), pixel.?); - // The button's edges are the scrollbar's. - const button = gripButton(&g, chrome, grip.rect.x, grip.rect.y, layout); - const column = scrollColumn(&g, chrome, s.region(.rail, 0).?.rect.x, layout); - try std.testing.expectEqual(column[0], button[0]); - try std.testing.expectEqual(column[1], button[2]); - }; - pane.file.?.revision = pane.file.?.saved_revision; -} - -test "small tagline fonts leave no background gutters between adjacent tags" { - const chrome: pardes.Chrome = .{}; - var g = testGui(10, 20, 8, 16); - const cell: pardes.Cell = .{ .default = false, .style = .{ .font_role = .tagline } }; - var instances: [6]CellInstance = undefined; - var next: u32 = 0; - for (0..3) |row| { - // Column 1: past the anchor's inset edge at the column's left. - emitSurfaceCell(&g, &chrome, &instances, &next, 1, @intCast(row), fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{}}, 0, null, false, bg_default); - const base = instances[row * 2]; - const ink = instances[row * 2 + 1]; - try std.testing.expectApproxEqAbs(@as(f32, 20.0 / 480.0 * 2), base.y0 - base.y1, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 16.0 / 480.0 * 2), ink.y0 - ink.y1, 0.0001); - try std.testing.expect(ink.y0 <= base.y0 and ink.y1 >= base.y1); - try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), ink.x1 - ink.x0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 10) / atlas_w, ink.u1 - ink.u0, 0.0001); - if (row > 0) try std.testing.expectApproxEqAbs(instances[(row - 1) * 2].y1, base.y0, 0.0001); - } - // Column 0 is an anchor's edge: its ink is inset by the band's margin - // (2 px here) and its underlay still covers the whole cell. - next = 0; - emitSurfaceCell(&g, &chrome, &instances, &next, 0, 1, fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{ .anchor = true }}, 0, null, false, bg_default); - try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), instances[0].x1 - instances[0].x0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 8.0 / 800.0 * 2), instances[1].x1 - instances[1].x0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 8) / atlas_w, instances[1].u1 - instances[1].u0, 0.0001); -} - fn emitInstance( g: *Gui, instances: [*]CellInstance, @@ -6350,45 +4955,11 @@ fn emitInstance( if (is_cursor) instances[idx].effect |= opaque_bg_bit; } -test "block cursor alone overrides transparent cell background" { - var g = testGui(10, 20, 6, 12); - const cell: pardes.Cell = .{}; - var instances: [2]CellInstance = undefined; - for ([_]bool{ false, true }, 0..) |cursor, i| { - emitInstance(&g, &instances, @intCast(i), 0, 0, fixedCellLayout(&g), 800, 480, .body, (&cell)[0..1], 0, null, cursor, bg_default); - try std.testing.expectEqual(cursor, instances[i].effect & opaque_bg_bit != 0); - } -} - fn cellCodepoint(cell: *const pardes.Cell) u32 { const grapheme = cell.grapheme(); return if (cell.default or grapheme.len == 0) ' ' else firstCp(grapheme); } -test "insert cursor overlays without replacing the character beneath it" { - const cell: pardes.Cell = .{ - .text = .{ 'x', ' ', ' ', ' ', ' ', ' ', ' ' }, - .len = 1, - .default = false, - }; - try std.testing.expectEqual(@as(u32, 'x'), cellCodepoint(&cell)); - - // A bar at a tag cell: tagline-tall, centered in its row, in the - // cell's ink, drawn as decor over it. - var cells: [25]pardes.Cell = @splat(.{}); - cells[3 * 5 + 2] = .{ .default = false, .style = .{ .fg = .{ .rgb = .{ 32, 48, 64 } }, .font_role = .tagline } }; - const surface: pardes.Surface = .{ .cols = 5, .rows = 5, .cells = &cells, .cursor = .{ .x = 2, .y = 3, .bar = true } }; - var g = testGui(10, 20, 8, 8); - defer g.decor.deinit(std.testing.allocator); - try cursorDecor(&g, std.testing.allocator, &surface, fixedCellLayout(&g), 100, 100); - try std.testing.expectEqual(@as(usize, 1), g.decor.items.len); - const bar = g.decor.items[0]; - try std.testing.expectApproxEqAbs(@as(f32, -0.32), bar.y0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, -0.48), bar.y1, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 32.0 / 255.0), bar.br, 0.0001); - try std.testing.expectEqual(@as(f32, 1), bar.fr); -} - fn palColor(idx: u8) [3]u8 { const p = ghostty_vt.color.default[idx]; return .{ p.r, p.g, p.b }; @@ -6669,120 +5240,6 @@ fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gu }; } -/// A Gui that can shape and rasterize `font` at `px`, and nothing else. From -/// here on the fonts allocate from std.testing.allocator (the caller puts -/// font_allocator back), so the test counts what they leak. -fn textTestGui(font: *c.UIFont, px: f32) !Gui { - c.ui_font_prime(font); - font_allocator = std.testing.allocator; - var cw: c_int = 0; - var ch: c_int = 0; - var ascent: c_int = 0; - c.ui_font_cell_metrics(font, px, &cw, &ch, &ascent); - const tag = taglineRaster(font, px, @intCast(cw), @intCast(ch), 82); - var g = testGui(@intCast(cw), @intCast(ch), tag.width, tag.height); - g.font = font; - g.px = px; - g.ascent = ascent; - g.tagline_px = tag.px; - g.tagline_baseline = tag.baseline; - g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); - g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); - resetGlyphAtlas(&g); - return g; -} - -fn textTestLine(comptime text: []const u8) [text.len]pardes.Cell { - var line: [text.len]pardes.Cell = @splat(.{ .default = false }); - for (&line, text) |*cell, byte| cell.text[0] = byte; - return line; -} - -test "a ligature draws across its cells, one slice each, and comes apart under the cursor" { - const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); - defer std.testing.allocator.free(bytes); - const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; - defer c.ui_font_free(font); - var g = try textTestGui(font, 27); - defer font_allocator = std.heap.smp_allocator; - defer std.testing.allocator.free(g.atlas_stage); - defer g.glyphs.deinit(); - defer g.words.deinit(std.testing.allocator); - - const line = textTestLine("a->b"); - var slots: [4]Slot = undefined; - for (&slots, 0..) |*slot, i| slot.* = cellSlot(&g, &line, i, null, .body); - // `->` is one glyph strip two cells wide: each cell samples its own half. - try std.testing.expectEqual(slots[1].v, slots[2].v); - try std.testing.expectEqual(slots[1].u + g.cell_w, slots[2].u); - var strips: usize = 0; - var it = g.glyphs.iterator(); - while (it.next()) |entry| if (entry.key_ptr.span == 2) { - strips += 1; - try std.testing.expectEqual(@as(u4, 1), entry.key_ptr.lead); - try std.testing.expectEqual(slots[1], entry.value_ptr.*); - }; - try std.testing.expectEqual(@as(usize, 1), strips); - // The arrow runs through the seam: both halves carry ink at it. - const seam = g.atlas_stage[@as(usize, slots[2].v) * atlas_w ..]; - var left_ink: usize = 0; - var right_ink: usize = 0; - for (0..g.cell_h) |y| { - left_ink += seam[y * atlas_w + slots[2].u - 1]; - right_ink += seam[y * atlas_w + slots[2].u]; - } - try std.testing.expect(left_ink > 0 and right_ink > 0); - // `a` and `b` are their plain glyphs. - try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'a'), .role = .body }).?, slots[0]); - try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'b'), .role = .body }).?, slots[3]); - - // A second line with the same word reuses the shaped slots. - const again = textTestLine("a->b"); - const text_len = g.words.text.items.len; - for (0..4) |i| try std.testing.expectEqual(slots[i], cellSlot(&g, &again, i, null, .body)); - try std.testing.expectEqual(text_len, g.words.text.items.len); - - // The cursor on either half shows plain `-` and `>`. - const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '-'), .role = .body }).?; - const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '>'), .role = .body }).?; - for ([_]usize{ 1, 2 }) |cursor| { - try std.testing.expectEqual(plain_minus, cellSlot(&g, &line, 1, cursor, .body)); - try std.testing.expectEqual(plain_greater, cellSlot(&g, &line, 2, cursor, .body)); - } - // A tagline is never shaped. - try std.testing.expectEqual(c.ui_font_glyph(font, '-'), (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph); -} - -fn glyphKeyAt(g: *Gui, slot: Slot) !GlyphKey { - var it = g.glyphs.iterator(); - while (it.next()) |entry| if (std.meta.eql(entry.value_ptr.*, slot)) return entry.key_ptr.*; - return error.NoGlyph; -} - -test "a font without ligatures draws every cell as its own glyph, exactly as before shaping" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var g = try textTestGui(font, 18); - defer font_allocator = std.heap.smp_allocator; - defer std.testing.allocator.free(g.atlas_stage); - defer g.glyphs.deinit(); - defer g.words.deinit(std.testing.allocator); - const text = "a->b != c => d <= e |> www == :: 0x1F"; - var line = textTestLine(text); - line[3].style.bold = true; // a style change inside a word - var expected: [64 * 64]u8 = undefined; - for (line, 0..) |cell, i| { - if (text[i] == ' ') continue; - const slot = cellSlot(&g, &line, i, null, .body); - const key = try glyphKeyAt(&g, slot); - try std.testing.expectEqual(c.ui_font_glyph(font, text[i]), key.glyph); - try std.testing.expectEqual(@as(u4, 1), key.span); - _ = c.ui_font_raster(font, 18, key.glyph, @intFromBool(cell.style.bold), &expected, 64, @intCast(g.cell_w), @intCast(g.cell_h), 0, @intCast(g.cell_w), g.ascent); - for (0..g.cell_h) |y| - try std.testing.expectEqualSlices(u8, expected[y * 64 ..][0..g.cell_w], g.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]); - } -} - /// The atlas slot of `key`, rasterized on first use. A strip is `span` cells /// wide (a grip glyph GUTTER cells, centered); a cell samples its slice of it. /// Null when the atlas is full. @@ -6846,84 +5303,6 @@ fn centerGlyphInk(out: [*]u8, width: usize, height: usize) void { } } -test "pane indicator cached ink centers bearings styles and sizes" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var g = testGui(10, 20, 6, 12); - g.font = font; - g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); - defer std.testing.allocator.free(g.atlas_stage); - g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); - defer g.glyphs.deinit(); - for ([_]f32{ 13, 27, 40 }) |px| { - g.px = px; - var cw: c_int = 0; - var ch: c_int = 0; - c.ui_font_cell_metrics(font, px, &cw, &ch, &g.ascent); - g.cell_w = @intCast(cw); - g.cell_h = @intCast(ch); - for ([_]u8{ 40, 82, 100 }) |percent| { - const tag = taglineRaster(font, px, g.cell_w, g.cell_h, percent); - g.tagline_width = tag.width; - g.tagline_height = tag.height; - g.tagline_px = tag.px; - g.tagline_baseline = tag.baseline; - resetGlyphAtlas(&g); - try std.testing.expectEqual(@as(usize, 0), g.glyphs.count()); - for ([_]u32{ '^', '$', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { - const key: GlyphKey = .{ .face = 0, .glyph = c.ui_font_glyph(font, @intCast(cp)), .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }; - const slot = cachedGlyph(&g, key).?; - const bounds = inkBounds(g.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?; - const center_x: isize = @intCast(bounds.min_x + bounds.max_x); - const center_y: isize = @intCast(bounds.min_y + bounds.max_y); - try std.testing.expect(@abs(center_x - @as(isize, @intCast(g.cell_w * config.GUTTER - 1))) <= 1); - try std.testing.expect(@abs(center_y - @as(isize, @intCast(tag.height - 1))) <= 1); - const count = g.glyphs.count(); - const pen = g.pen_x; - try std.testing.expectEqualDeep(slot, cachedGlyph(&g, key).?); - try std.testing.expectEqual(count, g.glyphs.count()); - try std.testing.expectEqual(pen, g.pen_x); - }; - } - } - resetGlyphAtlas(&g); - g.pen_y = atlas_h; - try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '^'), .role = .tagline, .centered = true })); -} - -test "pane indicator halves are safe on an exhausted atlas" { - var cells: [12]pardes.Cell = @splat(.{ .default = false, .style = .{ .font_role = .tagline } }); - cells[0].text[0] = '$'; - // A grip two cells wide at the top left. - const grip = [_]pardes.Region{.{ .kind = .grip, .serial = 1, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}; - var cover: [12]Cover = undefined; - coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); - try std.testing.expect(cover[0].grip and cover[1].grip and !cover[2].grip); - // A column's grip is a button too, cut the same way (it has no glyph). - coverFrame(&cover, 6, 2, &.{}, &.{}, &.{.{ .kind = .column_grip, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}); - try std.testing.expect(cover[0].grip); - coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); - const chrome: pardes.Chrome = .{}; - - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var g = testGui(10, 20, 8, 16); - g.font = font; - g.px = 20; - g.tagline_px = 16; - g.pen_y = atlas_h; - g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); - defer g.glyphs.deinit(); - defer g.words.deinit(std.testing.allocator); - var instances: [4]CellInstance = undefined; - var next: u32 = 0; - for (0..2) |col| { - emitSurfaceCell(&g, &chrome, &instances, &next, @intCast(col), 0, fixedCellLayout(&g), 100, 100, cells[0..6], cover[0..6], col, null, false, bg_default); - try std.testing.expectEqual(@as(f32, 0), instances[col * 2 + 1].u0); - } - try std.testing.expectEqual(@as(u32, 4), next); -} - // Underline and strikethrough stay inside the existing atlas slot, so text // advance, caret and selection geometry are identical to the regular glyph. // The cached mask keeps this work out of steady-state rendering and also @@ -6962,49 +5341,6 @@ fn decorateLine(out: [*]u8, stride: usize, width: usize, height: usize, baseline } } -test "a box-drawing rule reaches its cell's edges, and only its arms do" { - const stride = 12; - const width = 9; - const height = 15; - var mask: [stride * height]u8 = @splat(0xa5); - drawRule(&mask, stride, width, height, ruleArms(0x253c).?); - // ┼: ink on all four edges, none in the corners, nothing past the slot. - try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); - try std.testing.expectEqual(@as(u8, 255), mask[(height - 1) * stride + width / 2]); - try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride]); - try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride + width - 1]); - try std.testing.expectEqual(@as(u8, 0), mask[0]); - for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); - drawRule(&mask, stride, width, height, ruleArms(0x2502).?); - try std.testing.expectEqual(@as(u8, 0), mask[(height / 2) * stride]); - try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); - try std.testing.expect(ruleArms('|') == null); -} - -test "glyph decorations render spaces and stay inside their atlas slot" { - const stride = 9; - const width = 5; - const height = 7; - for ([_]GlyphDecoration{ - .{ .underline = .single }, - .{ .underline = .double }, - .{ .underline = .curly }, - .{ .underline = .dotted }, - .{ .underline = .dashed }, - .{ .strikethrough = true }, - }) |decoration| { - var mask: [stride * (height + 1)]u8 = @splat(0xa5); - for (0..height) |y| @memset(mask[y * stride ..][0..width], 0); - decorateLine(&mask, stride, width, height, 5, decoration); - try std.testing.expect(inkBounds(&mask, stride, width, height) != null); - for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| - try std.testing.expectEqual(@as(u8, 0xa5), guard); - for (mask[stride * height ..]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); - } - const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; - try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank()); -} - /// Uploads only the atlas rows drawn into since the last upload. Glyphs fill /// the atlas pen-style, a band of rows at a time, so new glyphs are a band a /// cell or two tall, not the whole 4 MB texture. The band sits at the same @@ -7027,49 +5363,6 @@ fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void { g.atlas_dirty_bottom = 0; } -test "the atlas's dirty rows hold every row a new glyph draws into, and a reset dirties them all" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var g = try textTestGui(font, 18); - defer font_allocator = std.heap.smp_allocator; - defer std.testing.allocator.free(g.atlas_stage); - defer g.glyphs.deinit(); - defer g.words.deinit(std.testing.allocator); - // The texture as uploadAtlas leaves it, which starts undefined. - const texture = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); - defer std.testing.allocator.free(texture); - @memset(texture, 0xa5); - var glyph: u32 = 0; - for (0..40) |frame| { - if (frame == 30) resetGlyphAtlas(&g); // a font change - // Plain glyphs, strips, taglines, grip glyphs and decorations. - for (0..25) |_| { - glyph += 1; - const span: u4 = @intCast(1 + glyph % 3); - _ = cachedGlyph(&g, .{ - .face = 0, - .glyph = glyph, - .role = if (glyph % 4 == 0) .tagline else .body, - .decoration = .{ .bold = glyph % 2 == 0, .underline = if (glyph % 5 == 0) .curly else .off, .strikethrough = glyph % 11 == 0 }, - .centered = glyph % 13 == 0, - .lead = @intCast(glyph % span), - .span = span, - }) orelse return error.AtlasFull; - } - for (0..atlas_h) |row| { - const stage = g.atlas_stage[row * atlas_w ..][0..atlas_w]; - const uploaded = texture[row * atlas_w ..][0..atlas_w]; - if (row >= g.atlas_dirty_top and row < g.atlas_dirty_bottom) - @memcpy(uploaded, stage) - else - try std.testing.expect(std.mem.eql(u8, stage, uploaded)); - } - g.atlas_dirty_top = atlas_h; - g.atlas_dirty_bottom = 0; - } - try std.testing.expect(g.pen_y >= 2 * g.cell_h); -} - /// A vertex buffer and its upload buffer holding at least `needed` /// elements of `stride` bytes: those there when they do, else twice as /// many again until they would (the old ones let go). @@ -7165,19 +5458,6 @@ fn backgroundLayerBlend() c.SDL_GPUColorTargetBlendState { return blend; } -test "overlapping background layers keep one uniform opacity" { - const blend = backgroundLayerBlend(); - try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR), blend.src_alpha_blendfactor); - try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA), blend.dst_alpha_blendfactor); - for ([_]f32{ 0, 0.25, 0.7, 1 }) |opacity| { - var alpha = opacity; - for ([_]f32{ 1, 0.5, 0.88, 0, 1 }) |coverage| { - alpha = opacity * coverage + alpha * (1 - coverage); - try std.testing.expectApproxEqAbs(opacity, alpha, 0.00001); - } - } -} - fn makeShader(device: *c.SDL_GPUDevice, code: []const u8, stage: c.SDL_GPUShaderStage, n_samplers: u32, n_uniform_buffers: u32) !*c.SDL_GPUShader { var info = std.mem.zeroes(c.SDL_GPUShaderCreateInfo); info.code = code.ptr; @@ -7331,15 +5611,6 @@ fn backgroundOpacity(percent: u8) f32 { return @as(f32, @floatFromInt(percent)) / 100; } -test "background opacity retains exact endpoints and percentage precision" { - try std.testing.expectEqual(@as(f32, 0), backgroundOpacity(0)); - try std.testing.expectEqual(@as(f32, 0.7), backgroundOpacity(70)); - try std.testing.expectEqual(@as(f32, 1), backgroundOpacity(100)); - for (0..100) |percent| { - try std.testing.expect(backgroundOpacity(@intCast(percent)) < backgroundOpacity(@intCast(percent + 1))); - } -} - /// PARDES_TEST_LATENCY trace for an external driver, CLOCK_MONOTONIC ns: /// `R t` when stdin input is read, `F start fence submit` per captured frame /// (present entry, the GPU fence of that frame, and its submission: submit - @@ -7768,39 +6039,6 @@ const encoded: [4096]u8 = blk: { break :blk table; }; -test "InactiveDim fades the unfocused panes' rows alone, never below the text's floor" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - core.sync(); - const s = try core.render(core.scratch.allocator()); - defer dim = .{}; - dim.begin(60, s.regionList()); - try std.testing.expect(dim.focused != pardes.Region.none); - var cover: [80 * 24]Cover = undefined; - coverFrame(&cover, 80, 24, &.{}, &.{}, s.regionList()); - var seen: [2]bool = .{ false, false }; - for (s.regionList()) |region| if (region.kind == .body or region.kind == .tag) { - const unfocused = region.owner != dim.focused; - try std.testing.expectEqual(unfocused, cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); - seen[@intFromBool(unfocused)] = true; - } else if (region.kind == .grip) try std.testing.expect(!cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); - try std.testing.expect(seen[0] and seen[1]); - // Toward the ground, a pair already near its floor no further. - var instance: CellInstance = std.mem.zeroes(CellInstance); - instance.fr = 0.9; - instance.fg = 0.9; - instance.fb = 0.9; - dim.fade(&instance); - try std.testing.expect(instance.fr < 0.9 and instance.fr > 0); - try std.testing.expect(pardes.colors.contrast(Dim.byteRgb(.{ instance.fr, instance.fg, instance.fb }), .{ 0, 0, 0 }) >= 4.5 - 1e-3); - // Off, nothing fades. - dim.begin(0, s.regionList()); - try std.testing.expect(!dim.of(0) and !dim.of(1)); -} - /// A logical pixel size in the display's pixels: rounded, at least one. fn dp(logical: f32) f32 { return @max(1, @round(logical * display_scale)); @@ -7881,287 +6119,6 @@ fn gripDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ce } } -test "a theme's own rules and scrollbar are drawn at its widths: acme's 2px black rules and 12px track" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); - for (0..40) |_| core.update(.tick); - core.sync(); - const s = try core.render(core.scratch.allocator()); - try std.testing.expectEqual(@as(u8, 2), s.chrome.rule_px); - // acme's 12px, at GripWidth's 150% default. - try std.testing.expectEqual(@as(u8, 18), s.chrome.rail_px); - var g = testGui(16, 20, 10, 12); - defer g.decor.deinit(gpa); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 480, true); - const px = struct { - fn w(item: CellInstance) f32 { - return (item.x1 - item.x0) / 2 * 1280; - } - }; - var spines: usize = 0; - var tracks: usize = 0; - for (g.decor.items) |item| { - const black = item.br == 0 and item.bg == 0 and item.bb == 0; - // No rule at the window's left edge; one 2px spine where columns meet. - if (black and @abs(px.w(item) - 2) < 0.01 and item.y1 < -0.9) { - try std.testing.expect(item.x0 > -1); - spines += 1; - } - const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); - if (@abs(item.br - @as(f32, 0x99) / 255) < 1e-3 and @abs(item.bb - @as(f32, 0x4c) / 255) < 1e-3 and @abs(px.w(item) - (column[1] - column[0])) < 0.01) tracks += 1; - } - try std.testing.expectEqual(@as(usize, 1), spines); - try std.testing.expect(tracks >= 2); -} - -test "the scrollbar thumb moves by the pixel and follows a glide" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - const thumb = struct { - // The thumb's top, in window pixels. - fn top(gui: *Gui, p: *pardes.Pardes) !f32 { - gui.decor.clearRetainingCapacity(); - p.sync(); - const s = try p.render(p.scratch.allocator()); - var groups: Groups = .{}; - try buildDecor(gui, std.testing.allocator, s, &groups, fixedCellLayout(gui), 800, 480, true); - const ink = s.chrome.scroll_thumb; - for (gui.decor.items) |item| if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and - @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and - @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) return (1 - item.y0) / 2 * 480; - return error.TestExpectedThumb; - } - }; - pane.file.?.scroll = 10; - const at10 = try thumb.top(&g, core); - pane.file.?.scroll = 11; - const at11 = try thumb.top(&g, core); - // A line of a thousand moves it a fraction of a row, not 0 or 20 px. - try std.testing.expect(at11 > at10 and at11 - at10 < 1); - g.glide.pane = core.view().active; - g.glide.follow.offset = -1; - try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); - // A wrapped line: the picture moved two rows for the one line, and the - // thumb lags the line, not two. - g.glide.lines_moved = 1; - g.glide.rows_moved = 2; - g.glide.follow.offset = -2; - try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); -} - -test "the scrollbar thumb lies in its scroll column, a pixel short of the column's right edge, so the track edges it" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - core.sync(); - const s = try core.render(core.scratch.allocator()); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); - const ink = s.chrome.scroll_thumb; - const thumb = for (g.decor.items) |item| { - if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and - @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and - @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) break item; - } else return error.TestExpectedThumb; - // The pane is the window's first: its scroll column is at cell 0. - const column = scrollColumn(&g, &s.chrome, 0, fixedCellLayout(&g)); - try std.testing.expectApproxEqAbs(column[0], (thumb.x0 + 1) / 2 * 800, 1e-3); - try std.testing.expectApproxEqAbs(column[1] - 1, (thumb.x1 + 1) / 2 * 800, 1e-3); -} - -test "the rule between stacked panes stays in the tag band's slack, at any tagline size" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - core.newScratchBelow(0); - core.sync(); - const s = try core.render(core.scratch.allocator()); - const lower = for (s.regionList()) |region| { - if (region.kind == .tag and region.rect.y > 2) break region; - } else return error.TestExpectedStackedTag; - for ([_]u32{ 12, 20 }) |tagline_h| { - var g = testGui(10, 20, 6, tagline_h); - defer g.decor.deinit(gpa); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); - const top = @as(f32, @floatFromInt(lower.rect.y)) * 20; - const slack: f32 = @floatFromInt(@max(1, pardes.Layer.taglineBandOffset(lower.rect.y, 480, 20, tagline_h))); - var found = false; - for (g.decor.items) |item| { - const y0 = (1 - item.y0) / 2 * 480; - const y1 = (1 - item.y1) / 2 * 480; - if (@abs(y0 - top) > 0.01 or @abs(item.br - @as(f32, @floatFromInt(s.chrome.border[0])) / 255) > 1e-3) continue; - found = true; - try std.testing.expect(y1 - y0 <= slack + 0.01); - } - try std.testing.expect(found); - } -} - -test "an empty column is ruled on both sides, as between two filled ones" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - // Newcol from the left pane: an empty column between the two filled ones. - pardes.layout.newColumn(core, 0); - core.sync(); - try std.testing.expectEqual(@as(usize, 3), core.view().ncol); - try std.testing.expectEqual(@as(usize, 0), core.view().cols[1].n); - const s = try core.render(core.scratch.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - const layout = fixedCellLayout(&g); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); - const border = [3]f32{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 }; - // Its left edge and its right edge (the next column's left): each a - // rule `rule_px` wide in the border colour, down to the window's foot. - for ([_]usize{ 1, 2 }) |column| { - const px: f32 = @floatFromInt(@as(u32, core.view().col_x[column]) * 10); - const rule = for (g.decor.items) |item| { - if (@abs(item.x0 - (px / 800 * 2 - 1)) < 1e-4 and @abs(item.x1 - ((px + @as(f32, @floatFromInt(s.chrome.rule_px))) / 800 * 2 - 1)) < 1e-4 and - std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &border)) break item; - } else return error.TestExpectedColumnRule; - try std.testing.expectEqual(@as(f32, -1), rule.y1); - } -} - -test "at a 2x display every logical pixel is two: rules, the tag rule, the grip's ring, the rail's edge" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); - for (0..40) |_| core.update(.tick); - core.sync(); - const s = try core.render(core.scratch.allocator()); - for ([_]f32{ 1, 2 }) |scale| { - display_scale = scale; - defer display_scale = 1; - var g = testGui(16, 32, 12, 24); - defer g.decor.deinit(gpa); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 768, true); - const w = struct { - fn of(item: CellInstance) f32 { - return (item.x1 - item.x0) / 2 * 1280; - } - fn h(item: CellInstance) f32 { - return (item.y0 - item.y1) / 2 * 768; - } - }; - var spine: ?f32 = null; - var tag_rule: ?f32 = null; - var ring: ?f32 = null; - for (g.decor.items) |item| { - const rgb: [3]u8 = .{ @intFromFloat(@round(item.br * 255)), @intFromFloat(@round(item.bg * 255)), @intFromFloat(@round(item.bb * 255)) }; - // The spine between the columns: black, tall. - if (std.mem.eql(u8, &rgb, &.{ 0, 0, 0 }) and w.h(item) > 300) spine = @round(w.of(item)); - // The tag rule: #8888cc, wide and thin. - if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.of(item) > 200) tag_rule = @round(w.h(item)); - // The ring's left side: #8888cc, a tag row tall. - if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.h(item) > 10 and w.of(item) < 8) ring = @round(w.of(item)); - } - try std.testing.expectEqual(@as(?f32, 2 * scale), spine); - try std.testing.expectEqual(@as(?f32, 1 * scale), tag_rule); - try std.testing.expectEqual(@as(?f32, 2 * scale), ring); - // The rail starts after the rule, a logical 2 in, and keeps a - // logical 3 clear of the text when the cell is narrow. - const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); - try std.testing.expectEqual(40 * 16 + 2 * scale, column[0]); - g.cell_w = 12; - defer g.cell_w = 16; - const narrow = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); - try std.testing.expectEqual(@as(f32, 40 * 12 + 2 * scale), narrow[0]); - try std.testing.expectEqual(@as(f32, 40 * 12) + 12 * @as(f32, @floatFromInt(config.GUTTER)) - 3 * scale, narrow[1]); - g.cell_w = 8; - // A bar cursor is an eighth of its cell, never under a logical pixel - // (an 8 px cell: one pixel, two at 2x). - const saved = s.cursor; - defer s.cursor = saved; - s.cursor = .{ .x = 60, .y = 10, .bar = true }; - var boxes: [max_cursors]CursorBox = undefined; - const n = cursorBoxes(&g, s, fixedCellLayout(&g), 768, &boxes); - const bar = for (boxes[0..n]) |box| { - if (box.bar and box.x0 == 60 * 8) break box; - } else return error.NoBarCursor; - try std.testing.expectEqual(scale, bar.x1 - bar.x0); - } -} - -test "decor is read from the regions" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - core.sync(); - const s = try core.render(core.scratch.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - const layout = fixedCellLayout(&g); - const ndc = struct { - fn x(px: f32) f32 { - return px / 800 * 2 - 1; - } - }; - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); - // A spine one pixel wide at each column's left edge, down from under the - // workspace tag; a rail two pixels wide at each pane's. - for (core.view().col_x[0..core.view().ncol]) |x| { - const left = ndc.x(@as(f32, @floatFromInt(x)) * 10); - // Two pixels (rule_px), and none at the window's own edge. - const spine = for (g.decor.items) |item| { - if (item.x0 == left and @abs(item.x1 - ndc.x(@as(f32, @floatFromInt(x)) * 10 + 2)) < 0.0001 and - @abs(item.y0 - (1 - 20.0 / 480.0 * 2)) < 0.0001 and std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &.{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 })) break item; - } else null; - try std.testing.expectEqual(x == 0, spine == null); - if (spine) |rule| { - try std.testing.expectApproxEqAbs(@as(f32, 1 - 20.0 / 480.0 * 2), rule.y0, 0.0001); - try std.testing.expectEqual(@as(f32, -1), rule.y1); - } - // The scrollbar fills the scroll column right of the rule. - const column = scrollColumn(&g, &s.chrome, x, layout); - const rail = for (g.decor.items) |item| { - if (@abs(item.x0 - ndc.x(column[0])) < 0.0001 and @abs(item.x1 - ndc.x(column[1])) < 0.0001 and - @abs(item.br - @as(f32, @floatFromInt(s.chrome.scroll_track[0])) / 255) < 0.0001) break item; - } else return error.TestExpectedRail; - _ = rail; - } - try std.testing.expectEqual(@as(u32, 0), groups.items[groups.notices].decor_count); -} - -test "a body tells its first line" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([80][5]u8, @splat("line\n".*)))); - pane.scrollBy(8); - core.sync(); - const s = try core.render(core.scratch.allocator()); - const body = for (s.regionList()) |region| { - if (region.kind == .body) break region; - } else return error.NoBody; - try std.testing.expectEqual(@as(i32, 8), body.line); -} - const CursorBox = struct { x0: f32, y0: f32, x1: f32, y1: f32, rgb: [3]u8, bar: bool }; const max_cursors = 1 + pardes.MAX_PANES + pardes.MAX_TAG_LAYERS; @@ -8406,32 +6363,6 @@ const Caret = struct { } }; -test "a caret eases a cell at a time, keeps up with typing, and glides a jump, landing exactly" { - const ms = std.time.ns_per_ms; - var caret: Caret = .{}; - caret.aim(.{ .x = 3, .y = 4, .w = 1, .h = 1 }, 0, false); - // The first mark lands at once. - try std.testing.expect(!caret.moving()); - // A step eases, a stream of them keeps up. - caret.aim(.{ .x = 4, .y = 4, .w = 1, .h = 1 }, 1000 * ms, false); - try std.testing.expect(caret.moving()); - caret.aim(.{ .x = 5, .y = 4, .w = 1, .h = 1 }, 1050 * ms, false); - try std.testing.expect(!caret.moving()); - // A jump glides, the leading corner ahead, and lands exactly. - caret.aim(.{ .x = 30, .y = 10, .w = 1, .h = 1 }, 2000 * ms, false); - try std.testing.expect(caret.moving()); - const mid = caret.sample(2040 * ms); - try std.testing.expect(mid[1][0] > mid[0][0] - 1 and mid[0][0] > 5 and mid[0][0] < 30); - var t: u64 = 2040 * ms; - while (caret.step(t)) t += 16 * ms; - try std.testing.expect(t < 2400 * ms); - try std.testing.expectEqual([2]f32{ 30, 10 }, caret.sample(t)[0]); - // A scroll lands it with its text. - caret.see(.{ .x = 30, .y = 8, .w = 1, .h = 1 }, 0, 10, 2, 1, t); - caret.see(.{ .x = 30, .y = 6, .w = 1, .h = 1 }, 0, 12, 2, 1, t + 16 * ms); - try std.testing.expect(!caret.moving()); -} - /// The rows a caret whose line rode the wheel's glide is drawn above its /// cell: the text's own offset, so it moves with its line as a glyph does /// (its springs landed on the cell, Caret.see). @@ -8452,54 +6383,6 @@ fn caretRide(g: *const Gui, surface: *const pardes.Surface) f32 { return g.scroll_lag; } -/// Every cursor on the frame where it is drawn, in window pixels: the grid's -/// where no layer has its cell, and each layer's at that layer's pitch. A bar -/// is an eighth of its cell wide, a block the whole cell. -fn cursorBoxes(g: *const Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, out: *[max_cursors]CursorBox) usize { - const chrome = &surface.chrome; - var n: usize = 0; - if (surface.cursor) |cursor| { - if (cursor.x < surface.cols and cursor.y < surface.rows and bodyLayerIn(surface.bodyLayers(), cursor.x, cursor.y) == null and tagLayerIn(surface.tagLayers(), cursor.x, cursor.y) == null) { - const cell = &surface.cells[@as(usize, cursor.y) * surface.cols + cursor.x]; - const role = cellFontRole(cell); - const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; - const height = std.math.clamp(if (role == .tagline) @as(f32, @floatFromInt(g.tagline_height)) else layout.h, 1.0, layout.h); - const x0 = @as(f32, @floatFromInt(cursor.x)) * layout.w; - const y0 = @as(f32, @floatFromInt(cursor.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(cursor.y, win_h, @intFromFloat(layout.h), @intFromFloat(height)))); - out[n] = .{ .x0 = x0, .y0 = y0, .x1 = x0 + if (cursor.bar) @max(dp(1), width / 8.0) else width, .y1 = y0 + height, .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; - n += 1; - } - } - for (surface.bodyLayers()) |*layer| { - if (layer.rows == 0) continue; - const cursor = layer.cursor orelse continue; - if (cursor.y >= layer.rows or cursor.x >= layer.cols) continue; - const left = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; - const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * layout.h; - const top = layer.rowTop(cursor.y, layout.h, @floatFromInt(g.tagline_height)); - if (top >= bottom) continue; - const height = layer.rowHeight(cursor.y, layout.h, @floatFromInt(g.tagline_height)); - const role: pardes.FontRole = if (cursor.y < layer.context_rows) .tagline else .body; - const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; - const x = left + @as(f32, @floatFromInt(cursor.x)) * width; - const cell = &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x]; - out[n] = .{ .x0 = x, .y0 = top, .x1 = x + if (cursor.bar) @max(dp(1), width / 8) else width, .y1 = @min(bottom, top + height), .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; - n += 1; - } - for (surface.tagLayers()) |*layer| { - if (layer.rows == 0) continue; - const cursor = layer.cursor orelse continue; - if (cursor.x >= layer.cols or cursor.y >= layer.rows) continue; - const width: f32 = @floatFromInt(g.tagline_width); - const span = layer.caretSpan(cursor.x, layout.w, width, if (cursor.bar) @max(dp(1), width / 8) else width); - const y = layer.viewport.y + cursor.y; - const top = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))); - out[n] = .{ .x0 = span[0], .y0 = top, .x1 = span[1], .y1 = top + @as(f32, @floatFromInt(g.tagline_height)), .rgb = cursorColor(chrome, &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x], .tagline), .bar = cursor.bar }; - n += 1; - } - return n; -} - /// The bar cursors as decor; a block cursor is its cell's own colours. fn cursorDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32) !void { var boxes: [max_cursors]CursorBox = undefined; @@ -8577,35 +6460,6 @@ fn appendJumpTrail(g: *Gui, on: bool, surface: *const pardes.Surface, now_ns: u6 } } -test "a jump's trail is drawn behind the cursor in its body, and gone by 120 ms" { - var cells: [80 * 4]pardes.Cell = @splat(.{}); - var surface: pardes.Surface = .{ .cols = 80, .rows = 4, .cells = &cells }; - surface.regions[0] = .{ .kind = .body, .rect = .{ .x = 2, .y = 0, .w = 78, .h = 4 } }; - surface.nregions = 1; - var g = testGui(10, 20, 8, 16); - var vertices: [5 * 6]OverlayVertex = undefined; - var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 80 }; - const ms = std.time.ns_per_ms; - surface.cursor = .{ .x = 4, .y = 1 }; - appendJumpTrail(&g, true, &surface, 1000 * ms, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); - surface.cursor = .{ .x = 14, .y = 1 }; - appendJumpTrail(&g, true, &surface, 1016 * ms, &builder); - try std.testing.expect(builder.len >= 3 * 6 and builder.len <= 5 * 6); - // On the cursor's row, behind it, never its own cell. - for (vertices[0..builder.len]) |v| { - const x = (v.x + 1) * 400; - const y = (1 - v.y) * 40; - try std.testing.expect(y >= 20 - 0.01 and y <= 40 + 0.01); - try std.testing.expect(x >= 50 - 0.01 and x <= 140 + 0.01); - } - try std.testing.expect(g.trail.active); - builder.len = 0; - appendJumpTrail(&g, true, &surface, 1150 * ms, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); - try std.testing.expect(!g.trail.active); -} - /// The workspace tag's pet (the Pet setting, gui/pet.zig): in the blank /// end of the grid's first row, past the tag's text, in the tag's colours, /// on the window's own clock. Nothing of it reaches the core. @@ -8649,32 +6503,6 @@ fn appendWorkspacePet(g: *Gui, which: pardes.config.Runtime.Pet, surface: *const }; } -test "a pet stays past the workspace tag's text, and off it is gone" { - std.testing.refAllDecls(pet); - var cells: [80]pardes.Cell = @splat(.{}); - const surface: pardes.Surface = .{ .cols = 80, .rows = 1, .cells = &cells }; - for ("Workspace Commands", 0..) |ch, i| { - cells[i].text[0] = ch; - cells[i].len = 1; - cells[i].default = false; - } - var g = testGui(10, 20, 8, 16); - var vertices: [pet.max_vertices]OverlayVertex = undefined; - var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 480 }; - appendWorkspacePet(&g, .cat, &surface, &builder); - try std.testing.expect(builder.len > 0); - for (vertices[0..builder.len]) |v| { - const x = (v.x + 1) * 400; - const y = (1 - v.y) * 240; - try std.testing.expect(x >= 20 * 8 - 0.01); - try std.testing.expect(y >= 0 and y < 20); - } - builder.len = 0; - appendWorkspacePet(&g, .off, &surface, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); - try std.testing.expectEqual(@as(?u64, null), g.pet_state.tick); -} - fn overlayRgb(rgb: [3]u8) OverlayColor { return .{ .r = @as(f32, @floatFromInt(rgb[0])) / 255.0, @@ -8725,13 +6553,6 @@ fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, now_ns: u64, build builder.addTri(px[0][0], px[0][1], px[2][0], px[2][1], px[3][0], px[3][1], color); } -fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: pardes.FontRole) [3]u8 { - return if (role == .tagline) switch (cell.style.fg) { - .rgb => |rgb| rgb, - else => chrome.tag_fg, - } else chrome.fg orelse fg_default; -} - fn uploadOverlayGpu(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, vertex_count: u32) bool { const byte_len: u32 = vertex_count * @sizeOf(OverlayVertex); const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.overlay_vxfer, false) orelse return false; @@ -8809,6 +6630,2185 @@ fn envU16(env: *std.process.Environ.Map, name: []const u8) ?u16 { return std.fmt.parseInt(u16, raw, 10) catch null; } +fn pixelCell(px: f32, cell: u32) u16 { + const idx = @floor(@max(px, 0) / @as(f32, @floatFromInt(@max(cell, 1)))); + return @intFromFloat(@min(idx, 10_000)); +} + +fn wheelRunFile(gpa: std.mem.Allocator) !*pardes.Pardes { + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + errdefer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..400) |i| try text.print(gpa, "{d:0>4} a line of the file\n", .{i}); + _ = try core.setTestFile(text.items); + for ("200G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); + return core; +} + +fn tagLayerIn(layers: []const pardes.Layer, col: u16, row: u16) ?*const pardes.Layer { + for (layers) |*layer| { + const r = layer.viewport; + if (layer.rows > 0 and row >= r.y and row - r.y < layer.rows and col >= r.x and col - r.x < r.w) return layer; + } + return null; +} + +fn expectCoverIsScan(cover: []const Cover, cols: u16, rows: u16, body_layers: []const pardes.Layer, tag_layers: []const pardes.Layer) !void { + for (0..rows) |row| for (0..cols) |col| { + const scan = bodyLayerIn(body_layers, @intCast(col), @intCast(row)) != null or tagLayerIn(tag_layers, @intCast(col), @intCast(row)) != null; + try std.testing.expectEqual(scan, cover[row * cols + col].layer); + }; +} + +/// A Gui that can shape and rasterize `font` at `px`, and nothing else. From +/// here on the fonts allocate from std.testing.allocator (the caller puts +/// font_allocator back), so the test counts what they leak. +fn textTestGui(font: *c.UIFont, px: f32) !Gui { + c.ui_font_prime(font); + font_allocator = std.testing.allocator; + var cw: c_int = 0; + var ch: c_int = 0; + var ascent: c_int = 0; + c.ui_font_cell_metrics(font, px, &cw, &ch, &ascent); + const tag = taglineRaster(font, px, @intCast(cw), @intCast(ch), 82); + var g = testGui(@intCast(cw), @intCast(ch), tag.width, tag.height); + g.font = font; + g.px = px; + g.ascent = ascent; + g.tagline_px = tag.px; + g.tagline_baseline = tag.baseline; + g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); + g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); + resetGlyphAtlas(&g); + return g; +} + +fn textTestLine(comptime text: []const u8) [text.len]pardes.Cell { + var line: [text.len]pardes.Cell = @splat(.{ .default = false }); + for (&line, text) |*cell, byte| cell.text[0] = byte; + return line; +} + +fn glyphKeyAt(g: *Gui, slot: Slot) !GlyphKey { + var it = g.glyphs.iterator(); + while (it.next()) |entry| if (std.meta.eql(entry.value_ptr.*, slot)) return entry.key_ptr.*; + return error.NoGlyph; +} + +/// Every cursor on the frame where it is drawn, in window pixels: the grid's +/// where no layer has its cell, and each layer's at that layer's pitch. A bar +/// is an eighth of its cell wide, a block the whole cell. +fn cursorBoxes(g: *const Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, out: *[max_cursors]CursorBox) usize { + const chrome = &surface.chrome; + var n: usize = 0; + if (surface.cursor) |cursor| { + if (cursor.x < surface.cols and cursor.y < surface.rows and bodyLayerIn(surface.bodyLayers(), cursor.x, cursor.y) == null and tagLayerIn(surface.tagLayers(), cursor.x, cursor.y) == null) { + const cell = &surface.cells[@as(usize, cursor.y) * surface.cols + cursor.x]; + const role = cellFontRole(cell); + const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; + const height = std.math.clamp(if (role == .tagline) @as(f32, @floatFromInt(g.tagline_height)) else layout.h, 1.0, layout.h); + const x0 = @as(f32, @floatFromInt(cursor.x)) * layout.w; + const y0 = @as(f32, @floatFromInt(cursor.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(cursor.y, win_h, @intFromFloat(layout.h), @intFromFloat(height)))); + out[n] = .{ .x0 = x0, .y0 = y0, .x1 = x0 + if (cursor.bar) @max(dp(1), width / 8.0) else width, .y1 = y0 + height, .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; + n += 1; + } + } + for (surface.bodyLayers()) |*layer| { + if (layer.rows == 0) continue; + const cursor = layer.cursor orelse continue; + if (cursor.y >= layer.rows or cursor.x >= layer.cols) continue; + const left = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; + const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * layout.h; + const top = layer.rowTop(cursor.y, layout.h, @floatFromInt(g.tagline_height)); + if (top >= bottom) continue; + const height = layer.rowHeight(cursor.y, layout.h, @floatFromInt(g.tagline_height)); + const role: pardes.FontRole = if (cursor.y < layer.context_rows) .tagline else .body; + const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; + const x = left + @as(f32, @floatFromInt(cursor.x)) * width; + const cell = &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x]; + out[n] = .{ .x0 = x, .y0 = top, .x1 = x + if (cursor.bar) @max(dp(1), width / 8) else width, .y1 = @min(bottom, top + height), .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; + n += 1; + } + for (surface.tagLayers()) |*layer| { + if (layer.rows == 0) continue; + const cursor = layer.cursor orelse continue; + if (cursor.x >= layer.cols or cursor.y >= layer.rows) continue; + const width: f32 = @floatFromInt(g.tagline_width); + const span = layer.caretSpan(cursor.x, layout.w, width, if (cursor.bar) @max(dp(1), width / 8) else width); + const y = layer.viewport.y + cursor.y; + const top = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))); + out[n] = .{ .x0 = span[0], .y0 = top, .x1 = span[1], .y1 = top + @as(f32, @floatFromInt(g.tagline_height)), .rgb = cursorColor(chrome, &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x], .tagline), .bar = cursor.bar }; + n += 1; + } + return n; +} + +fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: pardes.FontRole) [3]u8 { + return if (role == .tagline) switch (cell.style.fg) { + .rgb => |rgb| rgb, + else => chrome.tag_fg, + } else chrome.fg orelse fg_default; +} + +test "FreeType and HarfBuzz allocate from the gui allocator and give it all back" { + // HarfBuzz's process-wide objects come from the default heap, as in runNative. + const primer = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + c.ui_font_prime(primer); + c.ui_font_free(primer); + font_allocator = std.testing.allocator; + defer font_allocator = std.heap.smp_allocator; + + const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + defer c.ui_font_free(font); + var mask: [64 * 64]u8 = undefined; + try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, 27, c.ui_font_glyph(font, 'g'), 1, &mask, 64, 32, 48, 0, 32, 30)); + try std.testing.expectEqual(@as(c_int, 0), c.ui_font_substitutes(font, c.ui_font_glyph(font, '-'))); + + // A font with ligatures runs the whole HarfBuzz pass. + const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); + defer std.testing.allocator.free(bytes); + const maple = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; + defer c.ui_font_free(maple); + var cell_w: c_int = 0; + var cell_h: c_int = 0; + var ascent: c_int = 0; + c.ui_font_cell_metrics(maple, 27, &cell_w, &cell_h, &ascent); + const text = [_]u32{ 'a', '-', '>', 'b', '=', '=' }; + var shaped: [text.len]c.UIShapedCell = undefined; + c.ui_font_shape(maple, 27, cell_w, &text, text.len, &shaped); + try std.testing.expectEqual(@as(u8, 2), shaped[1].span); + try std.testing.expectEqual(@as(u8, 2), shaped[4].span); +} + +test "every font size step moves the cell, and the ends are reachable exactly" { + const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + defer c.ui_font_free(font); + var px = font_px_min + font_px_step; + while (px <= font_px_max) : (px += 1.0) { + var cw: c_int = 0; + var ch: c_int = 0; + var asc: c_int = 0; + var pw: c_int = 0; + var ph: c_int = 0; + c.ui_font_cell_metrics(font, px, &cw, &ch, &asc); + c.ui_font_cell_metrics(font, px - font_px_step, &pw, &ph, &asc); + try std.testing.expect(cw > pw and ch > ph); + } + try std.testing.expectEqual(font_px_max, std.math.clamp(font_px_max + font_px_step, font_px_min, font_px_max)); + try std.testing.expectEqual(font_px_min, std.math.clamp(font_px_min - font_px_step, font_px_min, font_px_max)); +} + +test "FreeType atlas raster is grayscale, bounded, and clears blank cells" { + const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + defer c.ui_font_free(font); + const h = c.ui_font_glyph(font, 'H'); + try std.testing.expect(h != 0); + try std.testing.expectEqual(@as(u32, 0), c.ui_font_glyph(font, 0x10ffff)); + + const size: f32 = 13.0; + var cell_w: c_int = 0; + var cell_h: c_int = 0; + var ascent: c_int = 0; + c.ui_font_cell_metrics(font, size, &cell_w, &cell_h, &ascent); + try std.testing.expect(cell_w > 0 and cell_w <= 128); + try std.testing.expect(cell_h > 0 and cell_h <= 128); + + const stride: c_int = 128; + var bitmap: [128 * 128]u8 = @splat(0xaa); + try std.testing.expectEqual( + @as(c_int, 1), + c.ui_font_raster(font, size, h, 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), + ); + + var ink: usize = 0; + var soft: usize = 0; + var regular_coverage: usize = 0; + for (0..@intCast(cell_h)) |y| { + for (0..@intCast(cell_w)) |x| { + const coverage = bitmap[y * @as(usize, @intCast(stride)) + x]; + if (coverage > 0) ink += 1; + if (coverage > 0 and coverage < 255) soft += 1; + regular_coverage += coverage; + } + } + try std.testing.expect(ink > 0); + try std.testing.expect(soft > 0); + // Synthetic bold thickens the outline inside the same cell. + try std.testing.expectEqual( + @as(c_int, 1), + c.ui_font_raster(font, size, h, 1, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), + ); + var bold_coverage: usize = 0; + for (0..@intCast(cell_h)) |y| { + for (0..@intCast(cell_w)) |x| bold_coverage += bitmap[y * @as(usize, @intCast(stride)) + x]; + for (bitmap[y * @as(usize, @intCast(stride)) + @as(usize, @intCast(cell_w)) ..][0..@intCast(stride - cell_w)]) |guard| + try std.testing.expectEqual(@as(u8, 0xaa), guard); + } + try std.testing.expect(bold_coverage > regular_coverage); + + try std.testing.expectEqual( + @as(c_int, 0), + c.ui_font_raster(font, size, c.ui_font_glyph(font, ' '), 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), + ); + for (0..@intCast(cell_h)) |y| + for (0..@intCast(cell_w)) |x| + try std.testing.expectEqual( + @as(u8, 0), + bitmap[y * @as(usize, @intCast(stride)) + x], + ); +} + +test "tagline glyph shrinks into its own cell and stays vertically centered" { + const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + defer c.ui_font_free(font); + + const body_px: f32 = 27.0; + var cell_w: c_int = 1; + var cell_h: c_int = 1; + var body_ascent: c_int = 1; + c.ui_font_cell_metrics(font, body_px, &cell_w, &cell_h, &body_ascent); + const tag = taglineRaster(font, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent); + try std.testing.expect(tag.px < body_px); + try std.testing.expect(tag.width < @as(u32, @intCast(cell_w))); + + const stride: c_int = 128; + var body: [128 * 128]u8 = @splat(0); + var tagline: [128 * 128]u8 = @splat(0); + const h = c.ui_font_glyph(font, 'H'); + try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, body_px, h, 0, &body, stride, cell_w, cell_h, 0, cell_w, body_ascent)); + try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, tag.px, h, 0, &tagline, stride, @intCast(tag.width), @intCast(tag.height), 0, @intCast(tag.width), tag.baseline)); + const b = inkBounds(&body, @intCast(stride), @intCast(cell_w), @intCast(cell_h)).?; + const t = inkBounds(&tagline, @intCast(stride), @intCast(tag.width), @intCast(tag.height)).?; + try std.testing.expect(t.max_x - t.min_x < b.max_x - b.min_x); + try std.testing.expect(t.max_y - t.min_y < b.max_y - b.min_y); + const body_center_x: isize = @intCast(b.min_x + b.max_x); + const tag_center_x: isize = @intCast(t.min_x + t.max_x); + const body_center_y: isize = @intCast(b.min_y + b.max_y); + const centered_top: isize = @intCast((@as(u32, @intCast(cell_h)) - tag.height) / 2); + const tag_center_y: isize = @as(isize, @intCast(t.min_y + t.max_y)) + centered_top * 2; + const body_slot_center: isize = @intCast(@as(u32, @intCast(cell_w)) - 1); + const tag_slot_center: isize = @intCast(tag.width - 1); + try std.testing.expect(@abs((tag_center_x - tag_slot_center) - (body_center_x - body_slot_center)) <= 2); + try std.testing.expect(@abs(tag_center_y - body_center_y) <= 4); + try std.testing.expect(tag.height < @as(u32, @intCast(cell_h))); +} + +test "tagline percentage changes measured band height without body metrics" { + const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + defer c.ui_font_free(font); + var cell_w: c_int = 1; + var cell_h: c_int = 1; + var ascent: c_int = 1; + c.ui_font_cell_metrics(font, 27.0, &cell_w, &cell_h, &ascent); + const small = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 40); + const configured = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 82); + const full = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 100); + try std.testing.expect(small.width < configured.width); + try std.testing.expect(configured.width <= full.width); + try std.testing.expectEqual(@as(u32, @intCast(cell_w)), full.width); + try std.testing.expect(small.height < configured.height); + try std.testing.expect(configured.height <= full.height); + try std.testing.expect(full.height <= @as(u32, @intCast(cell_h))); +} + +test "installed Nerd Symbols fallback covers Yazi directory icons" { + try std.testing.expectEqualStrings("SymbolsNerdFont-Regular", fonts.fallback_names[2]); + + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const candidate = for (fonts.fallbacks(arena_state.allocator())) |font| { + if (std.mem.eql(u8, font.name, "SymbolsNerdFont-Regular")) break font; + } else return; + + const bytes = try filesystem.readFile(std.testing.allocator, candidate.path); + defer std.testing.allocator.free(bytes); + const face = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; + defer c.ui_font_free(face); + try std.testing.expect(c.ui_font_glyph(face, 0xe5ff) != 0); +} + +test "the shader instance ABI: the flags after the colours, the clip after them" { + try std.testing.expectEqual(@as(usize, 76), @sizeOf(CellInstance)); + try std.testing.expectEqual(@as(usize, 56), @offsetOf(CellInstance, "effect")); + try std.testing.expectEqual(@as(usize, 60), @offsetOf(CellInstance, "clip_x0")); + try std.testing.expectEqual(@as(usize, 32), @sizeOf(ImageInstance)); +} + +test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + var shell: Shell = undefined; + shell.core = core; + shell.gpa = gpa; + shell.ptys = &ptys; + shell.gens = &gens; + shell.queue = &queue; + defer shell.shutdownPtys(); + const rcs: host_io.Shell.PromptFiles = .{}; + const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; + ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); + try std.testing.expect(host_io.writeFd(child.file.handle, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n")); + var bytes: std.ArrayList(u8) = .empty; + defer bytes.deinit(gpa); + var eof = false; + const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; + while (!eof and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + for (batch.slice()) |msg| switch (msg) { + .output => |o| { + try std.testing.expect(!eof); + try bytes.appendSlice(gpa, o.bytes); + }, + .eof => |e| { + try std.testing.expect(e.failure == null); + eof = true; + }, + else => return error.UnexpectedMessage, + }; + if (!eof) try std.testing.io.sleep(.fromMilliseconds(1), .awake); + } + try std.testing.expect(eof); + try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null); + shell.closePty(0); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expect(ptys[0] == null or ptys[0].?.reader == null); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); +} + +test "GUI PTY Restore joins a real reader waiting for queue space" { + const gpa = std.testing.allocator; + var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + try dump.dumpState(core); + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(1, 1); + for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 1, .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + var shell: Shell = undefined; + shell.core = core; + shell.gpa = gpa; + shell.ptys = &ptys; + shell.gens = &gens; + shell.queue = &queue; + defer shell.shutdownPtys(); + const rcs: host_io.Shell.PromptFiles = .{}; + const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; + ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); + try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); + try host_io.PtyTests.waitBlocked(&queue); + const old_serial = core.panes[0].?.serial; + const replacement = try dump.restore(core, core.dump_out.?, "test"); + shell.stopPtys(); + core.deinit(); + core = replacement; + shell.core = replacement; + // The dump's pane, its serial too; its old shell stopped all the same. + try std.testing.expectEqual(old_serial, core.panes[0].?.serial); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); + queue.cancelReader(1, 1); + queue.acceptReader(0, gens[0]); + queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); + try std.testing.expect(queue.pushOutput(0, gens[0], try gpa.dupe(u8, "fresh"))); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expectEqualStrings("fresh", batch.items[0].output.bytes); +} + +test "GUI PTY deletion joins an idle reader and its shell is reaped by exit" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + var shell: Shell = undefined; + shell.core = core; + shell.gpa = gpa; + shell.ptys = &ptys; + shell.gens = &gens; + shell.queue = &queue; + defer shell.shutdownPtys(); + const rcs: host_io.Shell.PromptFiles = .{}; + const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; + ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); + try core.removePane(0, null); + shell.reconcilePtys(); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); + shell.shutdownPtys(); + try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(child.pid, null, libc.W.NOHANG)); + try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1)); +} + +test "GUI PTY file watcher stops and joins without closing its watched descriptor" { + if (!file_watch.supported) return error.SkipZigTest; + const gpa = std.testing.allocator; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + const fd = file_watch.init(true); + if (fd < 0) return error.WatchInitFailed; + defer _ = libc.close(fd); + const stop = try stopPipe(); + defer for (stop) |pipe_fd| { + _ = libc.close(pipe_fd); + }; + const thread = try std.Thread.spawn(.{}, watchThread, .{ fd, stop[0], &queue }); + _ = host_io.writeFd(stop[1], "x"); + thread.join(); + try std.testing.expect(libc.fcntl(fd, libc.F.GETFD) >= 0); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); +} + +test "GUI completion failure survives backlog and leaves the document unchanged" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("abc"); + pane.body.cur_col = 1; + core.lspRequest(core.view().active, .completion, ""); + const id = core.lsp_ask.wait.?.id; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = id }; + defer queue.deinit(); + queue.acceptReader(0, 1); + for (0..output_capacity) |_| queue.push(.{ .output = .{ + .pane = 0, + .gen = 1, + .bytes = try gpa.dupe(u8, "output"), + } }); + queue.push(.{ .lsp = .{ .id = id, .rows = null } }); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var shell: Shell = undefined; + shell.core = core; + shell.queue = &queue; + shell.gpa = gpa; + shell.lsp_allocator = gpa; + shell.gens = &gens; + shell.ptys = &ptys; + shell.drainQueue(); + try std.testing.expect(core.lsp_ask.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); +} + +test "GUI worker setup failures finish matching LSP and pipe requests" { + const gpa = std.testing.allocator; + var failing_vtable = std.testing.io.vtable.*; + failing_vtable.concurrent = std.Io.failingConcurrent; + const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable }; + for (0..2) |failure| { + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("abc"); + var failing = std.testing.FailingAllocator.init(gpa, .{ + .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), + }); + var queue: Queue = .{ + .io = std.testing.io, + .gpa = gpa, + .lsp_allocator = failing.allocator(), + }; + defer queue.deinit(); + var tasks: PipeTasks = .{}; + core.lspRequest(core.view().active, .status, ""); + const req: host_io.Lsp.Request = .{ + .id = core.lsp_ask.wait.?.id, + .kind = .status, + .pane = @intCast(core.view().active), + .offset = 0, + .arg = "", + }; + if (failure == 0) { + queue.lsp_id = req.id -% 1; + queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "old queued result") } }); + queue.startLsp(core, req); + try std.testing.expectEqual(req.id, queue.lsp_id.?); + try std.testing.expectEqual(@as(usize, 0), queue.completion_len); + queue.push(.{ .lsp = .{ .id = req.id -% 1, .rows = try gpa.dupe(u8, "late old result") } }); + try std.testing.expectEqual(@as(usize, 0), queue.completion_len); + } else { + var shell: Shell = undefined; + shell.core = core; + shell.threads_ok = false; + lsp(&shell, req); + } + try std.testing.expect(core.lsp_ask.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + core.update(.{ .key = .{ .cp = '|' } }); + core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + core.update(.{ .key = .{ .cp = pardes.Key.enter } }); + const pipe_id = core.pipe.wait.?.id; + selection_pipe.start(failing_io, failing.allocator(), core, &tasks, pipe_id, &queue, Queue.pushPipe); + try std.testing.expect(core.pipe.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + try std.testing.expect(queue.lsp_task == null); + try std.testing.expectEqual(@as(usize, 0), tasks.len); + try std.testing.expectEqual(@as(usize, 0), queue.len); + } +} + +test "high-density window coordinates map once to render pixels" { + const geometry: WindowGeometry = .{ + .window_w = 560, + .window_h = 360, + .pixel_w = 1120, + .pixel_h = 720, + }; + try std.testing.expectEqual(Point{ .x = 700, .y = 240 }, windowPointToPixels(geometry, 350, 120)); +} + +test "the GUI's stdin keys reach a terminal pane as the tty's do: F5, Insert and the keypad's Up" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + core.panes[0].?.body.mode = .tty; + while (core.nextEffect()) |_| {} + var in: Input = .{ .core = core }; + var parser: vaxis.Parser = .{}; + var bytes: []const u8 = "\x1b[15~\x1b[2~\x1b[57419u"; + while (bytes.len > 0) { + const result = try parser.parse(bytes, gpa); + bytes = bytes[result.n..]; + if (result.event) |event| switch (event) { + .key_press => |key| postKey(&in, key, key.text orelse ""), + else => {}, + }; + } + var written: std.Io.Writer.Allocating = .init(gpa); + defer written.deinit(); + while (core.nextEffect()) |effect| { + if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); + } + try std.testing.expectEqualStrings("\x1b[15~\x1b[2~\x1b[A", written.written()); +} + +test "the window's function and editing keys reach a terminal as its cursor keys' mode and keyboard flags say" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + core.panes[0].?.body.mode = .tty; + while (core.nextEffect()) |_| {} + var in: Input = .{ .core = core }; + var written: std.Io.Writer.Allocating = .init(gpa); + defer written.deinit(); + const Case = struct { modes: []const u8, sym: c.SDL_Keycode, mod: c.SDL_Keymod = 0, sent: []const u8 }; + const cases = [_]Case{ + .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[A" }, + .{ .modes = "", .sym = c.SDLK_HOME, .sent = "\x1b[H" }, + .{ .modes = "", .sym = c.SDLK_F1, .sent = "\x1bOP" }, + .{ .modes = "", .sym = c.SDLK_F5, .sent = "\x1b[15~" }, + .{ .modes = "", .sym = c.SDLK_F12, .mod = c.SDL_KMOD_LSHIFT, .sent = "\x1b[24;2~" }, + .{ .modes = "", .sym = c.SDLK_INSERT, .sent = "\x1b[2~" }, + // DECCKM: less, vim, htop. + .{ .modes = "\x1b[?1h", .sym = c.SDLK_UP, .sent = "\x1bOA" }, + .{ .modes = "", .sym = c.SDLK_END, .sent = "\x1bOF" }, + .{ .modes = "", .sym = c.SDLK_LEFT, .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[1;5D" }, + // codex's kitty flags (>7u): Ctrl-C and Alt-a are unambiguous. + // (A bare Escape at a shell prompt is pardes's way out of raw input.) + .{ .modes = "\x1b[?1l\x1b[>7u", .sym = 'c', .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[99;5u" }, + .{ .modes = "", .sym = 'a', .mod = c.SDL_KMOD_LALT, .sent = "\x1b[97;3u" }, + // With event types asked for (2), an arrow says it is a press, as + // ghostty says it. + .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[1;1:1A" }, + }; + for (cases) |case| { + core.update(.{ .output = .{ .pane = 0, .bytes = case.modes } }); + while (core.nextEffect()) |_| {} + keyDown(&in, case.sym, case.mod); + written.clearRetainingCapacity(); + while (core.nextEffect()) |effect| { + if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); + } + try std.testing.expectEqualStrings(case.sent, written.written()); + } +} + +test "tagline pointer mapping retains physical grips and carries logical text coordinates" { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + core.update(.{ .resize = .{ .cols = 60, .rows = 12 } }); + core.update(.{ .command = "Newcol" }); + core.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 12 }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + _ = try core.render(arena.allocator()); + + const r = core.view().rects[core.view().active]; + const body_w: f32 = 10; + const body_h: f32 = 20; + const tag_w: f32 = 8; + const tag_y = r.y; + const x = @as(f32, @floatFromInt(r.x + pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; + + const tag = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); + try std.testing.expectEqual(pixelCell(x, 10), tag.col); + try std.testing.expectEqual(tag_y, tag.row); + try std.testing.expectEqual(@as(u16, 3), tag.tag_hit.?.col); + try std.testing.expectEqual(pardes.TagKind.pane, tag.tag_hit.?.kind); + const grip = gridCellAtDimensions(core, @as(f32, @floatFromInt(r.x + config.GUTTER)) * body_w - 0.1, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); + try std.testing.expect(grip.tag_hit == null); + try std.testing.expectEqual(r.x + config.GUTTER - 1, grip.col); + + const body_y = tag_y + core.panes[core.view().active].?.tag_rows; // a long tag wraps + const body = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(body_y)) + 0.5) * body_h, body_w, body_h, tag_w); + try std.testing.expectEqual(pixelCell(x, 10), body.col); + try std.testing.expectEqual(body_y, body.row); + try std.testing.expect(body.tag_hit == null); + + // The workspace tag's text starts TAG_TEXT_INSET cells in, as a pane's. + const x_top = @as(f32, @floatFromInt(pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; + const topbar = gridCellAtDimensions(core, x_top, 0.5 * body_h, body_w, body_h, tag_w); + try std.testing.expectEqual(pixelCell(x_top, 10), topbar.col); + try std.testing.expectEqual(@as(u16, 3), topbar.tag_hit.?.col); + try std.testing.expectEqual(pardes.TagKind.workspace, topbar.tag_hit.?.kind); +} + +test "a click at the window's corner lands in the corner cell" { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + var g = testGui(10, 20, 6, 12); + const geometry: WindowGeometry = .{ .window_w = 400, .window_h = 240, .pixel_w = 800, .pixel_h = 480 }; + const last = mouseCellWithGeometry(&g, core, 399.9, 239.9, geometry); + try std.testing.expectEqual(@as(u16, 79), last.col); + try std.testing.expectEqual(@as(u16, 23), last.row); + const first = mouseCellWithGeometry(&g, core, 0, 0, geometry); + try std.testing.expectEqual(@as(u16, 0), first.col); + try std.testing.expectEqual(@as(u16, 0), first.row); +} + +test "a blink holds while typing, eases at its edges and stops when idle" { + const ms = std.time.ns_per_ms; + try std.testing.expectEqual(@as(f32, 1), Blink.at(100 * ms, 0).alpha); + const out = Blink.at(Blink.hold_ns + Blink.half_ns + 100 * ms, 0); + try std.testing.expectEqual(@as(f32, 0), out.alpha); + const edge = Blink.at(Blink.hold_ns + Blink.half_ns - Blink.edge_ns / 2, 0); + try std.testing.expect(edge.edge and edge.alpha > 0.2 and edge.alpha < 0.8); + try std.testing.expectEqual(@as(?u64, null), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).next_ns); + try std.testing.expectEqual(@as(f32, 1), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).alpha); +} + +test "background opacity acknowledges success and rolls back unsupported surfaces" { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + var applied: u8 = 100; + try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 70")); + try std.testing.expect(core.settings.window_opacity_pending); + finishWindowOpacity(core, &applied, null); + try std.testing.expectEqual(@as(u8, 70), applied); + try std.testing.expect(!core.settings.window_opacity_pending); + + try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); + finishWindowOpacity(core, &applied, "background transparency requires an alpha-capable SDL window"); + try std.testing.expectEqual(@as(u8, 70), applied); + try std.testing.expectEqual(applied, core.settings.window_opacity); + try std.testing.expect(!core.settings.window_opacity_pending); + const pane = core.panes[0].?; + try std.testing.expectEqualStrings("WindowOpacity: background transparency requires an alpha-capable SDL window", pane.msg[0..pane.msg_len]); + + try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); + try std.testing.expect(core.settings.window_opacity_pending); + finishWindowOpacity(core, &applied, null); + try std.testing.expectEqual(@as(u8, 40), applied); + try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 100")); + finishWindowOpacity(core, &applied, null); + try std.testing.expectEqual(@as(u8, 100), applied); +} + +test "the clipboard pasted into a terminal reaches its pty as xterm pastes: bracketed when asked, no ESC[201~ smuggled through" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); + defer core.deinit(); + var shell: Shell = undefined; + shell.core = core; + var sent: std.ArrayList(u8) = .empty; + defer sent.deinit(gpa); + const take = struct { + fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + while (core_.nextEffect()) |effect| { + if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); + } + return out.items; + } + }.f; + _ = try take(core, &sent); + // The clipboard is SDL's own with no display to hold one. + _ = c.SDL_SetHint(c.SDL_HINT_VIDEO_DRIVER, "dummy"); + defer _ = c.SDL_ResetHint(c.SDL_HINT_VIDEO_DRIVER); + if (!c.SDL_InitSubSystem(c.SDL_INIT_VIDEO)) return error.SkipZigTest; + defer c.SDL_QuitSubSystem(c.SDL_INIT_VIDEO); + putClipboard(gpa, "ls\x1b[201~; rm -rf ~\nx"); + readClipboard(&shell); + try std.testing.expectEqualStrings("ls [201~; rm -rf ~\rx", try take(core, &sent)); + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); + _ = try take(core, &sent); + readClipboard(&shell); + try std.testing.expectEqualStrings("\x1b[200~ls [201~; rm -rf ~\nx\x1b[201~", try take(core, &sent)); +} + +test "fractional wheel delta moves the picture by the same fraction" { + const delta = accumulateWheelDelta(0, -0.125); + const s = applyScrollDelta(0, delta); + const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; + try std.testing.expectEqual(@as(f32, 0.125), delta); + try std.testing.expectEqual(@as(f32, 0.125), picture); + try std.testing.expectEqual(@as(i32, 1), s.rows); + try std.testing.expectEqual(@as(f32, -0.875), s.lag); +} + +test "repeated fractional deltas cross exactly one core row" { + var core_row: i32 = 0; + var lag: f32 = 0; + var crossed: u32 = 0; + for (0..8) |_| { + const s = applyScrollDelta(lag, 0.125); + core_row += s.rows; + crossed += @intCast(@abs(s.rows)); + lag = s.lag; + } + try std.testing.expectEqual(@as(u32, 1), crossed); + try std.testing.expectEqual(@as(i32, 1), core_row); + try std.testing.expectEqual(@as(f32, 0), lag); +} + +test "wheel magnitude is preserved without quantization" { + const delta = accumulateWheelDelta(0, -2.75); + const s = applyScrollDelta(0, delta); + const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; + try std.testing.expectEqual(@as(f32, 2.75), delta); + try std.testing.expectEqual(@as(f32, 2.75), picture); + try std.testing.expectEqual(@as(i32, 3), s.rows); + try std.testing.expectEqual(@as(f32, -0.25), s.lag); + try std.testing.expectEqual(@as(f32, 0), accumulateWheelDelta(0, std.math.inf(f32))); + + const bounded = boundScrollDelta(0, 3.0e38, 24); + const safe = applyScrollDelta(0, bounded); + try std.testing.expectEqual(@as(f32, 24), bounded); + try std.testing.expectEqual(@as(i32, 24), safe.rows); +} + +test "fractional scroll reversals preserve signed distance" { + var core_row: i32 = 0; + const forward = applyScrollDelta(0, 0.375); + core_row += forward.rows; + try std.testing.expectEqual(@as(f32, 0.375), @as(f32, @floatFromInt(core_row)) + forward.lag); + + const reverse = applyScrollDelta(forward.lag, -0.125); + core_row += reverse.rows; + try std.testing.expectEqual(@as(i32, -1), reverse.rows); + try std.testing.expectEqual(@as(f32, 0.25), @as(f32, @floatFromInt(core_row)) + reverse.lag); + try std.testing.expect(reverse.lag >= 0 and reverse.lag < 1); +} + +test "a wheel's notch is whole lines, a touchpad's fraction is not" { + try std.testing.expectEqual(@as(?i32, 1), notchOf(-1, -1)); + try std.testing.expectEqual(@as(?i32, -3), notchOf(3, 3)); + try std.testing.expectEqual(@as(?i32, null), notchOf(-0.25, 0)); + try std.testing.expectEqual(@as(?i32, null), notchOf(-1.5, -1)); + try std.testing.expectEqual(@as(?i32, null), notchOf(std.math.nan(f32), 1)); +} + +test "a click over codex in a terminal reaches its pty with its modifiers; Shift swaps B1 to pardes and B2 to the program" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); + defer core.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try core.render(frame.allocator()); + var in: Input = .{ .core = core }; + var sent: std.ArrayList(u8) = .empty; + defer sent.deinit(gpa); + const take = struct { + fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + while (core_.nextEffect()) |effect| { + if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); + } + return out.items; + } + }.f; + _ = try take(core, &sent); + const pane = core.panes[0].?; + const r = core.view().rects[0]; + const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; + const next: MouseCell = .{ .col = mc.col + 1, .row = mc.row }; + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); + _ = try take(core, &sent); + in.post(.{ .mouse = pointerMouse(.none, .motion, mc, .{}) }); + try std.testing.expectEqualStrings("\x1b[<35;6;4M", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .ctrl = true }) }); + try std.testing.expectEqualStrings("\x1b[<16;6;4M", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.left, .drag, next, .{}) }); + try std.testing.expectEqualStrings("\x1b[<32;7;4M", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.left, .release, next, .{}) }); + try std.testing.expectEqualStrings("\x1b[<0;7;4m", try take(core, &sent)); + // Shift-B1 is pardes's select; B2 is pardes's execute and Shift-B2 + // the program's, reported without the Shift. + in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .shift = true }) }); + in.post(.{ .mouse = pointerMouse(.left, .release, mc, .{ .shift = true }) }); + try std.testing.expectEqualStrings("", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{}) }); + in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{}) }); + try std.testing.expectEqualStrings("", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{ .shift = true }) }); + in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{ .shift = true }) }); + try std.testing.expectEqualStrings("\x1b[<1;6;4M\x1b[<1;6;4m", try take(core, &sent)); +} + +test "a wheel over codex in a terminal reaches its pty as the mouse reports it asked for" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); + defer core.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try core.render(frame.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + var in: Input = .{ .core = core }; + var sent: std.ArrayList(u8) = .empty; + defer sent.deinit(gpa); + const Sent = struct { + fn take(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + while (core_.nextEffect()) |effect| { + if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); + } + return out.items; + } + }; + _ = try Sent.take(core, &sent); + const pane = core.panes[0].?; + const r = core.view().rects[0]; + const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; + // What codex 0.159's chat sets on start. + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h\x1b[>7u\x1b[?1004h\x1b[?1049h\x1b[?1007l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); + _ = try Sent.take(core, &sent); + // A notch up, then a fast turn of three down: each its report, none + // left behind for a glide. + wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); + try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); + wheelAt(&g, &in, .{ .y = -3, .integer_y = -3 }, mc); + try std.testing.expectEqualStrings(std.mem.asBytes(&@as([3][10]u8, @splat("\x1b[<65;6;4M".*))), try Sent.take(core, &sent)); + try std.testing.expectEqual(@as(i32, 0), g.scroll_notch); + try std.testing.expect(g.scroll_pane == null); + // A touchpad's fractions add up to a turn. + wheelAt(&g, &in, .{ .y = 0.5 }, mc); + try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); + wheelAt(&g, &in, .{ .y = 0.5 }, mc); + try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); + // Alt is meta, 8; Shift keeps the turn pardes's own, a glide. + wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .alt = true } }, mc); + try std.testing.expectEqualStrings("\x1b[<72;6;4M", try Sent.take(core, &sent)); + wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .shift = true } }, mc); + try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); + try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); + stepGlide(&g, core); + try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); + resetScroll(&g); + // Its sign-in screen: mouse off, alternate scroll on, so arrow keys. + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1007h" } }); + _ = try Sent.take(core, &sent); + wheelAt(&g, &in, .{ .y = -1, .integer_y = -1 }, mc); + try std.testing.expectEqualStrings("\x1b[B", try Sent.take(core, &sent)); + // Back on the main screen a shell's wheel is ours: a notch to glide, + // nothing to the pty. + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049l" } }); + _ = try Sent.take(core, &sent); + wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); + try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); + try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); +} + +test "a notch scrolls the core at once and the picture glides after it, a wrapped line's rows at a time" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + // Lines of two rows each at this width, numbered so no two rows match. + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..60) |i| { + try text.print(gpa, "{d:0>4} ", .{i}); + try text.appendNTimes(gpa, 'a' + @as(u8, @intCast(i % 26)), 100); + try text.append(gpa, '\n'); + } + _ = try core.setTestFile(text.items); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const ms = std.time.ns_per_ms; + var now: u64 = std.time.ns_per_s; + core.advance(now); + var s = try core.render(arena.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + const r = core.view().rects[core.view().active]; + g.scroll_pane = core.view().active; + g.scroll_col = r.x + 10; + g.scroll_row = r.y + r.h - 2; + const body_y = core.bodyTop(core.panes[core.view().active].?, r); + const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y + 1) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); + defer gpa.free(row_before); + // The window has drawn the view once (Glide.frame finds a view that moved). + g.now_ns = now; + glideFrame(&g, gpa, s); + // One notch down: the core is a line on at once. + g.scroll_notch = 1; + const scrolled = core.panes[core.view().active].?.scroll(); + stepGlide(&g, core); + try std.testing.expectEqual(scrolled + 1, core.panes[core.view().active].?.scroll()); + _ = arena.reset(.retain_capacity); + s = try core.render(arena.allocator()); + glideFrame(&g, gpa, s); + // The window's own motion: it draws its frames while it moves. + try std.testing.expect(frontendMoving(&g)); + // Its two rows: the picture two rows behind, the rows that left kept, + // nearest first. + try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.follow.offset, 1e-4); + try std.testing.expectEqual(@as(u16, 2), g.glide.nabove); + try std.testing.expect(pardes.glide.sameRow(g.glide.above[0 .. r.w - config.GUTTER], row_before)); + // Frame by frame it comes back, never past, and settles. + var frames: usize = 0; + while (g.glide.moving()) : (frames += 1) { + now += 7 * ms; + core.advance(now); + stepGlide(&g, core); + g.now_ns = now; + glideFrame(&g, gpa, s); + try std.testing.expect(g.glide.follow.offset <= 1e-4); + if (frames > 200) return error.NeverSettled; + } + try std.testing.expect(frames > 5); + try std.testing.expectEqual(@as(f32, 0), g.glide.follow.offset); + try std.testing.expect(!frontendMoving(&g)); +} + +test "a fractional wheel turn that brings the picture back onto the core's row is drawn: the window never rests on a frame half a row off" { + const gpa = std.testing.allocator; + const core = try wheelRunFile(gpa); + defer core.deinit(); + var wr = try WheelRun.init(gpa, core); + defer wr.deinit(gpa); + // A high-resolution wheel's half notches (SDL's y, up positive), a + // frame each: the first scrolls the core a line and leaves the picture + // half a row behind it; the second takes the picture onto it. + for (0..2) |_| { + try wr.frame(gpa, &.{-0.5}); + try std.testing.expectEqual(wr.picture(), wr.drawn); + } + try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); +} + +test "a wheel turned down then up never draws the picture moving against the turn" { + const gpa = std.testing.allocator; + const core = try wheelRunFile(gpa); + defer core.deinit(); + var wr = try WheelRun.init(gpa, core); + defer wr.deinit(gpa); + // Two half notches down (the picture back on the core's row), then + // quarter notches up, a frame each and frames between: each frame's + // picture is where the last left it or on the way the wheel turns, + // never back against it. + for ([_]struct { f32, usize }{ .{ -0.5, 2 }, .{ 0.25, 4 } }) |phase| { + const turn, const turns = phase; + for (0..turns + 4) |k| { + const was = wr.drawn; + try wr.frame(gpa, if (k < turns) &.{turn} else &.{}); + const moved = wr.drawn - was; + try std.testing.expect(moved * -turn >= -1e-4); + } + } +} + +test "a fine wheel's turns that stop at a fraction leave the text on a whole row, and a turn mid-settle is not lost" { + const gpa = std.testing.allocator; + const core = try wheelRunFile(gpa); + defer core.deinit(); + var wr = try WheelRun.init(gpa, core); + defer wr.deinit(gpa); + const line = struct { + fn of(p: *pardes.Pardes) i64 { + return @intCast(p.panes[p.view().active].?.scroll()); + } + }.of; + const first = line(core); + // Three quarter notches down, a frame each: the core a line on, the + // picture a quarter row behind it. Then nothing: it eases onto the + // core's row (never back against the turns) and rests there, drawn. + for (0..3) |_| try wr.frame(gpa, &.{-0.25}); + try std.testing.expect(wr.g.scroll_lag != 0); + var frames: usize = 0; + while (wr.g.scroll_lag != 0) : (frames += 1) { + const was = wr.drawn; + try wr.frame(gpa, &.{}); + try std.testing.expect(wr.drawn >= was); + try std.testing.expect(frames < 20); + } + try std.testing.expectEqual(first + 1, line(core)); + try std.testing.expectEqual(wr.picture(), wr.drawn); + try std.testing.expectEqual(@as(f32, @floatFromInt(first + 1)), wr.drawn); + // Again, and a quarter notch more arrives mid-settle: it counts, and + // the settle ends on the row after it. + for (0..3) |_| try wr.frame(gpa, &.{-0.25}); + for (0..4) |_| try wr.frame(gpa, &.{}); + try std.testing.expect(wr.g.scroll_lag != 0); + try wr.frame(gpa, &.{-0.25}); + for (0..20) |_| try wr.frame(gpa, &.{}); + try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); + try std.testing.expectEqual(first + 3, line(core)); + try std.testing.expectEqual(@as(f32, @floatFromInt(first + 3)), wr.drawn); +} + +test "a bar cursor is drawn on its line while a wheel's fraction holds the text off its row, as a block is" { + const gpa = std.testing.allocator; + const core = try wheelRunFile(gpa); + defer core.deinit(); + core.settings.cursor_blink = false; + core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + var wr = try WheelRun.init(gpa, core); + defer wr.deinit(gpa); + defer wr.g.decor.deinit(gpa); + // Half a notch down: the core a line on, the text drawn half a row + // below its cells until the settle. + try wr.frame(gpa, &.{-0.5}); + try std.testing.expectEqual(@as(f32, -0.5), wr.g.scroll_lag); + _ = wr.arena.reset(.retain_capacity); + const s = try core.render(wr.arena.allocator()); + const cu = s.cursor.?; + try std.testing.expect(cu.bar); + const layout = fixedCellLayout(&wr.g); + const win_w: f32 = @floatFromInt(@as(u32, s.cols) * wr.g.cell_w); + const win_h: f32 = @floatFromInt(@as(u32, s.rows) * wr.g.cell_h); + wr.g.decor.clearRetainingCapacity(); + try cursorDecor(&wr.g, gpa, s, layout, win_w, win_h); + try std.testing.expectEqual(@as(usize, 1), wr.g.decor.items.len); + // Its top where its line's top is drawn (emitScrollRows: the row less + // the lag), not on its cell. + const top = (1 - wr.g.decor.items[0].y0) * win_h / 2; + try std.testing.expectApproxEqAbs((@as(f32, @floatFromInt(cu.y)) - wr.g.scroll_lag) * layout.h, top, 0.01); +} + +test "a wheel's caret rides with its line, the text's own glide, never a spring of its own" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..200) |i| try text.print(gpa, "line {d}\n", .{i}); + _ = try core.setTestFile(text.items); + core.settings.cursor_blink = false; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var now: u64 = std.time.ns_per_s; + core.advance(now); + for ("10G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); + _ = try core.render(arena.allocator()); + now += std.time.ns_per_s; + core.advance(now); + _ = arena.reset(.retain_capacity); + var s = try core.render(arena.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + const r = core.view().rects[core.view().active]; + g.scroll_pane = core.view().active; + g.scroll_col = r.x + 10; + g.scroll_row = r.y + r.h - 2; + stepGlide(&g, core); + // The window has drawn the view once (Glide.frame finds a view that moved). + g.now_ns = now; + glideFrame(&g, gpa, s); + const before: f32 = @floatFromInt(s.cursor.?.y); + g.scroll_notch = 1; + stepGlide(&g, core); + var frames: usize = 0; + while (true) : (frames += 1) { + now += 7 * std.time.ns_per_ms; + core.advance(now); + _ = arena.reset(.retain_capacity); + s = try core.render(arena.allocator()); + g.now_ns = now; + glideFrame(&g, gpa, s); + seeCaret(&g, s, fixedCellLayout(&g), 480, now); + if (frames == 0) { + try std.testing.expect(g.glide.caret_rides); + // Where its line is drawn: on the row it was on, the cell a row up. + try std.testing.expectApproxEqAbs(before, caretRow(&g, s, now).?, 1e-3); + } + // Always exactly with its line, the cell less the text's offset. + try std.testing.expectApproxEqAbs(@as(f32, @floatFromInt(s.cursor.?.y)) - g.glide.follow.offset, caretRow(&g, s, now).?, 1e-3); + if (!g.glide.moving()) break; + stepGlide(&g, core); + if (frames > 200) return error.NeverSettled; + } + try std.testing.expectEqual(@as(f32, @floatFromInt(s.cursor.?.y)), caretRow(&g, s, now).?); +} + +test "every scroll glides on one law: a half page, a page, the far jumps, a run of them retargeting" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); + defer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + // Numbered lines no two alike, short enough never to wrap. + for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); + _ = try core.setTestFile(text.items); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + core.advance(std.time.ns_per_s); + _ = try core.render(arena.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + const body_h: f32 = @floatFromInt(core.view().rects[core.view().active].h - core.panes[core.view().active].?.tag_rows); + const ctrl = struct { + fn key(cp: u21) pardes.Key { + return .{ .cp = cp, .ctrl = true }; + } + }; + const script = [_]GlideRun.Step{ + .{ .frame = 2, .key = ctrl.key('d') }, + .{ .frame = 40, .key = ctrl.key('f') }, + .{ .frame = 80, .key = .{ .cp = 'g', .text = "g" } }, + .{ .frame = 80, .key = .{ .cp = 'e', .text = "e" } }, + .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, + .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, + // Faster than they settle: each adds to the glide under way. + .{ .frame = 160, .key = ctrl.key('d') }, + .{ .frame = 165, .key = ctrl.key('d') }, + .{ .frame = 170, .key = ctrl.key('d') }, + .{ .frame = 175, .key = ctrl.key('d') }, + }; + var seq: GlideRun = .{}; + try seq.play(&g, core, gpa, &arena, &script, 240); + try seq.checkCaret(); + // Every one moves the picture on the frame it is drawn in, and the + // picture lags by what the core moved (a far jump, by one body). + var longest: usize = 0; + var shortest: usize = std.math.maxInt(usize); + for ([_]usize{ 2, 40, 80, 120 }) |at| { + const moved: f32 = @floatFromInt(@abs(seq.lines[at] - seq.lines[at - 1])); + try std.testing.expect(moved >= 1); + const lag = @abs(seq.offsets[at]); + try std.testing.expect(lag > 0.5 * @min(moved, body_h)); + try std.testing.expect(lag <= @min(moved, body_h) + 1e-3); + // Settles on the same law whatever the distance: a few frames for + // a half page, not many more for a jump of 3000 lines. + const frames = seq.settle(at); + longest = @max(longest, frames); + shortest = @min(shortest, frames); + try std.testing.expect(frames >= 8 and frames <= 24); + } + try std.testing.expect(longest - shortest <= 5); + // Readable: never more than a quarter of a body a frame once it moves. + for (1..seq.frames) |k| { + if (seq.lines[k] != seq.lines[k - 1]) continue; + try std.testing.expect(@abs(seq.offsets[k] - seq.offsets[k - 1]) <= body_h / 4 + 1e-3); + } + // The seq of half pages: one glide, never at rest between them, and + // done as soon after the last as one half page alone takes. + for (160..180) |k| try std.testing.expect(seq.offsets[k] != 0); + try std.testing.expect(seq.settle(175) <= seq.settle(2) + 4); +} + +test "a held key moves the view at the stream's own rate, never a bounce a line, and settles once it stops" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); + defer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); + _ = try core.setTestFile(text.items); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + core.advance(std.time.ns_per_s); + _ = try core.render(arena.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + // j held from the top: a repeat every second frame, the view following + // a line a repeat once the caret is at its last rows. + var script: [48]GlideRun.Step = undefined; + for (&script, 0..) |*step, i| step.* = .{ .frame = 20 + 2 * i, .key = .{ .cp = 'j', .text = "j" } }; + var seq: GlideRun = .{}; + try seq.play(&g, core, gpa, &arena, &script, 200); + // Inside the stream the picture moves every frame by about the same + // step: an input's rows over its spacing, not a spring's ease to each. + var least: f32 = std.math.inf(f32); + var most: f32 = 0; + for (90..110) |k| { + const step = (@as(f32, @floatFromInt(seq.lines[k])) + seq.offsets[k]) - (@as(f32, @floatFromInt(seq.lines[k - 1])) + seq.offsets[k - 1]); + least = @min(least, step); + most = @max(most, step); + } + try std.testing.expect(seq.lines[89] > 0 and least > 0.4 and most < 0.6); + // The caret stays on its row, the text moving under it: not a pixel's + // wobble (the glide's fractional lag never reaches it). + for (90..110) |k| try std.testing.expectEqual(seq.carets[89], seq.carets[k]); + // It comes to rest once the keys stop, never past its mark. + for (110..200) |k| try std.testing.expect(seq.offsets[k] <= 0); + try std.testing.expectEqual(@as(f32, 0), seq.offsets[199]); + // Ctrl-d held, then PageDown held: the caret keeps its row the whole + // way, the pages moving under it. + var pages: [40]GlideRun.Step = undefined; + for (&pages, 0..) |*step, i| step.* = .{ .frame = 10 + 2 * i, .key = if (i < 20) .{ .cp = 'd', .ctrl = true } else .{ .cp = pardes.Key.page_down } }; + var held: GlideRun = .{}; + try held.play(&g, core, gpa, &arena, &pages, 100); + try held.checkCaret(); + try seq.checkCaret(); + // (The first of each may move it, one ease: from the last row to where + // a half page keeps it, and from there to a page's.) + for (30..50) |k| try std.testing.expectEqual(held.carets[30], held.carets[k]); + for (70..90) |k| try std.testing.expectEqual(held.carets[70], held.carets[k]); +} + +test "a scroll's shifted rows start under the context rows, and its scissor below their band" { + var surface: pardes.Surface = .{}; + var g = testGui(10, 20, 6, 12); + g.scroll_rect = .{ .x = 0, .y = 0, .w = 40, .h = 20 }; + g.scroll_body_y = 1; + g.scroll_body_h = 19; + const layout: CellLayout = .{ .w = 10, .h = 20, .x_off = 0, .y_off = 0 }; + // On the grid, three body-high rows are held, and nothing moves up. + const grid = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(u16, 3), grid.rows); + try std.testing.expectEqual(@as(f32, 0), grid.lift); + const clip = scrollScissor(&g, layout, 400, 400); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 20), clip.y); + try std.testing.expectEqual(@as(c_int, 16 * 20), clip.h); + // In a body layer they are tagline-high: the rows under them move up + // by what each is shorter, to where the layer draws them. + surface.body_layers[0].rows = 30; + surface.body_layers[0].context_rows = 3; + const layered = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(f32, 3 * (12 - 20)), layered.lift); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout, 400, 400).y); + // None held: the whole body moves. + surface.body_layers[0].rows = 0; + try std.testing.expectEqual(@as(u16, 0), holdContext(&g, &surface, 0, 0, 19, layout).rows); + try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout, 400, 400).y); +} + +test "concealed terminal text emits no ink on its ground" { + var g = testGui(10, 20, 6, 12); + var cell: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; + cell.text[0] = 'X'; + const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); + try std.testing.expectEqualDeep(g.space_slot, resolved.slot); + try std.testing.expectEqual(bg_default, resolved.bg); +} + +test "a block cursor's cell is drawn reversed: the cell's ink its ground, its ground its ink" { + var g = testGui(10, 20, 6, 12); + // A blank, so no glyph is looked up in this atlas-less Gui. + const cell: pardes.Cell = .{ + .text = .{ ' ', ' ', ' ', ' ', ' ', ' ', ' ' }, + .len = 1, + .default = false, + .style = .{ .fg = .{ .rgb = .{ 10, 20, 30 } }, .bg = .{ .rgb = .{ 200, 210, 220 } } }, + }; + const plain = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); + const cursor = resolveCell(&g, (&cell)[0..1], 0, 0, .body, true, bg_default); + try std.testing.expectEqual([3]u8{ 10, 20, 30 }, plain.fg); + try std.testing.expectEqual(plain.fg, cursor.bg); + try std.testing.expectEqual(plain.bg, cursor.fg); +} + +test "the layer cover is the per-cell layer scan, over a core's layouts and random layers" { + // A gui-shaped core: its tagline is narrower and shorter than the body, + // so tags and notices are layers. + const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 97, .rows = 31 }); + defer core.deinit(); + core.update(.{ .resize = .{ .cols = 97, .rows = 31, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 7, .tagline_h = 13 } } }); + for (1..4) |id| _ = try core.newShell(id, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + pardes.layout.insert(core, 1, 1, 2); + pardes.layout.insert(core, 0, 1, 3); + var cover: [97 * 31]Cover = undefined; + var notices = false; + for (0..32) |step| { + if (step & 3 == 0) try std.testing.expect(core.executeBuiltinLine(2, "Collapse")); + core.view().prefix = if (step & 4 != 0) .leader else .none; + if (step & 8 != 0) { + try std.testing.expect(core.executeBuiltinLine(0, "Msg a message chip over the body")); + try std.testing.expect(core.executeBuiltinLine(3, "Msg another")); + } + const s = try core.render(core.scratch.allocator()); + try std.testing.expectEqual(@as(usize, cover.len), @as(usize, s.cols) * s.rows); + @memset(&cover, .{ .layer = true, .floating = true, .grip = true, .focus = true }); // what an earlier frame left + coverFrame(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); + try expectCoverIsScan(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers()); + // A grip's cells know their way to its glyph, and the focused + // pane's tag rows are the focused ones. + for (s.regionList()) |region| { + if (region.kind != .grip) continue; + for (0..region.rect.w) |offset| { + const cell = cover[@as(usize, region.rect.y) * s.cols + region.rect.x + offset]; + try std.testing.expect(cell.grip); + try std.testing.expectEqual(offset, cell.grip_offset); + try std.testing.expectEqual(region.owner == core.view().active, cell.focus); + } + } + for (s.tagLayers()) |layer| notices = notices or (layer.rows != 0 and layer.kind == .notice); + } + try std.testing.expect(notices); + + // Random layers: overlapping, empty, past the grid's right and bottom + // edges, and at the top of u16, where x + w overflows it. + const gen = struct { + fn coordinate(random: std.Random, limit: u16) u16 { + if (random.uintLessThan(u8, 12) == 0) return std.math.maxInt(u16) - random.uintLessThan(u16, 3); + return random.uintAtMost(u16, limit + 3); + } + fn rect(random: std.Random, cols: u16, rows: u16) pardes.Rect { + return .{ .x = coordinate(random, cols), .y = coordinate(random, rows), .w = coordinate(random, cols), .h = coordinate(random, rows / 2) }; + } + }; + var prng = std.Random.DefaultPrng.init(0x6c61796572); + const random = prng.random(); + var body: [pardes.MAX_PANES]pardes.Layer = undefined; + var tag: [pardes.MAX_TAG_LAYERS]pardes.Layer = undefined; + var grid: [64 * 40]Cover = undefined; + for (0..3000) |_| { + const cols = random.intRangeAtMost(u16, 1, 64); + const rows = random.intRangeAtMost(u16, 1, 40); + const empty = random.intRangeAtMost(u8, 2, 5); // about one layer in `empty` is empty + for (&body) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; + for (&tag) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; + const bodies = body[0..random.uintAtMost(usize, body.len)]; + const tags = tag[0..random.uintAtMost(usize, tag.len)]; + const cells = grid[0 .. @as(usize, cols) * rows]; + @memset(cells, .{ .layer = random.boolean() }); + coverFrame(cells, cols, rows, bodies, tags, &.{}); + try expectCoverIsScan(cells, cols, rows, bodies, tags); + } +} + +test "every pixel of a grip column is band, button or ring, and the button sits over the scrollbar" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 20 }); + defer core.deinit(); + const pane = try core.setTestFile(std.mem.asBytes(&@as([60][5]u8, @splat("text\n".*)))); + pane.tag.own = try gpa.dupe(u8, "second\nthird"); + core.newScratchBelow(0); + for ([_]struct { w: u32, h: u32, tag: u32 }{ .{ .w = 10, .h = 20, .tag = 12 }, .{ .w = 17, .h = 35, .tag = 30 }, .{ .w = 9, .h = 19, .tag = 15 }, .{ .w = 12, .h = 24, .tag = 24 } }) |m| for ([_]usize{ 0, 1 }) |focus| for ([_]bool{ false, true }) |dirty| { + core.view().active = focus; + pane.file.?.revision = pane.file.?.saved_revision + @intFromBool(dirty); + core.sync(); + const s = try core.render(core.scratch.allocator()); + var g = testGui(m.w, m.h, m.w, m.tag); + defer g.decor.deinit(gpa); + const layout = fixedCellLayout(&g); + const win_w: f32 = @floatFromInt(60 * m.w); + const win_h: f32 = @floatFromInt(20 * m.h); + const cover = try gpa.alloc(Cover, @as(usize, s.cols) * s.rows); + defer gpa.free(cover); + coverFrame(cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, layout, win_w, win_h, true); + const grip = s.region(.grip, 0).?; + // The grip column's pixels, band first, then its cells, then decor. + const x_px: u32 = grip.rect.x * m.w; + const w_px: u32 = config.GUTTER * m.w; + const y_px: u32 = grip.rect.y * m.h; + const h_px: u32 = grip.rect.h * m.h; + const pixels = try gpa.alloc(?[3]f32, w_px * h_px); + defer gpa.free(pixels); + @memset(pixels, null); + const paint = struct { + fn quad(into: []?[3]f32, x0n: f32, y0n: f32, x1n: f32, y1n: f32, rgb: [3]f32, ww: f32, wh: f32, ox: u32, oy: u32, pw: u32, ph: u32) void { + const px0: i64 = @intFromFloat(@round((x0n + 1) / 2 * ww)); + const px1: i64 = @intFromFloat(@round((x1n + 1) / 2 * ww)); + const py0: i64 = @intFromFloat(@round((1 - y0n) / 2 * wh)); + const py1: i64 = @intFromFloat(@round((1 - y1n) / 2 * wh)); + var y = @max(py0, oy); + while (y < @min(py1, oy + ph)) : (y += 1) { + var x = @max(px0, ox); + while (x < @min(px1, ox + pw)) : (x += 1) into[@intCast((y - oy) * pw + (x - ox))] = rgb; + } + } + }; + var instances: [4]CellInstance = undefined; + for (0..grip.rect.h) |line| for (0..config.GUTTER) |dx| { + const col: u16 = grip.rect.x + @as(u16, @intCast(dx)); + const row: u16 = grip.rect.y + @as(u16, @intCast(line)); + const at = @as(usize, row) * s.cols; + var next: u32 = 0; + emitSurfaceCell(&g, &s.chrome, &instances, &next, col, row, layout, win_w, win_h, s.cells[at..][0..s.cols], cover[at..][0..s.cols], col, null, false, bg_default); + for (instances[0..next]) |i| paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); + }; + for (g.decor.items) |i| if (i.fr >= 1 and i.clip_x1 < i.clip_x0) paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); + const rgb = struct { + fn of(v: [3]u8) [3]f32 { + return .{ @as(f32, @floatFromInt(v[0])) / 255, @as(f32, @floatFromInt(v[1])) / 255, @as(f32, @floatFromInt(v[2])) / 255 }; + } + }.of; + const chrome = &s.chrome; + const band = if (focus == 0) chrome.tag_focus_bg else chrome.tag_bg; + // Band, fills, rings, the rules between stacked panes and under the + // tag, and the mode marks' ink (the grip's first cell's). + const ink = inkOn(gripFill(chrome, grip.active, grip.dirty)); + const allowed = [_][3]f32{ rgb(band), rgb(core.chromeTheme().box), rgb(pardes.draw.boxDirty(core)), rgb(chrome.grip_border), rgb(chrome.grip_focus_ring), rgb(chrome.border), rgb(ink), rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)) }; + for (pixels, 0..) |pixel, n| { + const got = pixel orelse return error.TestUnpaintedGripPixel; + const known = for (allowed) |a| { + if (std.meta.eql(a, got)) break true; + } else false; + // Under the first row there is no button: band and rules only. + if (n / w_px >= m.h and n / w_px < h_px - 1 and !std.meta.eql(got, rgb(band)) and !std.meta.eql(got, rgb(chrome.border))) + return error.TestButtonUnderFirstRow; + if (!known) std.debug.print("sliver {any} at {d},{d} of {d}x{d} (metrics {d}x{d}/{d}, focus {d}, dirty {}) page {any}\n", .{ got, n % w_px, n / w_px, w_px, h_px, m.w, m.h, m.tag, focus, dirty, s.chrome.page }); + try std.testing.expect(known); + } + // The rule under the tag runs unbroken across the grip column. + for (pixels[(h_px - 1) * w_px ..][0..w_px]) |pixel| + try std.testing.expectEqual(rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)), pixel.?); + // The button's edges are the scrollbar's. + const button = gripButton(&g, chrome, grip.rect.x, grip.rect.y, layout); + const column = scrollColumn(&g, chrome, s.region(.rail, 0).?.rect.x, layout); + try std.testing.expectEqual(column[0], button[0]); + try std.testing.expectEqual(column[1], button[2]); + }; + pane.file.?.revision = pane.file.?.saved_revision; +} + +test "small tagline fonts leave no background gutters between adjacent tags" { + const chrome: pardes.Chrome = .{}; + var g = testGui(10, 20, 8, 16); + const cell: pardes.Cell = .{ .default = false, .style = .{ .font_role = .tagline } }; + var instances: [6]CellInstance = undefined; + var next: u32 = 0; + for (0..3) |row| { + // Column 1: past the anchor's inset edge at the column's left. + emitSurfaceCell(&g, &chrome, &instances, &next, 1, @intCast(row), fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{}}, 0, null, false, bg_default); + const base = instances[row * 2]; + const ink = instances[row * 2 + 1]; + try std.testing.expectApproxEqAbs(@as(f32, 20.0 / 480.0 * 2), base.y0 - base.y1, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 16.0 / 480.0 * 2), ink.y0 - ink.y1, 0.0001); + try std.testing.expect(ink.y0 <= base.y0 and ink.y1 >= base.y1); + try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), ink.x1 - ink.x0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 10) / atlas_w, ink.u1 - ink.u0, 0.0001); + if (row > 0) try std.testing.expectApproxEqAbs(instances[(row - 1) * 2].y1, base.y0, 0.0001); + } + // Column 0 is an anchor's edge: its ink is inset by the band's margin + // (2 px here) and its underlay still covers the whole cell. + next = 0; + emitSurfaceCell(&g, &chrome, &instances, &next, 0, 1, fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{ .anchor = true }}, 0, null, false, bg_default); + try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), instances[0].x1 - instances[0].x0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 8.0 / 800.0 * 2), instances[1].x1 - instances[1].x0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 8) / atlas_w, instances[1].u1 - instances[1].u0, 0.0001); +} + +test "block cursor alone overrides transparent cell background" { + var g = testGui(10, 20, 6, 12); + const cell: pardes.Cell = .{}; + var instances: [2]CellInstance = undefined; + for ([_]bool{ false, true }, 0..) |cursor, i| { + emitInstance(&g, &instances, @intCast(i), 0, 0, fixedCellLayout(&g), 800, 480, .body, (&cell)[0..1], 0, null, cursor, bg_default); + try std.testing.expectEqual(cursor, instances[i].effect & opaque_bg_bit != 0); + } +} + +test "insert cursor overlays without replacing the character beneath it" { + const cell: pardes.Cell = .{ + .text = .{ 'x', ' ', ' ', ' ', ' ', ' ', ' ' }, + .len = 1, + .default = false, + }; + try std.testing.expectEqual(@as(u32, 'x'), cellCodepoint(&cell)); + + // A bar at a tag cell: tagline-tall, centered in its row, in the + // cell's ink, drawn as decor over it. + var cells: [25]pardes.Cell = @splat(.{}); + cells[3 * 5 + 2] = .{ .default = false, .style = .{ .fg = .{ .rgb = .{ 32, 48, 64 } }, .font_role = .tagline } }; + const surface: pardes.Surface = .{ .cols = 5, .rows = 5, .cells = &cells, .cursor = .{ .x = 2, .y = 3, .bar = true } }; + var g = testGui(10, 20, 8, 8); + defer g.decor.deinit(std.testing.allocator); + try cursorDecor(&g, std.testing.allocator, &surface, fixedCellLayout(&g), 100, 100); + try std.testing.expectEqual(@as(usize, 1), g.decor.items.len); + const bar = g.decor.items[0]; + try std.testing.expectApproxEqAbs(@as(f32, -0.32), bar.y0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, -0.48), bar.y1, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 32.0 / 255.0), bar.br, 0.0001); + try std.testing.expectEqual(@as(f32, 1), bar.fr); +} + +test "a ligature draws across its cells, one slice each, and comes apart under the cursor" { + const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); + defer std.testing.allocator.free(bytes); + const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; + defer c.ui_font_free(font); + var g = try textTestGui(font, 27); + defer font_allocator = std.heap.smp_allocator; + defer std.testing.allocator.free(g.atlas_stage); + defer g.glyphs.deinit(); + defer g.words.deinit(std.testing.allocator); + + const line = textTestLine("a->b"); + var slots: [4]Slot = undefined; + for (&slots, 0..) |*slot, i| slot.* = cellSlot(&g, &line, i, null, .body); + // `->` is one glyph strip two cells wide: each cell samples its own half. + try std.testing.expectEqual(slots[1].v, slots[2].v); + try std.testing.expectEqual(slots[1].u + g.cell_w, slots[2].u); + var strips: usize = 0; + var it = g.glyphs.iterator(); + while (it.next()) |entry| if (entry.key_ptr.span == 2) { + strips += 1; + try std.testing.expectEqual(@as(u4, 1), entry.key_ptr.lead); + try std.testing.expectEqual(slots[1], entry.value_ptr.*); + }; + try std.testing.expectEqual(@as(usize, 1), strips); + // The arrow runs through the seam: both halves carry ink at it. + const seam = g.atlas_stage[@as(usize, slots[2].v) * atlas_w ..]; + var left_ink: usize = 0; + var right_ink: usize = 0; + for (0..g.cell_h) |y| { + left_ink += seam[y * atlas_w + slots[2].u - 1]; + right_ink += seam[y * atlas_w + slots[2].u]; + } + try std.testing.expect(left_ink > 0 and right_ink > 0); + // `a` and `b` are their plain glyphs. + try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'a'), .role = .body }).?, slots[0]); + try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'b'), .role = .body }).?, slots[3]); + + // A second line with the same word reuses the shaped slots. + const again = textTestLine("a->b"); + const text_len = g.words.text.items.len; + for (0..4) |i| try std.testing.expectEqual(slots[i], cellSlot(&g, &again, i, null, .body)); + try std.testing.expectEqual(text_len, g.words.text.items.len); + + // The cursor on either half shows plain `-` and `>`. + const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '-'), .role = .body }).?; + const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '>'), .role = .body }).?; + for ([_]usize{ 1, 2 }) |cursor| { + try std.testing.expectEqual(plain_minus, cellSlot(&g, &line, 1, cursor, .body)); + try std.testing.expectEqual(plain_greater, cellSlot(&g, &line, 2, cursor, .body)); + } + // A tagline is never shaped. + try std.testing.expectEqual(c.ui_font_glyph(font, '-'), (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph); +} + +test "a font without ligatures draws every cell as its own glyph, exactly as before shaping" { + const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + defer c.ui_font_free(font); + var g = try textTestGui(font, 18); + defer font_allocator = std.heap.smp_allocator; + defer std.testing.allocator.free(g.atlas_stage); + defer g.glyphs.deinit(); + defer g.words.deinit(std.testing.allocator); + const text = "a->b != c => d <= e |> www == :: 0x1F"; + var line = textTestLine(text); + line[3].style.bold = true; // a style change inside a word + var expected: [64 * 64]u8 = undefined; + for (line, 0..) |cell, i| { + if (text[i] == ' ') continue; + const slot = cellSlot(&g, &line, i, null, .body); + const key = try glyphKeyAt(&g, slot); + try std.testing.expectEqual(c.ui_font_glyph(font, text[i]), key.glyph); + try std.testing.expectEqual(@as(u4, 1), key.span); + _ = c.ui_font_raster(font, 18, key.glyph, @intFromBool(cell.style.bold), &expected, 64, @intCast(g.cell_w), @intCast(g.cell_h), 0, @intCast(g.cell_w), g.ascent); + for (0..g.cell_h) |y| + try std.testing.expectEqualSlices(u8, expected[y * 64 ..][0..g.cell_w], g.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]); + } +} + +test "pane indicator cached ink centers bearings styles and sizes" { + const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + defer c.ui_font_free(font); + var g = testGui(10, 20, 6, 12); + g.font = font; + g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); + defer std.testing.allocator.free(g.atlas_stage); + g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); + defer g.glyphs.deinit(); + for ([_]f32{ 13, 27, 40 }) |px| { + g.px = px; + var cw: c_int = 0; + var ch: c_int = 0; + c.ui_font_cell_metrics(font, px, &cw, &ch, &g.ascent); + g.cell_w = @intCast(cw); + g.cell_h = @intCast(ch); + for ([_]u8{ 40, 82, 100 }) |percent| { + const tag = taglineRaster(font, px, g.cell_w, g.cell_h, percent); + g.tagline_width = tag.width; + g.tagline_height = tag.height; + g.tagline_px = tag.px; + g.tagline_baseline = tag.baseline; + resetGlyphAtlas(&g); + try std.testing.expectEqual(@as(usize, 0), g.glyphs.count()); + for ([_]u32{ '^', '$', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { + const key: GlyphKey = .{ .face = 0, .glyph = c.ui_font_glyph(font, @intCast(cp)), .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }; + const slot = cachedGlyph(&g, key).?; + const bounds = inkBounds(g.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?; + const center_x: isize = @intCast(bounds.min_x + bounds.max_x); + const center_y: isize = @intCast(bounds.min_y + bounds.max_y); + try std.testing.expect(@abs(center_x - @as(isize, @intCast(g.cell_w * config.GUTTER - 1))) <= 1); + try std.testing.expect(@abs(center_y - @as(isize, @intCast(tag.height - 1))) <= 1); + const count = g.glyphs.count(); + const pen = g.pen_x; + try std.testing.expectEqualDeep(slot, cachedGlyph(&g, key).?); + try std.testing.expectEqual(count, g.glyphs.count()); + try std.testing.expectEqual(pen, g.pen_x); + }; + } + } + resetGlyphAtlas(&g); + g.pen_y = atlas_h; + try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '^'), .role = .tagline, .centered = true })); +} + +test "pane indicator halves are safe on an exhausted atlas" { + var cells: [12]pardes.Cell = @splat(.{ .default = false, .style = .{ .font_role = .tagline } }); + cells[0].text[0] = '$'; + // A grip two cells wide at the top left. + const grip = [_]pardes.Region{.{ .kind = .grip, .serial = 1, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}; + var cover: [12]Cover = undefined; + coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); + try std.testing.expect(cover[0].grip and cover[1].grip and !cover[2].grip); + // A column's grip is a button too, cut the same way (it has no glyph). + coverFrame(&cover, 6, 2, &.{}, &.{}, &.{.{ .kind = .column_grip, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}); + try std.testing.expect(cover[0].grip); + coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); + const chrome: pardes.Chrome = .{}; + + const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + defer c.ui_font_free(font); + var g = testGui(10, 20, 8, 16); + g.font = font; + g.px = 20; + g.tagline_px = 16; + g.pen_y = atlas_h; + g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); + defer g.glyphs.deinit(); + defer g.words.deinit(std.testing.allocator); + var instances: [4]CellInstance = undefined; + var next: u32 = 0; + for (0..2) |col| { + emitSurfaceCell(&g, &chrome, &instances, &next, @intCast(col), 0, fixedCellLayout(&g), 100, 100, cells[0..6], cover[0..6], col, null, false, bg_default); + try std.testing.expectEqual(@as(f32, 0), instances[col * 2 + 1].u0); + } + try std.testing.expectEqual(@as(u32, 4), next); +} + +test "a box-drawing rule reaches its cell's edges, and only its arms do" { + const stride = 12; + const width = 9; + const height = 15; + var mask: [stride * height]u8 = @splat(0xa5); + drawRule(&mask, stride, width, height, ruleArms(0x253c).?); + // ┼: ink on all four edges, none in the corners, nothing past the slot. + try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); + try std.testing.expectEqual(@as(u8, 255), mask[(height - 1) * stride + width / 2]); + try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride]); + try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride + width - 1]); + try std.testing.expectEqual(@as(u8, 0), mask[0]); + for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); + drawRule(&mask, stride, width, height, ruleArms(0x2502).?); + try std.testing.expectEqual(@as(u8, 0), mask[(height / 2) * stride]); + try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); + try std.testing.expect(ruleArms('|') == null); +} + +test "glyph decorations render spaces and stay inside their atlas slot" { + const stride = 9; + const width = 5; + const height = 7; + for ([_]GlyphDecoration{ + .{ .underline = .single }, + .{ .underline = .double }, + .{ .underline = .curly }, + .{ .underline = .dotted }, + .{ .underline = .dashed }, + .{ .strikethrough = true }, + }) |decoration| { + var mask: [stride * (height + 1)]u8 = @splat(0xa5); + for (0..height) |y| @memset(mask[y * stride ..][0..width], 0); + decorateLine(&mask, stride, width, height, 5, decoration); + try std.testing.expect(inkBounds(&mask, stride, width, height) != null); + for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| + try std.testing.expectEqual(@as(u8, 0xa5), guard); + for (mask[stride * height ..]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); + } + const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; + try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank()); +} + +test "the atlas's dirty rows hold every row a new glyph draws into, and a reset dirties them all" { + const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; + defer c.ui_font_free(font); + var g = try textTestGui(font, 18); + defer font_allocator = std.heap.smp_allocator; + defer std.testing.allocator.free(g.atlas_stage); + defer g.glyphs.deinit(); + defer g.words.deinit(std.testing.allocator); + // The texture as uploadAtlas leaves it, which starts undefined. + const texture = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); + defer std.testing.allocator.free(texture); + @memset(texture, 0xa5); + var glyph: u32 = 0; + for (0..40) |frame| { + if (frame == 30) resetGlyphAtlas(&g); // a font change + // Plain glyphs, strips, taglines, grip glyphs and decorations. + for (0..25) |_| { + glyph += 1; + const span: u4 = @intCast(1 + glyph % 3); + _ = cachedGlyph(&g, .{ + .face = 0, + .glyph = glyph, + .role = if (glyph % 4 == 0) .tagline else .body, + .decoration = .{ .bold = glyph % 2 == 0, .underline = if (glyph % 5 == 0) .curly else .off, .strikethrough = glyph % 11 == 0 }, + .centered = glyph % 13 == 0, + .lead = @intCast(glyph % span), + .span = span, + }) orelse return error.AtlasFull; + } + for (0..atlas_h) |row| { + const stage = g.atlas_stage[row * atlas_w ..][0..atlas_w]; + const uploaded = texture[row * atlas_w ..][0..atlas_w]; + if (row >= g.atlas_dirty_top and row < g.atlas_dirty_bottom) + @memcpy(uploaded, stage) + else + try std.testing.expect(std.mem.eql(u8, stage, uploaded)); + } + g.atlas_dirty_top = atlas_h; + g.atlas_dirty_bottom = 0; + } + try std.testing.expect(g.pen_y >= 2 * g.cell_h); +} + +test "overlapping background layers keep one uniform opacity" { + const blend = backgroundLayerBlend(); + try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR), blend.src_alpha_blendfactor); + try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA), blend.dst_alpha_blendfactor); + for ([_]f32{ 0, 0.25, 0.7, 1 }) |opacity| { + var alpha = opacity; + for ([_]f32{ 1, 0.5, 0.88, 0, 1 }) |coverage| { + alpha = opacity * coverage + alpha * (1 - coverage); + try std.testing.expectApproxEqAbs(opacity, alpha, 0.00001); + } + } +} + +test "background opacity retains exact endpoints and percentage precision" { + try std.testing.expectEqual(@as(f32, 0), backgroundOpacity(0)); + try std.testing.expectEqual(@as(f32, 0.7), backgroundOpacity(70)); + try std.testing.expectEqual(@as(f32, 1), backgroundOpacity(100)); + for (0..100) |percent| { + try std.testing.expect(backgroundOpacity(@intCast(percent)) < backgroundOpacity(@intCast(percent + 1))); + } +} + +test "InactiveDim fades the unfocused panes' rows alone, never below the text's floor" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + core.sync(); + const s = try core.render(core.scratch.allocator()); + defer dim = .{}; + dim.begin(60, s.regionList()); + try std.testing.expect(dim.focused != pardes.Region.none); + var cover: [80 * 24]Cover = undefined; + coverFrame(&cover, 80, 24, &.{}, &.{}, s.regionList()); + var seen: [2]bool = .{ false, false }; + for (s.regionList()) |region| if (region.kind == .body or region.kind == .tag) { + const unfocused = region.owner != dim.focused; + try std.testing.expectEqual(unfocused, cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); + seen[@intFromBool(unfocused)] = true; + } else if (region.kind == .grip) try std.testing.expect(!cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); + try std.testing.expect(seen[0] and seen[1]); + // Toward the ground, a pair already near its floor no further. + var instance: CellInstance = std.mem.zeroes(CellInstance); + instance.fr = 0.9; + instance.fg = 0.9; + instance.fb = 0.9; + dim.fade(&instance); + try std.testing.expect(instance.fr < 0.9 and instance.fr > 0); + try std.testing.expect(pardes.colors.contrast(Dim.byteRgb(.{ instance.fr, instance.fg, instance.fb }), .{ 0, 0, 0 }) >= 4.5 - 1e-3); + // Off, nothing fades. + dim.begin(0, s.regionList()); + try std.testing.expect(!dim.of(0) and !dim.of(1)); +} + +test "a theme's own rules and scrollbar are drawn at its widths: acme's 2px black rules and 12px track" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); + for (0..40) |_| core.update(.tick); + core.sync(); + const s = try core.render(core.scratch.allocator()); + try std.testing.expectEqual(@as(u8, 2), s.chrome.rule_px); + // acme's 12px, at GripWidth's 150% default. + try std.testing.expectEqual(@as(u8, 18), s.chrome.rail_px); + var g = testGui(16, 20, 10, 12); + defer g.decor.deinit(gpa); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 480, true); + const px = struct { + fn w(item: CellInstance) f32 { + return (item.x1 - item.x0) / 2 * 1280; + } + }; + var spines: usize = 0; + var tracks: usize = 0; + for (g.decor.items) |item| { + const black = item.br == 0 and item.bg == 0 and item.bb == 0; + // No rule at the window's left edge; one 2px spine where columns meet. + if (black and @abs(px.w(item) - 2) < 0.01 and item.y1 < -0.9) { + try std.testing.expect(item.x0 > -1); + spines += 1; + } + const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); + if (@abs(item.br - @as(f32, 0x99) / 255) < 1e-3 and @abs(item.bb - @as(f32, 0x4c) / 255) < 1e-3 and @abs(px.w(item) - (column[1] - column[0])) < 0.01) tracks += 1; + } + try std.testing.expectEqual(@as(usize, 1), spines); + try std.testing.expect(tracks >= 2); +} + +test "the scrollbar thumb moves by the pixel and follows a glide" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + const pane = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); + var g = testGui(10, 20, 6, 12); + defer g.decor.deinit(gpa); + const thumb = struct { + // The thumb's top, in window pixels. + fn top(gui: *Gui, p: *pardes.Pardes) !f32 { + gui.decor.clearRetainingCapacity(); + p.sync(); + const s = try p.render(p.scratch.allocator()); + var groups: Groups = .{}; + try buildDecor(gui, std.testing.allocator, s, &groups, fixedCellLayout(gui), 800, 480, true); + const ink = s.chrome.scroll_thumb; + for (gui.decor.items) |item| if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and + @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and + @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) return (1 - item.y0) / 2 * 480; + return error.TestExpectedThumb; + } + }; + pane.file.?.scroll = 10; + const at10 = try thumb.top(&g, core); + pane.file.?.scroll = 11; + const at11 = try thumb.top(&g, core); + // A line of a thousand moves it a fraction of a row, not 0 or 20 px. + try std.testing.expect(at11 > at10 and at11 - at10 < 1); + g.glide.pane = core.view().active; + g.glide.follow.offset = -1; + try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); + // A wrapped line: the picture moved two rows for the one line, and the + // thumb lags the line, not two. + g.glide.lines_moved = 1; + g.glide.rows_moved = 2; + g.glide.follow.offset = -2; + try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); +} + +test "the scrollbar thumb lies in its scroll column, a pixel short of the column's right edge, so the track edges it" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); + var g = testGui(10, 20, 6, 12); + defer g.decor.deinit(gpa); + core.sync(); + const s = try core.render(core.scratch.allocator()); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); + const ink = s.chrome.scroll_thumb; + const thumb = for (g.decor.items) |item| { + if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and + @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and + @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) break item; + } else return error.TestExpectedThumb; + // The pane is the window's first: its scroll column is at cell 0. + const column = scrollColumn(&g, &s.chrome, 0, fixedCellLayout(&g)); + try std.testing.expectApproxEqAbs(column[0], (thumb.x0 + 1) / 2 * 800, 1e-3); + try std.testing.expectApproxEqAbs(column[1] - 1, (thumb.x1 + 1) / 2 * 800, 1e-3); +} + +test "the rule between stacked panes stays in the tag band's slack, at any tagline size" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + core.newScratchBelow(0); + core.sync(); + const s = try core.render(core.scratch.allocator()); + const lower = for (s.regionList()) |region| { + if (region.kind == .tag and region.rect.y > 2) break region; + } else return error.TestExpectedStackedTag; + for ([_]u32{ 12, 20 }) |tagline_h| { + var g = testGui(10, 20, 6, tagline_h); + defer g.decor.deinit(gpa); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); + const top = @as(f32, @floatFromInt(lower.rect.y)) * 20; + const slack: f32 = @floatFromInt(@max(1, pardes.Layer.taglineBandOffset(lower.rect.y, 480, 20, tagline_h))); + var found = false; + for (g.decor.items) |item| { + const y0 = (1 - item.y0) / 2 * 480; + const y1 = (1 - item.y1) / 2 * 480; + if (@abs(y0 - top) > 0.01 or @abs(item.br - @as(f32, @floatFromInt(s.chrome.border[0])) / 255) > 1e-3) continue; + found = true; + try std.testing.expect(y1 - y0 <= slack + 0.01); + } + try std.testing.expect(found); + } +} + +test "an empty column is ruled on both sides, as between two filled ones" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + // Newcol from the left pane: an empty column between the two filled ones. + pardes.layout.newColumn(core, 0); + core.sync(); + try std.testing.expectEqual(@as(usize, 3), core.view().ncol); + try std.testing.expectEqual(@as(usize, 0), core.view().cols[1].n); + const s = try core.render(core.scratch.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.decor.deinit(gpa); + const layout = fixedCellLayout(&g); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); + const border = [3]f32{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 }; + // Its left edge and its right edge (the next column's left): each a + // rule `rule_px` wide in the border colour, down to the window's foot. + for ([_]usize{ 1, 2 }) |column| { + const px: f32 = @floatFromInt(@as(u32, core.view().col_x[column]) * 10); + const rule = for (g.decor.items) |item| { + if (@abs(item.x0 - (px / 800 * 2 - 1)) < 1e-4 and @abs(item.x1 - ((px + @as(f32, @floatFromInt(s.chrome.rule_px))) / 800 * 2 - 1)) < 1e-4 and + std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &border)) break item; + } else return error.TestExpectedColumnRule; + try std.testing.expectEqual(@as(f32, -1), rule.y1); + } +} + +test "at a 2x display every logical pixel is two: rules, the tag rule, the grip's ring, the rail's edge" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); + for (0..40) |_| core.update(.tick); + core.sync(); + const s = try core.render(core.scratch.allocator()); + for ([_]f32{ 1, 2 }) |scale| { + display_scale = scale; + defer display_scale = 1; + var g = testGui(16, 32, 12, 24); + defer g.decor.deinit(gpa); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 768, true); + const w = struct { + fn of(item: CellInstance) f32 { + return (item.x1 - item.x0) / 2 * 1280; + } + fn h(item: CellInstance) f32 { + return (item.y0 - item.y1) / 2 * 768; + } + }; + var spine: ?f32 = null; + var tag_rule: ?f32 = null; + var ring: ?f32 = null; + for (g.decor.items) |item| { + const rgb: [3]u8 = .{ @intFromFloat(@round(item.br * 255)), @intFromFloat(@round(item.bg * 255)), @intFromFloat(@round(item.bb * 255)) }; + // The spine between the columns: black, tall. + if (std.mem.eql(u8, &rgb, &.{ 0, 0, 0 }) and w.h(item) > 300) spine = @round(w.of(item)); + // The tag rule: #8888cc, wide and thin. + if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.of(item) > 200) tag_rule = @round(w.h(item)); + // The ring's left side: #8888cc, a tag row tall. + if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.h(item) > 10 and w.of(item) < 8) ring = @round(w.of(item)); + } + try std.testing.expectEqual(@as(?f32, 2 * scale), spine); + try std.testing.expectEqual(@as(?f32, 1 * scale), tag_rule); + try std.testing.expectEqual(@as(?f32, 2 * scale), ring); + // The rail starts after the rule, a logical 2 in, and keeps a + // logical 3 clear of the text when the cell is narrow. + const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); + try std.testing.expectEqual(40 * 16 + 2 * scale, column[0]); + g.cell_w = 12; + defer g.cell_w = 16; + const narrow = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); + try std.testing.expectEqual(@as(f32, 40 * 12 + 2 * scale), narrow[0]); + try std.testing.expectEqual(@as(f32, 40 * 12) + 12 * @as(f32, @floatFromInt(config.GUTTER)) - 3 * scale, narrow[1]); + g.cell_w = 8; + // A bar cursor is an eighth of its cell, never under a logical pixel + // (an 8 px cell: one pixel, two at 2x). + const saved = s.cursor; + defer s.cursor = saved; + s.cursor = .{ .x = 60, .y = 10, .bar = true }; + var boxes: [max_cursors]CursorBox = undefined; + const n = cursorBoxes(&g, s, fixedCellLayout(&g), 768, &boxes); + const bar = for (boxes[0..n]) |box| { + if (box.bar and box.x0 == 60 * 8) break box; + } else return error.NoBarCursor; + try std.testing.expectEqual(scale, bar.x1 - bar.x0); + } +} + +test "decor is read from the regions" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + core.sync(); + const s = try core.render(core.scratch.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.decor.deinit(gpa); + const layout = fixedCellLayout(&g); + const ndc = struct { + fn x(px: f32) f32 { + return px / 800 * 2 - 1; + } + }; + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); + // A spine one pixel wide at each column's left edge, down from under the + // workspace tag; a rail two pixels wide at each pane's. + for (core.view().col_x[0..core.view().ncol]) |x| { + const left = ndc.x(@as(f32, @floatFromInt(x)) * 10); + // Two pixels (rule_px), and none at the window's own edge. + const spine = for (g.decor.items) |item| { + if (item.x0 == left and @abs(item.x1 - ndc.x(@as(f32, @floatFromInt(x)) * 10 + 2)) < 0.0001 and + @abs(item.y0 - (1 - 20.0 / 480.0 * 2)) < 0.0001 and std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &.{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 })) break item; + } else null; + try std.testing.expectEqual(x == 0, spine == null); + if (spine) |rule| { + try std.testing.expectApproxEqAbs(@as(f32, 1 - 20.0 / 480.0 * 2), rule.y0, 0.0001); + try std.testing.expectEqual(@as(f32, -1), rule.y1); + } + // The scrollbar fills the scroll column right of the rule. + const column = scrollColumn(&g, &s.chrome, x, layout); + const rail = for (g.decor.items) |item| { + if (@abs(item.x0 - ndc.x(column[0])) < 0.0001 and @abs(item.x1 - ndc.x(column[1])) < 0.0001 and + @abs(item.br - @as(f32, @floatFromInt(s.chrome.scroll_track[0])) / 255) < 0.0001) break item; + } else return error.TestExpectedRail; + _ = rail; + } + try std.testing.expectEqual(@as(u32, 0), groups.items[groups.notices].decor_count); +} + +test "a body tells its first line" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + const pane = try core.setTestFile(std.mem.asBytes(&@as([80][5]u8, @splat("line\n".*)))); + pane.scrollBy(8); + core.sync(); + const s = try core.render(core.scratch.allocator()); + const body = for (s.regionList()) |region| { + if (region.kind == .body) break region; + } else return error.NoBody; + try std.testing.expectEqual(@as(i32, 8), body.line); +} + +test "a caret eases a cell at a time, keeps up with typing, and glides a jump, landing exactly" { + const ms = std.time.ns_per_ms; + var caret: Caret = .{}; + caret.aim(.{ .x = 3, .y = 4, .w = 1, .h = 1 }, 0, false); + // The first mark lands at once. + try std.testing.expect(!caret.moving()); + // A step eases, a stream of them keeps up. + caret.aim(.{ .x = 4, .y = 4, .w = 1, .h = 1 }, 1000 * ms, false); + try std.testing.expect(caret.moving()); + caret.aim(.{ .x = 5, .y = 4, .w = 1, .h = 1 }, 1050 * ms, false); + try std.testing.expect(!caret.moving()); + // A jump glides, the leading corner ahead, and lands exactly. + caret.aim(.{ .x = 30, .y = 10, .w = 1, .h = 1 }, 2000 * ms, false); + try std.testing.expect(caret.moving()); + const mid = caret.sample(2040 * ms); + try std.testing.expect(mid[1][0] > mid[0][0] - 1 and mid[0][0] > 5 and mid[0][0] < 30); + var t: u64 = 2040 * ms; + while (caret.step(t)) t += 16 * ms; + try std.testing.expect(t < 2400 * ms); + try std.testing.expectEqual([2]f32{ 30, 10 }, caret.sample(t)[0]); + // A scroll lands it with its text. + caret.see(.{ .x = 30, .y = 8, .w = 1, .h = 1 }, 0, 10, 2, 1, t); + caret.see(.{ .x = 30, .y = 6, .w = 1, .h = 1 }, 0, 12, 2, 1, t + 16 * ms); + try std.testing.expect(!caret.moving()); +} + +test "a jump's trail is drawn behind the cursor in its body, and gone by 120 ms" { + var cells: [80 * 4]pardes.Cell = @splat(.{}); + var surface: pardes.Surface = .{ .cols = 80, .rows = 4, .cells = &cells }; + surface.regions[0] = .{ .kind = .body, .rect = .{ .x = 2, .y = 0, .w = 78, .h = 4 } }; + surface.nregions = 1; + var g = testGui(10, 20, 8, 16); + var vertices: [5 * 6]OverlayVertex = undefined; + var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 80 }; + const ms = std.time.ns_per_ms; + surface.cursor = .{ .x = 4, .y = 1 }; + appendJumpTrail(&g, true, &surface, 1000 * ms, &builder); + try std.testing.expectEqual(@as(usize, 0), builder.len); + surface.cursor = .{ .x = 14, .y = 1 }; + appendJumpTrail(&g, true, &surface, 1016 * ms, &builder); + try std.testing.expect(builder.len >= 3 * 6 and builder.len <= 5 * 6); + // On the cursor's row, behind it, never its own cell. + for (vertices[0..builder.len]) |v| { + const x = (v.x + 1) * 400; + const y = (1 - v.y) * 40; + try std.testing.expect(y >= 20 - 0.01 and y <= 40 + 0.01); + try std.testing.expect(x >= 50 - 0.01 and x <= 140 + 0.01); + } + try std.testing.expect(g.trail.active); + builder.len = 0; + appendJumpTrail(&g, true, &surface, 1150 * ms, &builder); + try std.testing.expectEqual(@as(usize, 0), builder.len); + try std.testing.expect(!g.trail.active); +} + +test "a pet stays past the workspace tag's text, and off it is gone" { + std.testing.refAllDecls(pet); + var cells: [80]pardes.Cell = @splat(.{}); + const surface: pardes.Surface = .{ .cols = 80, .rows = 1, .cells = &cells }; + for ("Workspace Commands", 0..) |ch, i| { + cells[i].text[0] = ch; + cells[i].len = 1; + cells[i].default = false; + } + var g = testGui(10, 20, 8, 16); + var vertices: [pet.max_vertices]OverlayVertex = undefined; + var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 480 }; + appendWorkspacePet(&g, .cat, &surface, &builder); + try std.testing.expect(builder.len > 0); + for (vertices[0..builder.len]) |v| { + const x = (v.x + 1) * 400; + const y = (1 - v.y) * 240; + try std.testing.expect(x >= 20 * 8 - 0.01); + try std.testing.expect(y >= 0 and y < 20); + } + builder.len = 0; + appendWorkspacePet(&g, .off, &surface, &builder); + try std.testing.expectEqual(@as(usize, 0), builder.len); + try std.testing.expectEqual(@as(?u64, null), g.pet_state.tick); +} + test "compact body layer rendering fills recovered rows and clips the final glyph" { var g = testGui(10, 20, 6, 12); var cells: [24]pardes.Cell = @splat(.{}); |
