From 5157579ff7f9ae0cfc3c7629e953da05bce340fc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 9 Nov 2026 00:52:52 -0300 Subject: 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 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/gui/gui.zig | 7384 +++++++++++++++++++++++++++---------------------------- 1 file changed, 3692 insertions(+), 3692 deletions(-) (limited to 'src/gui') 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,262 +489,29 @@ 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, +fn stopPipe() ![2]c_int { + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.PipeFailed; + errdefer for (fds) |fd| { + _ = libc.close(fd); + }; + for (fds) |fd| if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 0) return error.PipeFailed; + return fds; +} + +fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { + while (true) { + var fds = [_]libc.pollfd{ + .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 }, + .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }, }; - 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; - errdefer for (fds) |fd| { - _ = libc.close(fd); - }; - for (fds) |fd| if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 0) return error.PipeFailed; - return fds; -} - -fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { - while (true) { - var fds = [_]libc.pollfd{ - .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 }, - .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }, - }; - if (libc.poll(&fds, fds.len, -1) < 0) { - if (libc.errno(-1) == .INTR) continue; - return; - } - if (fds[0].revents != 0) return; - if ((fds[1].revents & (libc.POLL.ERR | libc.POLL.HUP | libc.POLL.NVAL)) != 0) return; - if (fds[1].revents != 0 and file_watch.drain(fd)) q.push(.files_changed); - } -} - -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); + if (libc.poll(&fds, fds.len, -1) < 0) { + if (libc.errno(-1) == .INTR) continue; + return; + } + if (fds[0].revents != 0) return; + if ((fds[1].revents & (libc.POLL.ERR | libc.POLL.HUP | libc.POLL.NVAL)) != 0) return; + if (fds[1].revents != 0 and file_watch.drain(fd)) q.push(.files_changed); } } @@ -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,89 +1986,23 @@ 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 => {}, +const Input = struct { + core: *pardes.Pardes, + /// The shell whose window this is (views.zig: its view is `gview`). + shell: ?*Shell = null, + /// A replica client's (`remote`): its inputs go to its link, never + /// straight to the core, which only reads here. + remote: ?*Client = null, + quit: bool = false, + + fn post(in: *Input, ev: pardes.Event) void { + if (in.remote) |r| return r.post(ev); + // The window's input is its own view's, a replica client's input + // the session's last or not. + if (in.shell) |s| if (s.core.live != s.gview) { + _ = s.windowView(); }; - } - 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`). - shell: ?*Shell = null, - /// A replica client's (`remote`): its inputs go to its link, never - /// straight to the core, which only reads here. - remote: ?*Client = null, - quit: bool = false, - - fn post(in: *Input, ev: pardes.Event) void { - if (in.remote) |r| return r.post(ev); - // The window's input is its own view's, a replica client's input - // the session's last or not. - if (in.shell) |s| if (s.core.live != s.gview) { - _ = s.windowView(); - }; - in.core.update(ev); + in.core.update(ev); } fn close(in: *Input) void { @@ -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,126 +3646,7 @@ 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; +const Glide = pardes.glide.Glide; /// Feeds a wheel's notches to the core, and keeps what moved the view for /// the frame's glide (Glide.frame). @@ -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,222 +3748,51 @@ 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; -} +/// 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` +/// names; each frame's picture offset and the core's first line. +const GlideRun = struct { + const Step = struct { frame: usize, key: pardes.Key }; + offsets: [600]f32 = undefined, + lines: [600]i64 = undefined, + carets: [600]f32 = undefined, + cells: [600]f32 = undefined, + frames: usize = 0, -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); + fn play(seq: *GlideRun, g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator, arena: *std.heap.ArenaAllocator, script: []const Step, frames: usize) !void { + var now: u64 = core.clock.now_ns; + var next: usize = 0; + for (0..frames) |frame| { + while (next < script.len and script[next].frame == frame) : (next += 1) core.update(.{ .key = script[next].key }); + now += std.time.ns_per_s / 60; + core.advance(now); + stepGlide(g, core); + _ = arena.reset(.retain_capacity); + const s = try core.render(arena.allocator()); + g.now_ns = now; + glideFrame(g, gpa, s); + seeCaret(g, s, fixedCellLayout(g), @floatFromInt(@as(u32, s.rows) * g.cell_h), now); + seq.offsets[frame] = g.glide.follow.offset; + seq.lines[frame] = @intCast(core.panes[core.view().active].?.file.?.scroll); + seq.carets[frame] = caretRow(g, s, now) orelse -1; + seq.cells[frame] = if (s.cursor) |cu| @floatFromInt(cu.y) else -1; + } + seq.frames = frames; } - 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` -/// names; each frame's picture offset and the core's first line. -const GlideRun = struct { - const Step = struct { frame: usize, key: pardes.Key }; - offsets: [600]f32 = undefined, - lines: [600]i64 = undefined, - carets: [600]f32 = undefined, - cells: [600]f32 = undefined, - frames: usize = 0, - - fn play(seq: *GlideRun, g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator, arena: *std.heap.ArenaAllocator, script: []const Step, frames: usize) !void { - var now: u64 = core.clock.now_ns; - var next: usize = 0; - for (0..frames) |frame| { - while (next < script.len and script[next].frame == frame) : (next += 1) core.update(.{ .key = script[next].key }); - now += std.time.ns_per_s / 60; - core.advance(now); - stepGlide(g, core); - _ = arena.reset(.retain_capacity); - const s = try core.render(arena.allocator()); - g.now_ns = now; - glideFrame(g, gpa, s); - seeCaret(g, s, fixedCellLayout(g), @floatFromInt(@as(u32, s.rows) * g.cell_h), now); - seq.offsets[frame] = g.glide.follow.offset; - seq.lines[frame] = @intCast(core.panes[core.view().active].?.file.?.scroll); - seq.carets[frame] = caretRow(g, s, now) orelse -1; - seq.cells[frame] = if (s.cursor) |cu| @floatFromInt(cu.y) else -1; - } - seq.frames = frames; - } - - /// The caret's invariants over the run: while its cell stays and it is - /// on it, it does not move a pixel; it only ever closes on its cell (a - /// twentieth of a row of play for a jump's bow); it lands within half a - /// second of its last change. - fn checkCaret(seq: *const GlideRun) !void { - var changed: usize = 0; - for (1..seq.frames) |k| { - if (seq.cells[k] < 0 or seq.cells[k - 1] < 0) continue; - if (seq.cells[k] != seq.cells[k - 1]) changed = k; - if (seq.cells[k] == seq.cells[k - 1] and seq.carets[k - 1] == seq.cells[k - 1]) try std.testing.expectEqual(seq.carets[k - 1], seq.carets[k]); - try std.testing.expect(@abs(seq.carets[k] - seq.cells[k]) <= @abs(seq.carets[k - 1] - seq.cells[k]) + 0.05); - if (k - changed == 30) try std.testing.expectEqual(seq.cells[k], seq.carets[k]); + /// The caret's invariants over the run: while its cell stays and it is + /// on it, it does not move a pixel; it only ever closes on its cell (a + /// twentieth of a row of play for a jump's bow); it lands within half a + /// second of its last change. + fn checkCaret(seq: *const GlideRun) !void { + var changed: usize = 0; + for (1..seq.frames) |k| { + if (seq.cells[k] < 0 or seq.cells[k - 1] < 0) continue; + if (seq.cells[k] != seq.cells[k - 1]) changed = k; + if (seq.cells[k] == seq.cells[k - 1] and seq.carets[k - 1] == seq.cells[k - 1]) try std.testing.expectEqual(seq.carets[k - 1], seq.carets[k]); + try std.testing.expect(@abs(seq.carets[k] - seq.cells[k]) <= @abs(seq.carets[k - 1] - seq.cells[k]) + 0.05); + if (k - changed == 30) try std.testing.expectEqual(seq.cells[k], seq.carets[k]); } } @@ -4831,130 +3804,14 @@ 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; - g.scroll_lag = 0; - g.scroll_idle = 0; - g.scroll_edge_len = 0; - g.scroll_notch = 0; - g.glide.stop(); +fn resetScroll(g: *Gui) void { + g.scroll_pane = null; + g.scroll_delta = 0; + g.scroll_lag = 0; + g.scroll_idle = 0; + g.scroll_edge_len = 0; + g.scroll_notch = 0; + g.glide.stop(); } /// Loop steps with no turn before a resting fraction settles; the share of @@ -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,2404 +4897,3861 @@ 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]); +fn emitInstance( + g: *Gui, + instances: [*]CellInstance, + idx: u32, + col: u16, + row: u16, + layout: CellLayout, + win_w: f32, + win_h: f32, + role: pardes.FontRole, + line: []const pardes.Cell, + at: usize, + cursor: ?usize, + is_cursor: bool, + page: [3]u8, +) void { + const resolved = resolveCell(g, line, at, cursor, role, is_cursor, page); + + const px0 = layout.x_off + @as(f32, @floatFromInt(col)) * layout.w; + const visual_h: f32 = if (resolved.role == .tagline) + @floatFromInt(g.tagline_height) + else + layout.h; + const band_offset: f32 = if (resolved.role == .tagline) + @floatFromInt(taglineBandOffset(row, win_h, g.cell_h, g.tagline_height)) + else + 0; + const py0 = layout.y_off + @as(f32, @floatFromInt(row)) * layout.h + band_offset; + const x0 = (px0 / win_w) * 2.0 - 1.0; + const x1 = ((px0 + layout.w) / win_w) * 2.0 - 1.0; + const y0 = 1.0 - (py0 / win_h) * 2.0; + const y1 = 1.0 - ((py0 + visual_h) / win_h) * 2.0; + const aw_f: f32 = @floatFromInt(atlas_w); + const ah_f: f32 = @floatFromInt(atlas_h); + const uv_w: u32 = if (resolved.role == .tagline) g.tagline_width else g.cell_w; + const uv_h: u32 = if (resolved.role == .tagline) g.tagline_height else g.cell_h; + + instances[idx] = .{ + .x0 = x0, + .y0 = y0, + .x1 = x1, + .y1 = y1, + .u0 = @as(f32, @floatFromInt(resolved.slot.u)) / aw_f, + .v0 = @as(f32, @floatFromInt(resolved.slot.v)) / ah_f, + .u1 = @as(f32, @floatFromInt(resolved.slot.u + uv_w)) / aw_f, + .v1 = @as(f32, @floatFromInt(resolved.slot.v + uv_h)) / ah_f, + .fr = @as(f32, @floatFromInt(resolved.fg[0])) / 255.0, + .fg = @as(f32, @floatFromInt(resolved.fg[1])) / 255.0, + .fb = @as(f32, @floatFromInt(resolved.fg[2])) / 255.0, + .br = @as(f32, @floatFromInt(resolved.bg[0])) / 255.0, + .bg = @as(f32, @floatFromInt(resolved.bg[1])) / 255.0, + .bb = @as(f32, @floatFromInt(resolved.bg[2])) / 255.0, + }; + // A block cursor is foreground UI ink, even though its color is carried + // in the reversed cell background. Keep it visible at WindowOpacity 0. + if (is_cursor) instances[idx].effect |= opaque_bg_bit; +} + +fn cellCodepoint(cell: *const pardes.Cell) u32 { + const grapheme = cell.grapheme(); + return if (cell.default or grapheme.len == 0) ' ' else firstCp(grapheme); +} + +fn palColor(idx: u8) [3]u8 { + const p = ghostty_vt.color.default[idx]; + return .{ p.r, p.g, p.b }; +} + +fn firstCp(s: []const u8) u32 { + if (s.len == 0) return ' '; + const n = std.unicode.utf8ByteSequenceLength(s[0]) catch return ' '; + if (n > s.len) return ' '; + return std.unicode.utf8Decode(s[0..n]) catch ' '; +} + +fn refitFont(g: *Gui, core: ?*pardes.Pardes) void { + var cw: c_int = 10; + var chh: c_int = 20; + var asc: c_int = 16; + c.ui_font_cell_metrics(g.font, g.px, &cw, &chh, &asc); + g.cell_w = @intCast(@max(cw, 1)); + g.cell_h = @intCast(@max(chh, 1)); + g.ascent = @intCast(@max(asc, 1)); + const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, g.tagline_percent); + g.tagline_px = tagline.px; + g.tagline_width = tagline.width; + g.tagline_baseline = tagline.baseline; + g.tagline_height = tagline.height; + + resetGlyphAtlas(g); + + if (core) |p| { + const geom = windowCells(g); + _ = updateCoreResize(p, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); + } + + resetScroll(g); +} + +// The first cell of the cleared atlas stays blank: the space slot. +fn resetGlyphAtlas(g: *Gui) void { + g.glyphs.clearRetainingCapacity(); + g.words.clear(); + @memset(g.atlas_stage, 0); + g.space_slot = .{ .u = 0, .v = 0 }; + g.pen_x = g.cell_w; + g.pen_y = 0; + g.atlas_dirty_top = 0; + g.atlas_dirty_bottom = atlas_h; +} + +fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void { + if (!fitTaglineFont(g, core.settings.font.tagline_percent)) return; + const geom = windowCells(g); + _ = updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); +} + +/// The tagline's face at `percent` of the body's: whether it changed. +fn fitTaglineFont(g: *Gui, percent: u8) bool { + if (percent == g.tagline_percent) return false; + g.tagline_percent = percent; + const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, percent); + g.tagline_px = tagline.px; + g.tagline_width = tagline.width; + g.tagline_baseline = tagline.baseline; + g.tagline_height = tagline.height; + resetGlyphAtlas(g); + return true; +} + +/// What text draws, so a frame does not work it out again. `cells` is the +/// atlas slot of a codepoint no ligature can touch (`shape_slot` for one that +/// is shaped with its word); `map` is the atlas slot of every cell of a word +/// holding one, found by the word's text. Bounded: past `max_cells` word cells +/// it starts over, and the next frames look up what they show again (the +/// glyphs stay in the atlas). +const Words = struct { + cells: std.AutoHashMapUnmanaged(CellKey, Slot) = .empty, + map: std.AutoHashMapUnmanaged(u64, Word) = .empty, + /// Every word's codepoints and slots, end to end; a Word indexes both. + text: std.ArrayListUnmanaged(u32) = .empty, + slots: std.ArrayListUnmanaged(Slot) = .empty, + shaped: std.ArrayListUnmanaged(c.UIShapedCell) = .empty, + /// The word the last cell was in, so the rest of it costs a compare. It + /// is positional, so every frame forgets it: the cells change under it. + memo: Memo = .{}, + + const max_cells = 1 << 17; + const CellKey = packed struct(u64) { cp: u21, role: pardes.FontRole, decoration: GlyphDecoration, _: u30 = 0 }; + const shape_slot: Slot = .{ .u = std.math.maxInt(u32), .v = std.math.maxInt(u32) }; + const Word = struct { start: u32, len: u32, decoration: GlyphDecoration }; + const Memo = struct { + line: ?[*]const pardes.Cell = null, + len: usize = 0, + start: usize = 0, + end: usize = 0, + cursor: ?usize = null, + slots: usize = 0, + }; + + fn clear(w: *Words) void { + w.cells.clearRetainingCapacity(); + w.map.clearRetainingCapacity(); + w.text.clearRetainingCapacity(); + w.slots.clearRetainingCapacity(); + w.memo = .{}; + } + + fn deinit(w: *Words, gpa: std.mem.Allocator) void { + w.cells.deinit(gpa); + w.map.deinit(gpa); + w.text.deinit(gpa); + w.slots.deinit(gpa); + w.shaped.deinit(gpa); + } +}; + +/// What decides where a word ends, for one cell. A concealed cell is a space. +const WordCell = struct { cp: u32, decoration: GlyphDecoration, role: pardes.FontRole }; + +fn wordCell(cell: *const pardes.Cell) WordCell { + return .{ + .cp = if (!cell.default and cell.style.invisible) ' ' else cellCodepoint(cell), + .decoration = GlyphDecoration.fromCell(cell), + .role = cellFontRole(cell), + }; +} + +/// Whether a word ends between `a`, cell `i`, and `b`, cell `i + 1`: at a +/// space, a decoration or role change, either side of the cursor (Ghostty's +/// rule: the cell being edited shows its own glyph, so a ligature under the +/// cursor comes apart), and inside f|i, f|l and s|t, whose typographic +/// ligatures do not belong on a grid (Ghostty again). Colours never end a +/// word: a ligature spans a syntax colour change or a selection edge, and each +/// cell tints its own slice. +fn wordBreak(a: WordCell, b: WordCell, i: usize, cursor: ?usize) bool { + if (a.cp == ' ' or b.cp == ' ') return true; + // A rule is drawn by hand (ruleArms), never a slice of a shaped word. + if (ruleArms(a.cp) != null or ruleArms(b.cp) != null) return true; + if (cursor) |at| if (at == i or at == i + 1) return true; + if (a.role != b.role or !std.meta.eql(a.decoration, b.decoration)) return true; + return (a.cp == 'f' and (b.cp == 'i' or b.cp == 'l')) or (a.cp == 's' and b.cp == 't'); +} + +/// The atlas slot `line[at]` draws: blank for a plain space (or concealed +/// text), its own glyph when no ligature could replace that glyph (every +/// cell, in a font without ligatures), else its slice +/// of the word around it, shaped once and cached by the word's text. The +/// cells of a word being walked cost a compare. Taglines are not shaped: they are drawn at two pitches +/// (tagline_width in a tag layer, a whole cell in the grid), and a strip would +/// not line up in one of them. +fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: pardes.FontRole) Slot { + const words = &g.words; + const memo = words.memo; + if (memo.line == line.ptr and memo.len == line.len and memo.cursor == cursor and at >= memo.start and at < memo.end and role == .body) + return words.slots.items[memo.slots + at - memo.start]; + var here = wordCell(&line[at]); + // An underlined or struck-out space is a glyph of its own: it draws its line. + if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.space_slot; + if (ruleArms(here.cp) != null) + return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = role, .rule = true }) orelse g.space_slot; + const gpa = g.glyphs.allocator; + const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration }; + const known = words.cells.getOrPut(gpa, cell_key) catch return g.space_slot; + if (!known.found_existing) { + const drawn = glyphForCodepoint(g, here.cp); + const font = if (drawn.face == 0) g.font else g.fallbacks[drawn.face - 1].?.face; + known.value_ptr.* = if (role == .body and c.ui_font_substitutes(font, drawn.glyph) != 0) + Words.shape_slot + else + cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = role, .decoration = here.decoration }) orelse g.space_slot; + } + const plain = known.value_ptr.*; + if (!std.meta.eql(plain, Words.shape_slot)) return plain; + + if (words.text.items.len > Words.max_cells) words.clear(); + var start = at; + while (start > 0) { + const before = wordCell(&line[start - 1]); + if (wordBreak(before, here, start - 1, cursor)) break; + start -= 1; + here = before; + } + // The word's text goes on the end of `text`: a new word keeps it there, + // a known one gives it back. + const text_start = words.text.items.len; + var end = start; + while (true) { + words.text.append(gpa, here.cp) catch return g.space_slot; + end += 1; + if (end == line.len) break; + const next = wordCell(&line[end]); + if (wordBreak(here, next, end - 1, cursor)) break; + here = next; + } + const text = words.text.items[text_start..]; + const decoration = here.decoration; + const hash = std.hash.Wyhash.hash(@as(u5, @bitCast(decoration)), std.mem.sliceAsBytes(text)); + if (words.map.get(hash)) |word| { + if (word.len == text.len and std.meta.eql(word.decoration, decoration) and + std.mem.eql(u32, words.text.items[word.start..][0..word.len], text)) + { + words.text.shrinkRetainingCapacity(text_start); + words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = word.start }; + return words.slots.items[word.start + at - start]; + } + } + + // A new word (a hash collision takes the map entry over). Runs of one + // face are shaped in that face; fallback faces shape like the primary. + const probe_shape = monoNs(); + defer if (frame_probe) |probe| { + probe.zone(.gui_shape, probe_shape); + probe.shaped +|= 1; + }; + const n = text.len; + words.slots.ensureUnusedCapacity(gpa, n) catch { + words.text.shrinkRetainingCapacity(text_start); + return g.space_slot; + }; + words.shaped.resize(gpa, n) catch { + words.text.shrinkRetainingCapacity(text_start); + return g.space_slot; + }; + const shaped = words.shaped.items; + var run_start: usize = 0; + var face = glyphForCodepoint(g, text[0]).face; + while (run_start < n) { + var run_end = run_start + 1; + var next_face = face; + while (run_end < n) : (run_end += 1) { + next_face = glyphForCodepoint(g, text[run_end]).face; + if (next_face != face) break; + } + const run_font = if (face == 0) g.font else g.fallbacks[face - 1].?.face; + c.ui_font_shape(run_font, g.px, @intCast(g.cell_w), text[run_start..].ptr, @intCast(run_end - run_start), shaped[run_start..].ptr); + for (shaped[run_start..run_end]) |cell| { + const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = decoration, .lead = @intCast(cell.lead), .span = @intCast(cell.span) }; + const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.space_slot; + words.slots.appendAssumeCapacity(slot); + } + run_start = run_end; + face = next_face; + } + words.map.put(gpa, hash, .{ .start = @intCast(text_start), .len = @intCast(n), .decoration = decoration }) catch {}; + words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = text_start }; + return words.slots.items[text_start + at - start]; +} + +/// A Gui for the tests that build cells, decor or a scroll without a +/// window: these metrics, every other field its default. What needs SDL, a +/// font or the atlas is undefined (textTestGui adds a font and an atlas). +fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gui { + return .{ + .window = undefined, + .device = undefined, + .swapchain_format = undefined, + .pipeline = undefined, + .decor_pipeline = undefined, + .overlay_pipeline = undefined, + .image_pipeline = undefined, + .atlas_tex = undefined, + .atlas_sampler = undefined, + .linear_sampler = undefined, + .atlas_xfer = undefined, + .overlay_vbuf = undefined, + .overlay_vxfer = undefined, + .overlay_vertices = &.{}, + .font = undefined, + .px = 0, + .tagline_px = 0, + .tagline_percent = 0, + .tagline_width = tagline_width, + .tagline_height = tagline_height, + .cell_w = cell_w, + .cell_h = cell_h, + .ascent = 0, + .tagline_baseline = 0, + .atlas_stage = &.{}, + .glyphs = undefined, + }; +} + +/// 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. +fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { + if (g.glyphs.get(key)) |s| return s; + const slot_w = g.cell_w * @as(u32, if (key.centered) config.GUTTER else key.span); + if (g.pen_x + slot_w > atlas_w) { + g.pen_x = 0; + g.pen_y += g.cell_h; + } + if (g.pen_y + g.cell_h > atlas_h) return null; // atlas full: fall back + const probe_raster = monoNs(); + defer if (frame_probe) |probe| { + probe.zone(.gui_raster, probe_raster); + probe.rastered +|= 1; + }; + const s = Slot{ .u = g.pen_x, .v = g.pen_y }; + const out = g.atlas_stage.ptr + @as(usize, s.v) * atlas_w + s.u; + const face = if (key.face == 0) g.font else g.fallbacks[key.face - 1].?.face; + const px = if (key.role == .tagline) g.tagline_px else g.px; + const baseline = if (key.role == .tagline) g.tagline_baseline else g.ascent; + const cell_w = if (key.role == .tagline) g.tagline_width else g.cell_w; + const raster_w = if (key.centered) slot_w else cell_w * key.span; + const raster_h = if (key.role == .tagline) g.tagline_height else g.cell_h; + const bold = @intFromBool(key.decoration.bold); + if (key.rule) { + drawRule(out, atlas_w, raster_w, raster_h, ruleArms(key.glyph).?); + } else if (key.centered) { + _ = c.ui_font_raster_centered(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h)); + } else { + _ = c.ui_font_raster(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h), @intCast(cell_w * key.lead), @intCast(cell_w), baseline); + } + decorateLine(out, atlas_w, raster_w, raster_h, baseline, key.decoration); + if (key.centered) centerGlyphInk(out, raster_w, raster_h); + g.atlas_dirty_top = @min(g.atlas_dirty_top, s.v); + g.atlas_dirty_bottom = @max(g.atlas_dirty_bottom, s.v + raster_h); + g.glyphs.put(key, s) catch return null; + g.pen_x += slot_w; + return s; +} + +// Run once when a grip glyph enters the atlas, after decorations. Copy only +// visible ink so bearings, empty bitmap margins and bold all share one center. +fn centerGlyphInk(out: [*]u8, width: usize, height: usize) void { + const b = inkBounds(out[0 .. (height - 1) * atlas_w + width], atlas_w, width, height) orelse return; + const w = b.max_x - b.min_x + 1; + const h = b.max_y - b.min_y + 1; + const left = (width - w) / 2; + const top = (height - h) / 2; + var scratch: [atlas_w]u8 = undefined; + for (0..h) |step| { + const row = if (top > b.min_y) h - 1 - step else step; + const source = (b.min_y + row) * atlas_w + b.min_x; + const target = (top + row) * atlas_w; + @memcpy(scratch[0..w], out[source..][0..w]); + @memset(out[target..][0..width], 0); + @memcpy(out[target + left ..][0..w], scratch[0..w]); + } + for (0..height) |row| { + if (row < top or row >= top + h) @memset(out[row * atlas_w ..][0..width], 0); + } +} + +// 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 +// decorates terminal spaces. Bold is not drawn here: the rasterizer emboldens +// the outline. +fn decorateLine(out: [*]u8, stride: usize, width: usize, height: usize, baseline: i32, decoration: GlyphDecoration) void { + if (width == 0 or height == 0) return; + // A line is a logical pixel thick, its dots and waves as long: the same + // weight at any density (dp). + const t: usize = @intFromFloat(dp(1)); + if (decoration.underline != .off) { + const base: usize = @intCast(@max(0, baseline)); + const row = @min(base + 1, height -| t); + for (0..width) |x| { + const top = switch (decoration.underline) { + .off => unreachable, + .single => row, + .double => { + const upper = @min(base + 1, height -| 3 * t); + for (0..t) |k| { + out[@min(upper + k, height - 1) * stride + x] = 255; + out[@min(upper + 2 * t + k, height - 1) * stride + x] = 255; + } + continue; + }, + .curly => row -| @as(usize, if (x % (4 * t) < 2 * t) t else 0), + .dotted => if (x % (3 * t) < t) row else continue, + .dashed => if (x % (6 * t) < 4 * t) row else continue, + }; + for (0..t) |k| out[@min(top + k, height - 1) * stride + x] = 255; + } + } + if (decoration.strikethrough) { + const row = @min(height -| t, @as(usize, @intCast(@max(0, baseline))) * 2 / 3); + for (0..t) |k| @memset(out[@min(row + k, height - 1) * stride ..][0..width], 255); + } +} + +/// 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 +/// offset in the transfer buffer as in the stage, and the texture keeps the +/// rows outside it. +fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void { + const top = g.atlas_dirty_top; + const rows = g.atlas_dirty_bottom - top; + const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.atlas_xfer, false) orelse return; + const dst: [*]u8 = @ptrCast(ptr); + @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], g.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]); + c.SDL_UnmapGPUTransferBuffer(g.device, g.atlas_xfer); + + const copy = c.SDL_BeginGPUCopyPass(cmd); + const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = g.atlas_xfer, .offset = top * atlas_w, .pixels_per_row = atlas_w, .rows_per_layer = rows }; + const dstregion = c.SDL_GPUTextureRegion{ .texture = g.atlas_tex, .mip_level = 0, .layer = 0, .x = 0, .y = top, .z = 0, .w = atlas_w, .h = rows, .d = 1 }; + c.SDL_UploadToGPUTexture(copy, &src, &dstregion, false); + c.SDL_EndGPUCopyPass(copy); + g.atlas_dirty_top = atlas_h; + g.atlas_dirty_bottom = 0; +} + +/// 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). +fn growInstances(g: *Gui, buffer: *?*c.SDL_GPUBuffer, transfer: *?*c.SDL_GPUTransferBuffer, capacity: *u32, needed: u32, stride: u32) !void { + if (needed <= capacity.* and buffer.* != null and transfer.* != null) return; + var grown = @max(@as(u32, 1), capacity.*); + while (grown < needed) grown = std.math.mul(u32, grown, 2) catch return error.GpuCapacity; + const size = std.math.mul(u32, grown, stride) catch return error.GpuCapacity; + var vb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = size, .props = 0 }; + const next_buffer = c.SDL_CreateGPUBuffer(g.device, &vb_info) orelse return error.GpuCreate; + errdefer c.SDL_ReleaseGPUBuffer(g.device, next_buffer); + var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = size, .props = 0 }; + const next_transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate; + if (buffer.*) |old| c.SDL_ReleaseGPUBuffer(g.device, old); + if (transfer.*) |old| c.SDL_ReleaseGPUTransferBuffer(g.device, old); + buffer.* = next_buffer; + transfer.* = next_transfer; + capacity.* = grown; +} + +/// One vertex buffer of a pipeline: `pitch` bytes an element, read per +/// vertex or per instance through `attrs`. +const VertexInput = struct { pitch: u32, rate: c.SDL_GPUVertexInputRate, attrs: []const c.SDL_GPUVertexAttribute }; + +/// The cells' and the decor's instances (ui.vert.glsl). +const cell_input: VertexInput = .{ .pitch = @sizeOf(CellInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{ + .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "x0") }, + .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "u0") }, + .{ .location = 2, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "fr") }, + .{ .location = 3, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "br") }, + .{ .location = 4, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_UINT, .offset = @offsetOf(CellInstance, "effect") }, + .{ .location = 5, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "clip_x0") }, +} }; + +const overlay_input: VertexInput = .{ .pitch = @sizeOf(OverlayVertex), .rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .attrs = &.{ + .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, .offset = @offsetOf(OverlayVertex, "x") }, + .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(OverlayVertex, "r") }, +} }; + +const image_input: VertexInput = .{ .pitch = @sizeOf(ImageInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{ + .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "x0") }, + .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "u0") }, +} }; + +/// A pipeline drawing triangles into `color_format`: `vert`, and `frag` +/// with its samplers and uniform buffers, over one vertex buffer of +/// `input` (none: the post chain's triangle over the whole frame). +pub fn makePipeline( + device: *c.SDL_GPUDevice, + color_format: c.SDL_GPUTextureFormat, + vert: []const u8, + frag: []const u8, + samplers: u32, + uniforms: u32, + input: ?VertexInput, + blend: c.SDL_GPUColorTargetBlendState, +) !*c.SDL_GPUGraphicsPipeline { + const vs = try makeShader(device, vert, c.SDL_GPU_SHADERSTAGE_VERTEX, 0, 0); + defer c.SDL_ReleaseGPUShader(device, vs); + const fs = try makeShader(device, frag, c.SDL_GPU_SHADERSTAGE_FRAGMENT, samplers, uniforms); + defer c.SDL_ReleaseGPUShader(device, fs); + var col_desc = c.SDL_GPUColorTargetDescription{ .format = color_format, .blend_state = blend }; + var vbuf_desc: c.SDL_GPUVertexBufferDescription = undefined; + var info = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo); + info.vertex_shader = vs; + info.fragment_shader = fs; + info.primitive_type = c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; + if (input) |in| { + vbuf_desc = .{ .slot = 0, .pitch = in.pitch, .input_rate = in.rate, .instance_step_rate = 0 }; + info.vertex_input_state = .{ + .vertex_buffer_descriptions = &vbuf_desc, + .num_vertex_buffers = 1, + .vertex_attributes = in.attrs.ptr, + .num_vertex_attributes = @intCast(in.attrs.len), + }; + } + info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL; + info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE; + info.multisample_state.sample_count = c.SDL_GPU_SAMPLECOUNT_1; + info.target_info = .{ .color_target_descriptions = &col_desc, .num_color_targets = 1 }; + return c.SDL_CreateGPUGraphicsPipeline(device, &info) orelse error.GpuCreate; +} + +fn backgroundLayerBlend() c.SDL_GPUColorTargetBlendState { + var blend = std.mem.zeroes(c.SDL_GPUColorTargetBlendState); + blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_SRC_ALPHA; + blend.dst_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; + blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD; + blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR; + blend.dst_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; + blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD; + blend.enable_blend = true; + return blend; +} + +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; + info.code_size = code.len; + info.entrypoint = "main"; + info.format = c.SDL_GPU_SHADERFORMAT_SPIRV; + info.stage = stage; + info.num_samplers = n_samplers; + info.num_uniform_buffers = n_uniform_buffers; + return c.SDL_CreateGPUShader(device, &info) orelse error.GpuCreate; +} + +/// A 2D texture of one level, one layer and one sample. +pub fn texture2d(device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, width: u32, height: u32) ?*c.SDL_GPUTexture { + var info = std.mem.zeroes(c.SDL_GPUTextureCreateInfo); + info.type = c.SDL_GPU_TEXTURETYPE_2D; + info.format = format; + info.usage = usage; + info.width = width; + info.height = height; + info.layer_count_or_depth = 1; + info.num_levels = 1; + info.sample_count = c.SDL_GPU_SAMPLECOUNT_1; + return c.SDL_CreateGPUTexture(device, &info); +} + +fn ensureCaptureTexture(g: *Gui, width: u32, height: u32) !void { + if (g.capture_tex != null and g.capture_tex_w == width and g.capture_tex_h == height) return; + const next = texture2d(g.device, g.swapchain_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, width, height) orelse return error.GpuCreate; + if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture); + g.capture_tex = next; + g.capture_tex_w = width; + g.capture_tex_h = height; +} + +fn softTargetFormat(device: *c.SDL_GPUDevice) c.SDL_GPUTextureFormat { + const candidates = [_]c.SDL_GPUTextureFormat{ + c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, + c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, + }; + for (candidates) |format| { + if (c.SDL_GPUTextureSupportsFormat( + device, + format, + c.SDL_GPU_TEXTURETYPE_2D, + c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER, + )) return format; + } + return c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM; +} + +fn softPixelFormat(format: c.SDL_GPUTextureFormat) ?c.SDL_PixelFormat { + return switch (format) { + c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, + c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB, + => c.SDL_PIXELFORMAT_ARGB8888, + c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, + c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB, + => c.SDL_PIXELFORMAT_ABGR8888, + else => null, + }; +} + +fn ensureSoftTexture(g: *Gui, width: u32, height: u32) !*c.SDL_Texture { + if (g.soft_texture) |texture| { + if (g.soft_tex_w == width and g.soft_tex_h == height) return texture; + c.SDL_DestroyTexture(texture); + g.soft_texture = null; + } + const renderer = g.soft_renderer orelse return error.GpuCreate; + const pixel_format = softPixelFormat(g.swapchain_format) orelse return error.UnsupportedCaptureFormat; + const next = c.SDL_CreateTexture( + renderer, + pixel_format, + c.SDL_TEXTUREACCESS_STREAMING, + @intCast(width), + @intCast(height), + ) orelse return error.GpuCreate; + _ = c.SDL_SetTextureScaleMode(next, c.SDL_SCALEMODE_NEAREST); + _ = c.SDL_SetTextureBlendMode(next, c.SDL_BLENDMODE_NONE); + g.soft_texture = next; + g.soft_tex_w = width; + g.soft_tex_h = height; + return next; +} + +/// The frame in `target`, `size` bytes, copied down into `capture_xfer` +/// (grown to it first) by `cmd`, which the caller submits and waits for. +/// With no buffer to be had the command buffer is submitted as it is. +fn downloadTarget(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32, size: u32) !*c.SDL_GPUTransferBuffer { + if (g.capture_xfer == null or g.capture_xfer_size < size) { + var info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = size, .props = 0 }; + const next = c.SDL_CreateGPUTransferBuffer(g.device, &info) orelse { + _ = c.SDL_SubmitGPUCommandBuffer(cmd); + return error.GpuCreate; + }; + if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer); + g.capture_xfer = next; + g.capture_xfer_size = size; + } + const xfer = g.capture_xfer.?; + const copy = c.SDL_BeginGPUCopyPass(cmd); + const src = c.SDL_GPUTextureRegion{ .texture = target, .mip_level = 0, .layer = 0, .x = 0, .y = 0, .z = 0, .w = sw, .h = sh, .d = 1 }; + const dst = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = xfer, .offset = 0, .pixels_per_row = sw, .rows_per_layer = sh }; + c.SDL_DownloadFromGPUTexture(copy, &src, &dst); + c.SDL_EndGPUCopyPass(copy); + return xfer; +} + +fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void { + const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format); + const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1); + if (size == 0 or bpp != 4) { + _ = c.SDL_SubmitGPUCommandBuffer(cmd); + return error.UnsupportedCaptureFormat; + } + const xfer = try downloadTarget(g, cmd, target, sw, sh, size); + + const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; + defer c.SDL_ReleaseGPUFence(g.device, fence); + var fences = [_]*c.SDL_GPUFence{fence}; + const probe_wait = monoNs(); + if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit; + if (frame_probe) |probe| probe.zone(.gui_wait, probe_wait); + + const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap; + defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer); + + const texture = try ensureSoftTexture(g, sw, sh); + const renderer = g.soft_renderer orelse return error.GpuCreate; + const probe_upload = monoNs(); + defer if (frame_probe) |probe| probe.zone(.gui_upload, probe_upload); + if (!c.SDL_UpdateTexture(texture, null, mapped, @intCast(sw * bpp))) return error.GpuMap; + // PARDES_FRAMES_CAPTURE: every presented frame's pixels as they went + // out, and when, for a recording at the frames' own times. One write a + // frame; nothing else. + if (frame_capture_dir) |dir| captureSeries(dir, @as([*]const u8, @ptrCast(mapped))[0..size], sw, sh); + // The cell shader already produced premultiplied backgrounds with opaque + // foreground ink. Copy that alpha unchanged; never modulate the full frame. + _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE); + _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.surface_opacity) 0 else 255); + _ = c.SDL_RenderClear(renderer); + _ = c.SDL_RenderTexture(renderer, texture, null, null); + const probe_flip = monoNs(); + _ = c.SDL_RenderPresent(renderer); + if (frame_probe) |probe| probe.zone(.gui_flip, probe_flip); +} + +fn backgroundOpacity(percent: u8) f32 { + std.debug.assert(percent <= 100); + return @as(f32, @floatFromInt(percent)) / 100; +} + +/// 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 - +/// start is the frame's CPU cost). Nothing is written without it. +var latency_fd: c_int = -1; +var frame_started_ns: u64 = 0; + +fn monoNs() u64 { + var ts: libc.timespec = undefined; + if (libc.clock_gettime(.MONOTONIC, &ts) != 0) return 0; + return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); +} + +fn latencyNote(comptime fmt: []const u8, args: anytype) void { + if (latency_fd < 0) return; + var buf: [64]u8 = undefined; + const line = std.fmt.bufPrint(&buf, fmt, args) catch return; + _ = libc.write(latency_fd, line.ptr, line.len); +} + +/// Writes the frame to latest.ppm in the capture directory, and in a +/// series to frame-.ppm too. +fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void { + const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1); + if (size == 0) { + _ = c.SDL_SubmitGPUCommandBuffer(cmd); + return error.UnsupportedCaptureFormat; + } + const xfer = try downloadTarget(g, cmd, target, sw, sh, size); + + const submit_ns = monoNs(); + const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; + defer c.SDL_ReleaseGPUFence(g.device, fence); + var fences = [_]*c.SDL_GPUFence{fence}; + if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit; + latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, monoNs(), submit_ns }); + + const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap; + defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer); + const pixels: [*]const u8 = @ptrCast(mapped); + try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, "latest"); + var name: [24]u8 = undefined; + // unreachable below: "frame-" and a u32 fit 24 + if (g.capture_series) try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable); + g.captured +%= 1; +} + +/// A test window's state for a harness (test/process/window.zig), in the +/// capture directory's `status`: " ". +/// Idle is 1 once the frame last captured is the one that stays: nothing +/// owes a frame, nothing moves, nothing waits on a clock. A harness that +/// sees a step past the one it acted on, idle, has its frame, however slow +/// the machine is. +var test_status_step: u64 = 0; +fn writeTestStatus(g: *const Gui, core: *const pardes.Pardes, presented: bool) void { + test_status_step +%= 1; + if (g.capture_dir.len == 0) return; + const idle = presented and !core.needs_frame and !frontendMoving(g) and core.nextWake() == null and + !g.glide.moving() and g.scroll_lag == 0 and g.scroll_delta == 0 and g.scroll_notch == 0; + var line_buf: [64]u8 = undefined; + // What keeps it busy, after: owes a frame, moves, waits, not shown. + const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}{d}{d}{d}\n", .{ test_status_step, g.captured, @intFromBool(idle), @intFromBool(core.needs_frame), @intFromBool(frontendMoving(g)), @intFromBool(core.nextWake() != null), @intFromBool(!presented) }) catch unreachable; // seven numbers fit 64 + var tmp_buf: [4096]u8 = undefined; + var final_buf: [4096]u8 = undefined; + const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/status.tmp", .{g.capture_dir}, 0) catch return; + const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/status", .{g.capture_dir}, 0) catch return; + const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return; + _ = libc.write(fd, line.ptr, line.len); + _ = libc.close(fd); + _ = libc.rename(tmp_path, final_path); +} + +fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8) !void { + // A latency trace times frames, and an 8 MB file write per frame would + // stall the loop it is timing. + if (g.capture_dir.len == 0 or latency_fd >= 0) return; + const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format); + if (bpp != 4) return error.UnsupportedCaptureFormat; + const bgr = switch (g.swapchain_format) { + c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB => false, + c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB => true, + else => return error.UnsupportedCaptureFormat, }; - pane.file.?.revision = pane.file.?.saved_revision; + + var tmp_buf: [4096]u8 = undefined; + var final_buf: [4096]u8 = undefined; + const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.ppm.tmp", .{ g.capture_dir, name }, 0) catch return error.CapturePathTooLong; + const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.ppm", .{ g.capture_dir, name }, 0) catch return error.CapturePathTooLong; + + const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return error.CaptureWriteFailed; + defer _ = libc.close(fd); + + var header: [64]u8 = undefined; + const hdr = std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch unreachable; // two u32s fit 64 + _ = host_io.writeFd(fd, hdr); + + const row_rgb = try gpa.alloc(u8, @as(usize, width) * 3); + defer gpa.free(row_rgb); + for (0..height) |row| { + const src = pixels[row * width * 4 ..][0 .. @as(usize, width) * 4]; + for (0..width) |x| { + const si = x * 4; + const di = x * 3; + row_rgb[di + 0] = src[si + if (bgr) @as(usize, 2) else 0]; + row_rgb[di + 1] = src[si + 1]; + row_rgb[di + 2] = src[si + if (bgr) @as(usize, 0) else 2]; + } + _ = host_io.writeFd(fd, row_rgb); + } + if (libc.rename(tmp_path, final_path) != 0) return error.CaptureWriteFailed; +} + +/// One flat, hard-edged rectangle of decor, in window pixels: clipped to the +/// window and dropped when empty, as the triangle overlay drew it. +fn addDecor(g: *Gui, gpa: std.mem.Allocator, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, rgb: [3]u8, alpha: f32, win_w: f32, win_h: f32) !void { + const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, win_w); + const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, win_w); + const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, win_h); + const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, win_h); + if (x1 <= x0 or y1 <= y0) return; + // decor.frag.glsl reads the colour from the ground and the coverage + // from the ink's red. + try g.decor.append(gpa, .{ + .x0 = (x0 / win_w) * 2.0 - 1.0, + .y0 = 1.0 - (y0 / win_h) * 2.0, + .x1 = (x1 / win_w) * 2.0 - 1.0, + .y1 = 1.0 - (y1 / win_h) * 2.0, + .u0 = 0, + .v0 = 0, + .u1 = 0, + .v1 = 0, + .fr = alpha, + .fg = 0, + .fb = 0, + .br = @as(f32, @floatFromInt(rgb[0])) / 255.0, + .bg = @as(f32, @floatFromInt(rgb[1])) / 255.0, + .bb = @as(f32, @floatFromInt(rgb[2])) / 255.0, + }); +} + +/// A body region in window pixels. +fn bodyPixels(region: pardes.Region, layout: CellLayout) [4]f32 { + return .{ + @as(f32, @floatFromInt(region.rect.x)) * layout.w, + @as(f32, @floatFromInt(region.rect.y)) * layout.h, + @as(f32, @floatFromInt(region.rect.x + region.rect.w)) * layout.w, + @as(f32, @floatFromInt(region.rect.y + region.rect.h)) * layout.h, + }; +} + +/// The frame's decor, group by group (docs/render-pipeline.md), all of it +/// read from the regions and the palette: the page's rules and the panes' +/// rails, rules and grip marks with the page, notice rules with the +/// notices, bar cursors with the ink. +fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, groups: *Groups, layout: CellLayout, win_w: f32, win_h: f32, cursors_shown: bool) !void { + g.decor.clearRetainingCapacity(); + const chrome = &surface.chrome; + const regions = surface.regionList(); + for (groups.items[0..groups.len], 0..) |*group, index| { + group.decor_start = @intCast(g.decor.items.len); + defer group.decor_count = @as(u32, @intCast(g.decor.items.len)) - group.decor_start; + if (index == 0) { + // The grips' buttons before any rule: the rules over their rows + // cut them, and the band round them never covers a rule. + try gripDecor(g, gpa, regions, surface.cells, chrome, layout, surface.cols, surface.rows, win_w, win_h); + const top = for (regions) |region| { + if (region.kind == .workspace_tag) break region.rect.h; + } else 0; + // The workspace tag is ruled off from the tags right under it. + const tag_under = for (regions) |region| switch (region.kind) { + .grip, .tag, .column_grip, .column_tag => if (region.rect.y == top) break true, + else => {}, + } else false; + // As wide as the other rules, where the tagline leaves the room. + const height: u32 = @intFromFloat(@max(1, @min(rulePx(chrome), @as(f32, @floatFromInt((g.cell_h -| g.tagline_height) * 2))))); + if (top != 0 and top < surface.rows and tag_under and height != 0) { + const y0: f32 = @floatFromInt(top * g.cell_h - height / 2); + try addDecor(g, gpa, 0, y0, win_w, y0 + @as(f32, @floatFromInt(height)), chrome.topbar_rule, 1, win_w, win_h); + } + // The column bar is ruled off from the panes under it. + for (regions) |bar| { + if (bar.kind != .column_grip) continue; + const y = @as(f32, @floatFromInt(bar.rect.y + bar.rect.h)) * layout.h; + try addDecor(g, gpa, 0, y - rulePx(chrome), win_w, y, chrome.border, 1, win_w, win_h); + break; + } + // A tag on the last row runs on through the pixels under the grid. + const grid_bottom = @as(f32, @floatFromInt(surface.rows)) * layout.h; + const tag_last = for (regions) |region| switch (region.kind) { + .grip, .tag, .column_grip, .column_tag, .workspace_tag => if (region.rect.h != 0 and region.rect.y + region.rect.h == surface.rows) break true, + else => {}, + } else false; + if (grid_bottom < win_h and tag_last) try addDecor(g, gpa, 0, grid_bottom, win_w, win_h, chrome.tag_bg, 1, win_w, win_h); + try paneDecor(g, gpa, regions, surface.rail_ticks[0..surface.nrail_ticks], chrome, layout, surface.cols, surface.rows, win_w, win_h); + // A single spine runs down each column, through every tag and body. + for (regions) |column| { + if (column.kind != .column) continue; + const x = @as(f32, @floatFromInt(column.rect.x)) * layout.w; + const y0 = @as(f32, @floatFromInt(column.rect.y)) * layout.h; + const grid_y1 = @as(f32, @floatFromInt(surface.rows)) * layout.h; + const y1 = if (win_h - grid_y1 < layout.h) @max(grid_y1, win_h) else grid_y1; + // None at the window's edge: nothing to rule apart there. + if (column.rect.x == 0) continue; + if (y1 > y0) try addDecor(g, gpa, x, y0, x + rulePx(chrome), y1, chrome.border, 1, win_w, win_h); + } + } + // A notice chip is tagline hung over the body's top rows, so it is + // ruled off from the text beneath it the way a tag is: the same + // colour and thickness along its bottom, running to the window's + // edge when it does. + if (index == groups.notices) for (surface.tagLayers()) |*layer| { + if (layer.rows == 0 or layer.kind != .notice) continue; + const x0 = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; + const x1 = x0 + @as(f32, @floatFromInt(layer.viewport.w)) * layout.w; + const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; + const top = @as(f32, @floatFromInt(layer.viewport.y)) * layout.h; + const rule_y = top + layout.h; + try addDecor(g, gpa, x0, rule_y - dp(1), rule_x1, rule_y, chrome.border, 1, win_w, win_h); + }; + if (index == groups.ink and cursors_shown) try cursorDecor(g, gpa, surface, layout, win_w, win_h); + } } -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); +/// Each pane's rule between its tag and body, and its scroll rail: a page +/// coloured gutter with a thin track and its thumb, running down through the +/// pixels past the last whole row. +fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ticks: []const pardes.RailTick, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { + const page = chrome.page orelse bg_default; + for (regions) |rail| { + if (rail.kind != .rail or rail.rect.h == 0) continue; + const tag = for (regions) |region| { + if (region.kind == .tag and region.owner == rail.owner) break region; + } else continue; + if (@as(u32, tag.rect.x) + tag.rect.w > cols or @as(u32, tag.rect.y) + tag.rect.h > rows or + @as(u32, rail.rect.y) + rail.rect.h > rows) continue; + const x0 = @as(f32, @floatFromInt(rail.rect.x)) * layout.w; + const x1 = @as(f32, @floatFromInt(tag.rect.x + tag.rect.w)) * layout.w; + // Like the band above it, the rule of a pane at the right edge runs + // on through the pixels past the last whole cell. Under a tag on + // top, over one below its body. + const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; + const tag_bottom = tag.rect.y > rail.rect.y; + const rule_y = @as(f32, @floatFromInt(if (tag_bottom) tag.rect.y else tag.rect.y + tag.rect.h)) * layout.h; + try addDecor(g, gpa, x0, if (tag_bottom) rule_y else rule_y - dp(1), rule_x1, if (tag_bottom) rule_y + dp(1) else rule_y, chrome.tag_rule orelse mixRgb(chrome.tag_bg, page), 1, win_w, win_h); + // Stacked panes are ruled apart as columns are, where one pane's + // body meets the next one's tag (acme's Border). + { + const pane_top = @min(tag.rect.y, rail.rect.y); + const stacked = for (regions) |other| { + if ((other.kind == .body or other.kind == .tag) and other.owner != rail.owner and other.rect.y + other.rect.h == pane_top and + other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; + } else false; + // Inside the tag band's slack, never over its glyphs: the top + // slack of a tag on top, the bottom slack of the one above when + // tags are at the bottom; a pixel at least. + const y = @as(f32, @floatFromInt(pane_top)) * layout.h; + const spare = g.cell_h -| g.tagline_height; + if (stacked and !tag_bottom) { + const room = taglineBandOffset(pane_top, win_h, g.cell_h, g.tagline_height); + try addDecor(g, gpa, x0, y, rule_x1, y + @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), chrome.border, 1, win_w, win_h); + } else if (stacked and pane_top > 0) { + const room = spare - taglineBandOffset(pane_top - 1, win_h, g.cell_h, g.tagline_height); + try addDecor(g, gpa, x0, y - @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), rule_x1, y, chrome.border, 1, win_w, win_h); + } + } + + const y0 = @as(f32, @floatFromInt(rail.rect.y)) * layout.h; + const body_end = rail.rect.y + rail.rect.h; + const body_y1 = @as(f32, @floatFromInt(body_end)) * layout.h; + const y1 = if (body_end == rows and win_h - body_y1 < layout.h) @max(body_y1, win_h) else body_y1; + // A theme's own track fills its width, the thumb one pixel short + // of it so the track edges it (acme's scrollbar); else a thin rail. + // acme's scrollbar: the track fills the scroll column, under the + // grip's button; the thumb is a pixel short of its right edge, so + // the track edges it. + const column = scrollColumn(g, chrome, rail.rect.x, layout); + try addDecor(g, gpa, x0, y0, x0 + layout.w, y1, page, 1, win_w, win_h); + try addDecor(g, gpa, column[0], y0, column[1], y1, chrome.scroll_track, 1, win_w, win_h); + if (rail.thumb_h != 0 and rail.thumb_span > 0) { + // In pixels, not rows, and with the picture while it glides + // or lags behind the core's rows (both in rows of the body). + const lag: f32 = if (g.glide.follow.offset != 0 and g.glide.pane == rail.owner) + g.glide.lagLines() + else if (g.scroll_pane != null and g.scroll_pane.? == rail.owner) g.scroll_lag else 0; + const track_px = body_y1 - y0; + const size = @min(track_px, @max(layout.h, rail.thumb_span * track_px)); + const at = rail.thumb_at + lag * rail.thumb_span / @as(f32, @floatFromInt(rail.rect.h)); + const thumb_y0 = y0 + std.math.clamp(at * track_px, 0, track_px - size); + const thumb_y1 = if (thumb_y0 + size >= body_y1 - 0.5) y1 else thumb_y0 + size; + try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); + } else if (rail.thumb_h != 0) { + const thumb_y0 = @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y)) * layout.h; + const thumb_y1 = if (rail.thumb_y + rail.thumb_h == rail.rect.h) y1 else @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y + rail.thumb_h)) * layout.h; + try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); + } + // A query's places' ticks over the track and thumb, where its matches + // are in the file (Places.addTicks); the current one last, on top. + const track_px = body_y1 - y0; + for (0..2) |pass| for (ticks) |tick| { + if (tick.owner != rail.owner or tick.current != (pass == 1)) continue; + const at = @as(f32, @floatFromInt(tick.at)) / @as(f32, @floatFromInt(pardes.panes.Places.tick_scale)); + const h = if (tick.current) dp(3) else dp(2); + const ty = y0 + std.math.clamp(at * track_px, 0, track_px - h); + try addDecor(g, gpa, column[0], ty, column[1], ty + h, if (tick.current) chrome.match_current else chrome.match_tick, 1, win_w, win_h); + }; } - // 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, - idx: u32, - col: u16, - row: u16, - layout: CellLayout, - win_w: f32, - win_h: f32, - role: pardes.FontRole, - line: []const pardes.Cell, - at: usize, - cursor: ?usize, - is_cursor: bool, - page: [3]u8, -) void { - const resolved = resolveCell(g, line, at, cursor, role, is_cursor, page); - - const px0 = layout.x_off + @as(f32, @floatFromInt(col)) * layout.w; - const visual_h: f32 = if (resolved.role == .tagline) - @floatFromInt(g.tagline_height) - else - layout.h; - const band_offset: f32 = if (resolved.role == .tagline) - @floatFromInt(taglineBandOffset(row, win_h, g.cell_h, g.tagline_height)) - else - 0; - const py0 = layout.y_off + @as(f32, @floatFromInt(row)) * layout.h + band_offset; - const x0 = (px0 / win_w) * 2.0 - 1.0; - const x1 = ((px0 + layout.w) / win_w) * 2.0 - 1.0; - const y0 = 1.0 - (py0 / win_h) * 2.0; - const y1 = 1.0 - ((py0 + visual_h) / win_h) * 2.0; - const aw_f: f32 = @floatFromInt(atlas_w); - const ah_f: f32 = @floatFromInt(atlas_h); - const uv_w: u32 = if (resolved.role == .tagline) g.tagline_width else g.cell_w; - const uv_h: u32 = if (resolved.role == .tagline) g.tagline_height else g.cell_h; +/// Halfway between two colours. +const mixRgb = pardes.colors.mix; - instances[idx] = .{ - .x0 = x0, - .y0 = y0, - .x1 = x1, - .y1 = y1, - .u0 = @as(f32, @floatFromInt(resolved.slot.u)) / aw_f, - .v0 = @as(f32, @floatFromInt(resolved.slot.v)) / ah_f, - .u1 = @as(f32, @floatFromInt(resolved.slot.u + uv_w)) / aw_f, - .v1 = @as(f32, @floatFromInt(resolved.slot.v + uv_h)) / ah_f, - .fr = @as(f32, @floatFromInt(resolved.fg[0])) / 255.0, - .fg = @as(f32, @floatFromInt(resolved.fg[1])) / 255.0, - .fb = @as(f32, @floatFromInt(resolved.fg[2])) / 255.0, - .br = @as(f32, @floatFromInt(resolved.bg[0])) / 255.0, - .bg = @as(f32, @floatFromInt(resolved.bg[1])) / 255.0, - .bb = @as(f32, @floatFromInt(resolved.bg[2])) / 255.0, - }; - // A block cursor is foreground UI ink, even though its color is carried - // in the reversed cell background. Keep it visible at WindowOpacity 0. - if (is_cursor) instances[idx].effect |= opaque_bg_bit; +/// A rule's width: the theme's own, or one pixel. +fn rulePx(chrome: *const pardes.Chrome) f32 { + return dp(@floatFromInt(@max(1, chrome.rule_px))); } -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); +/// The display's density (SDL's window display scale: 2 on a 2x screen), +/// by which every size given in logical pixels is drawn, as acme scales its +/// Border, ButtonBorder and Scrollgap (scalesize). Cells, glyphs and what is +/// measured in them are already the display's pixels and are not scaled. +/// One per process, as its window is. +var display_scale: f32 = 1; + +/// The window's display scale, or PARDES_TEST_SCALE (a harness forcing 2x); +/// a test window is 1x unless forced, whatever display it lands on, so its +/// captures are the same on any machine. +fn updateDisplayScale(window: *c.SDL_Window) void { + if (std.c.getenv("PARDES_TEST_SCALE")) |forced| { + display_scale = std.fmt.parseFloat(f32, std.mem.span(forced)) catch 1; + } else if (std.c.getenv("PARDES_TEST") != null) { + display_scale = 1; + } else { + const scale = c.SDL_GetWindowDisplayScale(window); + display_scale = if (scale > 0 and std.math.isFinite(scale)) scale else 1; } + display_scale = std.math.clamp(display_scale, 1, 4); } -fn cellCodepoint(cell: *const pardes.Cell) u32 { - const grapheme = cell.grapheme(); - return if (cell.default or grapheme.len == 0) ' ' else firstCp(grapheme); -} +/// InactiveDim: the unfocused panes' text faded toward its ground by the +/// setting's percent, never below the pair's own contrast or 4.5, whichever +/// is lower. The window's alone, from the regions' focus: renderFrame +/// begins it each frame. ponytail: one window per process, as display_scale. +var dim: Dim = .{}; -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)); +const Dim = struct { + amount: f32 = 0, + /// The pane with the keyboard, from its regions. + focused: u16 = pardes.Region.none, + /// The few ink and paper pairs a frame has, each faded once. + keys: [32]?[6]u8 = @splat(null), + values: [32][3]u8 = undefined, - // 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 begin(d: *Dim, percent: u8, regions: []const pardes.Region) void { + d.* = .{ .amount = @as(f32, @floatFromInt(@min(percent, 100))) / 100 }; + for (regions) |region| if (region.active and (region.kind == .grip or region.kind == .tag or region.kind == .body)) { + d.focused = region.owner; + break; + }; + if (d.focused == pardes.Region.none) d.amount = 0; + } -fn palColor(idx: u8) [3]u8 { - const p = ghostty_vt.color.default[idx]; - return .{ p.r, p.g, p.b }; -} + /// Whether pane `owner`'s text fades this frame. + fn of(d: *const Dim, owner: u16) bool { + return d.amount > 0 and owner != d.focused; + } -fn firstCp(s: []const u8) u32 { - if (s.len == 0) return ' '; - const n = std.unicode.utf8ByteSequenceLength(s[0]) catch return ' '; - if (n > s.len) return ' '; - return std.unicode.utf8Decode(s[0..n]) catch ' '; -} + /// A cell instance's ink faded toward its ground. + fn fade(d: *Dim, instance: *CellInstance) void { + const ink = d.faded(byteRgb(.{ instance.fr, instance.fg, instance.fb }), byteRgb(.{ instance.br, instance.bg, instance.bb })); + instance.fr = @as(f32, @floatFromInt(ink[0])) / 255.0; + instance.fg = @as(f32, @floatFromInt(ink[1])) / 255.0; + instance.fb = @as(f32, @floatFromInt(ink[2])) / 255.0; + } -fn refitFont(g: *Gui, core: ?*pardes.Pardes) void { - var cw: c_int = 10; - var chh: c_int = 20; - var asc: c_int = 16; - c.ui_font_cell_metrics(g.font, g.px, &cw, &chh, &asc); - g.cell_w = @intCast(@max(cw, 1)); - g.cell_h = @intCast(@max(chh, 1)); - g.ascent = @intCast(@max(asc, 1)); - const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, g.tagline_percent); - g.tagline_px = tagline.px; - g.tagline_width = tagline.width; - g.tagline_baseline = tagline.baseline; - g.tagline_height = tagline.height; + fn faded(d: *Dim, ink: [3]u8, paper: [3]u8) [3]u8 { + const key = ink ++ paper; + const slot = (@as(usize, ink[0]) *% 31 +% @as(usize, ink[1]) *% 7 +% ink[2] +% @as(usize, paper[0]) *% 13 +% @as(usize, paper[1]) *% 3 +% paper[2]) % d.keys.len; + if (d.keys[slot]) |held| if (std.mem.eql(u8, &held, &key)) return d.values[slot]; + // Contrast falls as the ink nears its paper: the most of `amount` + // that keeps the pair at its own contrast or 4.5, whichever is lower. + const floor = @min(pardes.colors.contrast(ink, paper), 4.5); + var t = d.amount; + if (pardes.colors.contrast(blendLinear(ink, paper, t), paper) < floor) { + var lo: f32 = 0; + var hi: f32 = t; + for (0..8) |_| { + const mid = (lo + hi) / 2; + if (pardes.colors.contrast(blendLinear(ink, paper, mid), paper) >= floor) lo = mid else hi = mid; + } + t = lo; + } + d.keys[slot] = key; + d.values[slot] = blendLinear(ink, paper, t); + return d.values[slot]; + } + + fn byteRgb(rgb: [3]f32) [3]u8 { + var out: [3]u8 = undefined; + for (&out, rgb) |*o, v| o.* = @intFromFloat(@round(std.math.clamp(v, 0, 1) * 255)); + return out; + } +}; - resetGlyphAtlas(g); +/// `t` of the way from one colour to the other in linear light, so a +/// coloured ink does not muddy on its way to the paper. +fn blendLinear(from: [3]u8, to: [3]u8, t: f32) [3]u8 { + var out: [3]u8 = undefined; + for (&out, from, to) |*o, a, b| { + const l = pardes.colors.to_linear[a] * (1 - t) + pardes.colors.to_linear[b] * t; + o.* = encoded[@intFromFloat(@round(std.math.clamp(l, 0, 1) * (encoded.len - 1)))]; + } + return out; +} - if (core) |p| { - const geom = windowCells(g); - _ = updateCoreResize(p, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); +/// Linear light back to an sRGB channel, in 4096 steps. +const encoded: [4096]u8 = blk: { + @setEvalBranchQuota(1_000_000); + var table: [4096]u8 = undefined; + for (&table, 0..) |*out, i| { + const l = @as(f64, @floatFromInt(i)) / 4095; + const v = if (l <= 0.0031308) l * 12.92 else 1.055 * std.math.pow(f64, l, 1.0 / 2.4) - 0.055; + out.* = @intFromFloat(@round(v * 255)); } + break :blk table; +}; - resetScroll(g); +/// 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)); } -// The first cell of the cleared atlas stays blank: the space slot. -fn resetGlyphAtlas(g: *Gui) void { - g.glyphs.clearRetainingCapacity(); - g.words.clear(); - @memset(g.atlas_stage, 0); - g.space_slot = .{ .u = 0, .v = 0 }; - g.pen_x = g.cell_w; - g.pen_y = 0; - g.atlas_dirty_top = 0; - g.atlas_dirty_bottom = atlas_h; +/// The two short bars on each row of a grip with no mode glyph there, +/// centered in its anchor. +fn gripDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, cells: []const pardes.Cell, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { + if (g.tagline_height < 6 or g.tagline_width < 3) return; + for (regions) |grip| { + if (grip.kind != .grip and grip.kind != .column_grip) continue; + if (grip.rect.h == 0 or grip.rect.y >= rows) continue; + const button = gripButton(g, chrome, grip.rect.x, grip.rect.y, layout); + // Round the button, its first row is the tag's band: nothing of the + // cells under it shows there. + const band = if (grip.active) chrome.tag_focus_bg else chrome.tag_bg; + const left = @as(f32, @floatFromInt(grip.rect.x)) * layout.w; + const right = @as(f32, @floatFromInt(grip.rect.x + grip.rect.w)) * layout.w; + try addDecor(g, gpa, left, button[1], button[0], button[3], band, 1, win_w, win_h); + try addDecor(g, gpa, button[2], button[1], right, button[3], band, 1, win_w, win_h); + if (grip.kind != .grip) continue; + // acme's button ring, two pixels (ButtonBorder) inside the button: + // the focused one's in its own fill. An unfocused dirty one keeps a + // pixel of band inside its ring, so the four states differ in shape + // whatever a theme's colours (a focused dirty one is acme's + // modbutton, filled up to its ring). + { + // The rules drawn over the row (paneDecor, after this) cut into + // it: the ring runs inside them, from rule to rule. + const tag = for (regions) |part| { + if (part.kind == .tag and part.owner == grip.owner) break part; + } else grip; + const tag_bottom = for (regions) |part| { + if (part.kind == .rail and part.owner == grip.owner) break part.rect.y < tag.rect.y; + } else false; + const stacked = !tag_bottom and for (regions) |other| { + if ((other.kind == .body or other.kind == .tag) and other.owner != grip.owner and other.rect.y + other.rect.h == grip.rect.y and + other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; + } else false; + const top_rule: f32 = if (tag_bottom) dp(1) else if (stacked) @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(taglineBandOffset(grip.rect.y, win_h, g.cell_h, g.tagline_height))))) else 0; + const bottom_rule: f32 = if (!tag_bottom and grip.rect.h == 1) dp(1) else 0; + const x0 = button[0]; + const x1 = button[2]; + const y0 = button[1] + top_rule; + const y1 = button[3] - bottom_rule; + const ring = if (grip.active) chrome.grip_focus_ring else chrome.grip_border; + // acme's ButtonBorder: two logical pixels. + const b = dp(2); + try addDecor(g, gpa, x0, y0, x1, y0 + b, ring, 1, win_w, win_h); + try addDecor(g, gpa, x0, y1 - b, x1, y1, ring, 1, win_w, win_h); + try addDecor(g, gpa, x0, y0 + b, x0 + b, y1 - b, ring, 1, win_w, win_h); + try addDecor(g, gpa, x1 - b, y0 + b, x1, y1 - b, ring, 1, win_w, win_h); + if (grip.dirty and !grip.active) { + const gap = b + dp(1); + try addDecor(g, gpa, x0 + b, y0 + b, x1 - b, y0 + gap, band, 1, win_w, win_h); + try addDecor(g, gpa, x0 + b, y1 - gap, x1 - b, y1 - b, band, 1, win_w, win_h); + try addDecor(g, gpa, x0 + b, y0 + gap, x0 + gap, y1 - gap, band, 1, win_w, win_h); + try addDecor(g, gpa, x1 - gap, y0 + gap, x1 - b, y1 - gap, band, 1, win_w, win_h); + } + } + // The marks are the first row's alone, where its cell is blank (no + // mode glyph), centered in the button, in its ink from the region's + // state. + const x = grip.rect.x; + const y = grip.rect.y; + if (x >= cols) continue; + const cell = &cells[@as(usize, y) * cols + x]; + if (cell.default or cell.printableAscii() != ' ') continue; + const rgb = inkOn(gripFill(chrome, grip.active, grip.dirty)); + const center_x = @floor((button[0] + button[2]) / 2); + const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; + const half_w = @max(dp(1), @min(dp(3), @floor((button[2] - button[0] - 2 * dp(3)) / 2))); + // The mode's two bars: a logical pixel thick, a pixel either side of + // the middle. + const bar = dp(1); + try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y - bar - dp(1)), @floor(center_x + half_w), @floor(center_y - dp(1)), rgb, 1, win_w, win_h); + try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y + dp(1)), @floor(center_x + half_w), @floor(center_y + dp(1) + bar), rgb, 1, win_w, win_h); + } } -fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void { - if (!fitTaglineFont(g, core.settings.font.tagline_percent)) return; - const geom = windowCells(g); - _ = updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); +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; + +/// Where the frame draws the focused caret, its top in grid rows: from its +/// own springs (the quad's, while it moves or while a glide moves the text) +/// or its cell; carried by the text's glide when its line rode it. The probe +/// records it and the glide tests hold its invariants. +fn caretRow(g: *const Gui, surface: *const pardes.Surface, now_ns: u64) ?f32 { + const cursor = surface.cursor orelse return null; + const quad = g.caret.placed and (g.caret.moving() or g.glide.follow.offset != 0); + return if (quad) g.caret.sample(now_ns)[0][1] - caretRide(g, surface) else @floatFromInt(cursor.y); } -/// The tagline's face at `percent` of the body's: whether it changed. -fn fitTaglineFont(g: *Gui, percent: u8) bool { - if (percent == g.tagline_percent) return false; - g.tagline_percent = percent; - const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, percent); - g.tagline_px = tagline.px; - g.tagline_width = tagline.width; - g.tagline_baseline = tagline.baseline; - g.tagline_height = tagline.height; - resetGlyphAtlas(g); - return true; +/// What the caret's ease sees in the frame about to be drawn (Caret.see): +/// the focused cursor's box in cells (its own cell's, or the layer's that +/// draws it), and the focused body's pane, first line and place. +fn seeCaret(g: *Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, now_ns: u64) void { + const box: ?Caret.Box = if (surface.cursor) |cursor| box: { + var boxes: [max_cursors]CursorBox = undefined; + const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; + if (all.len == 0) break :box null; + const cx = (@as(f32, @floatFromInt(cursor.x)) + 0.5) * layout.w; + const cy = (@as(f32, @floatFromInt(cursor.y)) + 0.5) * layout.h; + var best = all[0]; + var nearest = std.math.inf(f32); + for (all) |b| { + const dx = (b.x0 + b.x1) / 2 - cx; + const dy = (b.y0 + b.y1) / 2 - cy; + if (dx * dx + dy * dy < nearest) { + nearest = dx * dx + dy * dy; + best = b; + } + } + break :box .{ .x = best.x0 / layout.w, .y = best.y0 / layout.h, .w = (best.x1 - best.x0) / layout.w, .h = (best.y1 - best.y0) / layout.h }; + } else null; + for (surface.regionList()) |region| if (region.kind == .body and region.active) + return g.caret.see(box, region.owner, region.line, region.rect.x, region.rect.y, now_ns); + g.caret.see(box, pardes.Region.none, 0, 0, 0, now_ns); } -/// What text draws, so a frame does not work it out again. `cells` is the -/// atlas slot of a codepoint no ligature can touch (`shape_slot` for one that -/// is shaped with its word); `map` is the atlas slot of every cell of a word -/// holding one, found by the word's text. Bounded: past `max_cells` word cells -/// it starts over, and the next frames look up what they show again (the -/// glyphs stay in the atlas). -const Words = struct { - cells: std.AutoHashMapUnmanaged(CellKey, Slot) = .empty, - map: std.AutoHashMapUnmanaged(u64, Word) = .empty, - /// Every word's codepoints and slots, end to end; a Word indexes both. - text: std.ArrayListUnmanaged(u32) = .empty, - slots: std.ArrayListUnmanaged(Slot) = .empty, - shaped: std.ArrayListUnmanaged(c.UIShapedCell) = .empty, - /// The word the last cell was in, so the rest of it costs a compare. It - /// is positional, so every frame forgets it: the cells change under it. - memo: Memo = .{}, +/// The caret's ease (G3), the window's own: the focused cursor's quad on +/// critically damped springs at its box's corners, in grid cells, on the +/// window's clock, from the cursor the Surface shows. A jump glides, its +/// leading corners first, bowing a little on a long one; a step eases, and +/// a stream of them (typing, a held key) keeps up; a scroll or a pane's move +/// carries it with its text; a focus change glides from where it was drawn. +/// The quad is drawn only while it moves: at rest the cells draw the cursor. +const Caret = struct { + /// Top left, top right, bottom right, bottom left; x then y. + corners: [4][2]Spring = @splat(@splat(.{})), + target: Box = .{}, + from_centre: [2]f32 = .{ 0, 0 }, + placed: bool = false, + /// When the last step (a move of a cell or less) came. + step_ns: u64 = 0, + /// The focused body as the last frame showed it: its pane, its first + /// line and its top left, to tell a scroll and a pane's move from the + /// caret's own. + seen: struct { owner: u8 = pardes.Region.none, line: i32 = 0, x: u16 = 0, y: u16 = 0 } = .{}, - const max_cells = 1 << 17; - const CellKey = packed struct(u64) { cp: u21, role: pardes.FontRole, decoration: GlyphDecoration, _: u30 = 0 }; - const shape_slot: Slot = .{ .u = std.math.maxInt(u32), .v = std.math.maxInt(u32) }; - const Word = struct { start: u32, len: u32, decoration: GlyphDecoration }; - const Memo = struct { - line: ?[*]const pardes.Cell = null, - len: usize = 0, - start: usize = 0, - end: usize = 0, - cursor: ?usize = null, - slots: usize = 0, - }; + /// The default flavour's spring, as fast again as the caret follows + /// input (it settles in 90-150 ms). + const omega: f32 = 34 * 2.4; + /// The trailing corners of a jump, a little behind the leading ones. + const follow: f32 = 0.85; + /// A step's spring, stiffer than a jump's. + const step_pace: f32 = 1.5; + /// A jump longer than this, in cells, bows, by this much of its length. + const arc_from: f32 = 8; + const arc: f32 = 0.04; + /// Steps this close are a stream: each lands. + const stream_ns: u64 = 150 * std.time.ns_per_ms; - fn clear(w: *Words) void { - w.cells.clearRetainingCapacity(); - w.map.clearRetainingCapacity(); - w.text.clearRetainingCapacity(); - w.slots.clearRetainingCapacity(); - w.memo = .{}; - } + const Box = struct { x: f32 = 0, y: f32 = 0, w: f32 = 0, h: f32 = 0 }; - fn deinit(w: *Words, gpa: std.mem.Allocator) void { - w.cells.deinit(gpa); - w.map.deinit(gpa); - w.text.deinit(gpa); - w.slots.deinit(gpa); - w.shaped.deinit(gpa); - } -}; + /// One axis on a critically damped spring, closed form: a new target + /// keeps the value and its speed; settled, it is its target. + const Spring = struct { + omega: f32 = omega, + target: f32 = 0, + from: f32 = 0, + velocity: f32 = 0, + from_ns: u64 = 0, + settled: bool = true, + + fn at(s: *const Spring, now_ns: u64) [2]f32 { + if (s.settled) return .{ s.target, 0 }; + const t: f32 = @floatCast(@as(f64, @floatFromInt(now_ns -| s.from_ns)) / std.time.ns_per_s); + const x0 = s.from - s.target; + const k = s.velocity + s.omega * x0; + const decay = @exp(-s.omega * t); + return .{ s.target + (x0 + k * t) * decay, (s.velocity - s.omega * t * k) * decay }; + } -/// What decides where a word ends, for one cell. A concealed cell is a space. -const WordCell = struct { cp: u32, decoration: GlyphDecoration, role: pardes.FontRole }; + fn value(s: *const Spring, now_ns: u64) f32 { + return s.at(now_ns)[0]; + } -fn wordCell(cell: *const pardes.Cell) WordCell { - return .{ - .cp = if (!cell.default and cell.style.invisible) ' ' else cellCodepoint(cell), - .decoration = GlyphDecoration.fromCell(cell), - .role = cellFontRole(cell), - }; -} + fn retarget(s: *Spring, target: f32, now_ns: u64, w: f32) void { + if (target == s.target) return; + const state = s.at(now_ns); + s.* = .{ .omega = w, .target = target, .from = state[0], .velocity = state[1], .from_ns = now_ns, .settled = false }; + } -/// Whether a word ends between `a`, cell `i`, and `b`, cell `i + 1`: at a -/// space, a decoration or role change, either side of the cursor (Ghostty's -/// rule: the cell being edited shows its own glyph, so a ligature under the -/// cursor comes apart), and inside f|i, f|l and s|t, whose typographic -/// ligatures do not belong on a grid (Ghostty again). Colours never end a -/// word: a ligature spans a syntax colour change or a selection edge, and each -/// cell tints its own slice. -fn wordBreak(a: WordCell, b: WordCell, i: usize, cursor: ?usize) bool { - if (a.cp == ' ' or b.cp == ' ') return true; - // A rule is drawn by hand (ruleArms), never a slice of a shaped word. - if (ruleArms(a.cp) != null or ruleArms(b.cp) != null) return true; - if (cursor) |at| if (at == i or at == i + 1) return true; - if (a.role != b.role or !std.meta.eql(a.decoration, b.decoration)) return true; - return (a.cp == 'f' and (b.cp == 'i' or b.cp == 'l')) or (a.cp == 's' and b.cp == 't'); -} + /// Settles within half a percent of a cell, barely moving; true + /// while it still moves. + fn step(s: *Spring, now_ns: u64) bool { + if (s.settled) return false; + const state = s.at(now_ns); + if (@abs(state[0] - s.target) < 5e-3 and @abs(state[1]) < 5e-2) s.settled = true; + return !s.settled; + } + }; -/// The atlas slot `line[at]` draws: blank for a plain space (or concealed -/// text), its own glyph when no ligature could replace that glyph (every -/// cell, in a font without ligatures), else its slice -/// of the word around it, shaped once and cached by the word's text. The -/// cells of a word being walked cost a compare. Taglines are not shaped: they are drawn at two pitches -/// (tagline_width in a tag layer, a whole cell in the grid), and a strip would -/// not line up in one of them. -fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: pardes.FontRole) Slot { - const words = &g.words; - const memo = words.memo; - if (memo.line == line.ptr and memo.len == line.len and memo.cursor == cursor and at >= memo.start and at < memo.end and role == .body) - return words.slots.items[memo.slots + at - memo.start]; - var here = wordCell(&line[at]); - // An underlined or struck-out space is a glyph of its own: it draws its line. - if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.space_slot; - if (ruleArms(here.cp) != null) - return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = role, .rule = true }) orelse g.space_slot; - const gpa = g.glyphs.allocator; - const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration }; - const known = words.cells.getOrPut(gpa, cell_key) catch return g.space_slot; - if (!known.found_existing) { - const drawn = glyphForCodepoint(g, here.cp); - const font = if (drawn.face == 0) g.font else g.fallbacks[drawn.face - 1].?.face; - known.value_ptr.* = if (role == .body and c.ui_font_substitutes(font, drawn.glyph) != 0) - Words.shape_slot - else - cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = role, .decoration = here.decoration }) orelse g.space_slot; + fn cornersOf(box: Box) [4][2]f32 { + return .{ .{ box.x, box.y }, .{ box.x + box.w, box.y }, .{ box.x + box.w, box.y + box.h }, .{ box.x, box.y + box.h } }; } - const plain = known.value_ptr.*; - if (!std.meta.eql(plain, Words.shape_slot)) return plain; - if (words.text.items.len > Words.max_cells) words.clear(); - var start = at; - while (start > 0) { - const before = wordCell(&line[start - 1]); - if (wordBreak(before, here, start - 1, cursor)) break; - start -= 1; - here = before; - } - // The word's text goes on the end of `text`: a new word keeps it there, - // a known one gives it back. - const text_start = words.text.items.len; - var end = start; - while (true) { - words.text.append(gpa, here.cp) catch return g.space_slot; - end += 1; - if (end == line.len) break; - const next = wordCell(&line[end]); - if (wordBreak(here, next, end - 1, cursor)) break; - here = next; + fn centre(box: Box) [2]f32 { + return .{ box.x + box.w / 2, box.y + box.h / 2 }; } - const text = words.text.items[text_start..]; - const decoration = here.decoration; - const hash = std.hash.Wyhash.hash(@as(u5, @bitCast(decoration)), std.mem.sliceAsBytes(text)); - if (words.map.get(hash)) |word| { - if (word.len == text.len and std.meta.eql(word.decoration, decoration) and - std.mem.eql(u32, words.text.items[word.start..][0..word.len], text)) - { - words.text.shrinkRetainingCapacity(text_start); - words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = word.start }; - return words.slots.items[word.start + at - start]; + + /// Heads for `box`: eased, or landed at once (`land`: a scroll moved + /// the text under it, not the caret). + fn aim(caret: *Caret, box: Box, now_ns: u64, land_it: bool) void { + if (caret.placed and std.meta.eql(box, caret.target) and !(land_it and caret.moving())) return; + const to = cornersOf(box); + const from_c = if (caret.placed) caret.centreAt(now_ns) else centre(box); + const to_c = centre(box); + const dx = to_c[0] - from_c[0]; + const dy = to_c[1] - from_c[1]; + const jump = @abs(dx) > 1.01 or @abs(dy) > 1.01; + // A step is measured mark to mark, not from where an ease under way + // has got to (a held key's steps would read as jumps from there). + const last = centre(caret.target); + const one_step = caret.placed and @abs(to_c[0] - last[0]) <= 1.01 and @abs(to_c[1] - last[1]) <= 1.01; + const streaming = one_step and caret.step_ns != 0 and now_ns -| caret.step_ns < stream_ns; + if (one_step) caret.step_ns = now_ns; + const land = !caret.placed or land_it or streaming; + caret.from_centre = from_c; + caret.target = box; + caret.placed = true; + for (&caret.corners, to) |*corner, point| { + // Leading: the corner ahead of the move, on the side it goes. + const ahead = (point[0] - to_c[0]) * dx + (point[1] - to_c[1]) * dy; + const w = if (jump) omega * (if (ahead > 0) 1 else follow) else omega * step_pace; + for (corner, point) |*axis, v| { + if (land) axis.* = .{ .omega = w, .target = v, .from = v } else axis.retarget(v, now_ns, w); + } } } - // A new word (a hash collision takes the map entry over). Runs of one - // face are shaped in that face; fallback faces shape like the primary. - const probe_shape = monoNs(); - defer if (frame_probe) |probe| { - probe.zone(.gui_shape, probe_shape); - probe.shaped +|= 1; - }; - const n = text.len; - words.slots.ensureUnusedCapacity(gpa, n) catch { - words.text.shrinkRetainingCapacity(text_start); - return g.space_slot; - }; - words.shaped.resize(gpa, n) catch { - words.text.shrinkRetainingCapacity(text_start); - return g.space_slot; - }; - const shaped = words.shaped.items; - var run_start: usize = 0; - var face = glyphForCodepoint(g, text[0]).face; - while (run_start < n) { - var run_end = run_start + 1; - var next_face = face; - while (run_end < n) : (run_end += 1) { - next_face = glyphForCodepoint(g, text[run_end]).face; - if (next_face != face) break; - } - const run_font = if (face == 0) g.font else g.fallbacks[face - 1].?.face; - c.ui_font_shape(run_font, g.px, @intCast(g.cell_w), text[run_start..].ptr, @intCast(run_end - run_start), shaped[run_start..].ptr); - for (shaped[run_start..run_end]) |cell| { - const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = decoration, .lead = @intCast(cell.lead), .span = @intCast(cell.span) }; - const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.space_slot; - words.slots.appendAssumeCapacity(slot); - } - run_start = run_end; - face = next_face; + fn centreAt(caret: *const Caret, now_ns: u64) [2]f32 { + var sum: [2]f32 = .{ 0, 0 }; + for (caret.corners) |corner| for (&sum, corner) |*s, axis| { + s.* += axis.value(now_ns) / 4; + }; + return sum; } - words.map.put(gpa, hash, .{ .start = @intCast(text_start), .len = @intCast(n), .decoration = decoration }) catch {}; - words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = text_start }; - return words.slots.items[text_start + at - start]; -} -/// A Gui for the tests that build cells, decor or a scroll without a -/// window: these metrics, every other field its default. What needs SDL, a -/// font or the atlas is undefined (textTestGui adds a font and an atlas). -fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gui { - return .{ - .window = undefined, - .device = undefined, - .swapchain_format = undefined, - .pipeline = undefined, - .decor_pipeline = undefined, - .overlay_pipeline = undefined, - .image_pipeline = undefined, - .atlas_tex = undefined, - .atlas_sampler = undefined, - .linear_sampler = undefined, - .atlas_xfer = undefined, - .overlay_vbuf = undefined, - .overlay_vxfer = undefined, - .overlay_vertices = &.{}, - .font = undefined, - .px = 0, - .tagline_px = 0, - .tagline_percent = 0, - .tagline_width = tagline_width, - .tagline_height = tagline_height, - .cell_w = cell_w, - .cell_h = cell_h, - .ascent = 0, - .tagline_baseline = 0, - .atlas_stage = &.{}, - .glyphs = undefined, - }; -} + /// The text under it moved by (dx, dy) cells: so does the quad. + fn shift(caret: *Caret, dx: f32, dy: f32) void { + for (&caret.corners) |*corner| for (corner, [2]f32{ dx, dy }) |*axis, d| { + axis.from += d; + axis.target += d; + }; + caret.from_centre = .{ caret.from_centre[0] + dx, caret.from_centre[1] + dy }; + caret.target.x += dx; + caret.target.y += dy; + } -/// 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; -} + /// The quad at `now_ns`, bowed on a long jump. + fn sample(caret: *const Caret, now_ns: u64) [4][2]f32 { + var out: [4][2]f32 = undefined; + for (&out, caret.corners) |*point, corner| for (point, corner) |*v, axis| { + v.* = axis.value(now_ns); + }; + const to_c = centre(caret.target); + const dx = to_c[0] - caret.from_centre[0]; + const dy = to_c[1] - caret.from_centre[1]; + const length = @sqrt(dx * dx + dy * dy); + if (length < arc_from) return out; + const now_c = caret.centreAt(now_ns); + const left = @sqrt((to_c[0] - now_c[0]) * (to_c[0] - now_c[0]) + (to_c[1] - now_c[1]) * (to_c[1] - now_c[1])); + const travelled = std.math.clamp(1 - left / length, 0, 1); + const bow = arc * length * 4 * travelled * (1 - travelled); + for (&out) |*point| { + point[0] += -dy / length * bow; + point[1] += dx / length * bow; + } + return out; + } -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; -} + /// Steps the springs to `now_ns`; true while the quad still moves. + fn step(caret: *Caret, now_ns: u64) bool { + var any = false; + for (&caret.corners) |*corner| for (corner) |*axis| { + if (axis.step(now_ns)) any = true; + }; + return any; + } -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); + /// How far, in cells, the furthest corner still is from its mark. + fn remaining(caret: *const Caret, now_ns: u64) f32 { + var most: f32 = 0; + for (caret.corners) |corner| for (corner) |axis| { + most = @max(most, @abs(axis.value(now_ns) - axis.target)); + }; + return most; + } - 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]; + fn moving(caret: *const Caret) bool { + for (caret.corners) |corner| for (corner) |axis| { + if (!axis.settled) return true; + }; + return false; } - 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 frame about to be drawn shows the focused cursor at `box` (grid + /// cells; null: none) in pane `owner`'s body, whose first line is + /// `line` and top left (x, y): carried with that body when it moved or + /// scrolled, eased to its box otherwise. + fn see(caret: *Caret, box: ?Box, owner: u8, line: i32, x: u16, y: u16, now_ns: u64) void { + const b = box orelse { + // Nowhere to land: a glide under way stops; the next cursor + // lands where it is. + caret.* = .{}; + return; + }; + var land = false; + const was = caret.seen; + if (was.owner == owner and owner != pardes.Region.none) { + // The pane moved in the layout: its caret moves with it. + caret.shift(@as(f32, @floatFromInt(x)) - @as(f32, @floatFromInt(was.x)), @as(f32, @floatFromInt(y)) - @as(f32, @floatFromInt(was.y))); + // Scrolled: the text moved, not the caret; it lands on its + // cell (the glide draws it with the text, caretRide). + land = line != was.line; + } + caret.seen = .{ .owner = owner, .line = line, .x = x, .y = y }; + caret.aim(b, now_ns, land); + _ = caret.step(now_ns); + } +}; - // 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)); +/// 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). +fn caretRide(g: *const Gui, surface: *const pardes.Surface) f32 { + const glide = &g.glide; + const cu = surface.cursor orelse return 0; + if (glide.follow.offset != 0) { + if (!glide.caret_rides) return 0; + const x0 = glide.rect.x + config.GUTTER; + if (cu.x < x0 or cu.x >= x0 + glide.bw() or cu.y < glide.body_y or cu.y >= glide.body_y + glide.body_h) return 0; + return glide.follow.offset; } - // A tagline is never shaped. - try std.testing.expectEqual(c.ui_font_glyph(font, '-'), (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph); + // A fine wheel's or a touchpad's fraction (scroll_lag) holds the whole + // body off its cells, the caret's row with the rest, at rest too. + if (g.scroll_lag == 0 or g.scroll_pane == null) return 0; + const r = g.scroll_rect; + if (cu.x < r.x + config.GUTTER or cu.x >= r.x + r.w or cu.y < g.scroll_body_y or cu.y >= g.scroll_body_y + g.scroll_body_h) return 0; + return g.scroll_lag; } -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; +/// 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; + // The focused one is drawn with its line where a wheel's fraction holds + // the text off its cells (a block is a cell of the shifted rows). + // The focused box is the one nearest its cell (a body layer's is lifted + // off the grid), as seeCaret finds it. + const ride = caretRide(g, surface) * layout.h; + const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; + var focused: usize = all.len; + if (surface.cursor) |cu| { + const cx = (@as(f32, @floatFromInt(cu.x)) + 0.5) * layout.w; + const cy = (@as(f32, @floatFromInt(cu.y)) + 0.5) * layout.h; + var nearest = std.math.inf(f32); + for (all, 0..) |b, i| { + const d = ((b.x0 + b.x1) / 2 - cx) * ((b.x0 + b.x1) / 2 - cx) + ((b.y0 + b.y1) / 2 - cy) * ((b.y0 + b.y1) / 2 - cy); + if (d < nearest) { + nearest = d; + focused = i; + } + } + } + for (all, 0..) |box, i| if (box.bar) { + const shift = if (i == focused) ride else 0; + try addDecor(g, gpa, box.x0, box.y0 - shift, box.x1, box.y1 - shift, box.rgb, 1, win_w, win_h); + }; } -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 triangle overlay: the cursor's glide, over everything. +fn buildOverlay( + g: *Gui, + which: pardes.config.Runtime.Pet, + trail_on: bool, + surface: *const pardes.Surface, + now_ns: u64, + sw: u32, + sh: u32, +) u32 { + if (g.overlay_vertices.len == 0 or sw == 0 or sh == 0) return 0; + var builder = OverlayBuilder{ .vertices = g.overlay_vertices, .win_w = @floatFromInt(sw), .win_h = @floatFromInt(sh) }; + appendWorkspacePet(g, which, surface, &builder); + appendJumpTrail(g, trail_on, surface, now_ns, &builder); + appendCursorGlide(g, surface, now_ns, &builder); + return @intCast(builder.len); +} + +/// A jump's trail (jump_trail.zig): the cells behind the cursor in its +/// body, on the page's own ground, drawn over toward the text's colour. +fn appendJumpTrail(g: *Gui, on: bool, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { + var at: [5]JumpTrail.Cell = undefined; + const lit = g.trail.see(if (surface.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); + if (lit.len == 0) return; + const cursor = surface.cursor.?; + const body = for (surface.regionList()) |region| { + if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and + cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; + } else return; + const page = surface.chrome.page orelse bg_default; + const w: f32 = @floatFromInt(g.cell_w); + const h: f32 = @floatFromInt(g.cell_h); + for (lit) |cell| { + if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue; + const under = &surface.cells[@as(usize, @intCast(cell.y)) * surface.cols + @as(usize, @intCast(cell.x))]; + // On the page's own ground alone: never a selection or a match. + const ground: [3]u8 = if (under.default) page else switch (under.style.bg) { + .rgb => |rgb| rgb, + else => page, + }; + if (!std.mem.eql(u8, &ground, &page)) continue; + var color = overlayRgb(surface.chrome.fg orelse fg_default); + color.a = cell.strength; + const x0 = @as(f32, @floatFromInt(cell.x)) * w; + const y0 = @as(f32, @floatFromInt(cell.y)) * h; + builder.addRect(x0, y0, x0 + w, y0 + h, color); + } +} + +/// 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. +fn appendWorkspacePet(g: *Gui, which: pardes.config.Runtime.Pet, surface: *const pardes.Surface, builder: *OverlayBuilder) void { + const kind: pet.Kind = @fromBackingInt(@backingInt(which)); + if (kind == .off or surface.rows == 0 or surface.cols == 0) { + g.pet_state = .{}; + return; } + var occupied: usize = 0; + for (surface.cells[0..surface.cols], 0..) |*cell, i| { + if (cellCodepoint(cell) != ' ') occupied = i + 1; + } + const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); + const region = if (occupied >= surface.cols) null else pet.lane( + occupied, + @floatFromInt(g.tagline_width), + builder.win_w, + band_top, + @floatFromInt(g.tagline_height), + ); + // ponytail: it moves when the window draws; a wake of its own for an + // idle window if a still pet ever matters. + const pose = g.pet_state.sample(kind, c.SDL_GetTicks(), region) orelse return; + const ink = overlayRgb(surface.chrome.tag_fg); + const eye = overlayRgb(surface.chrome.tag_bg); + // Behind the cursor: the overlay is over the cells, so the pixels a + // cursor covers are left out. + var boxes: [max_cursors]CursorBox = undefined; + const cursors = boxes[0..cursorBoxes(g, surface, fixedCellLayout(g), builder.win_h, &boxes)]; + for (0..pet.height) |y| for (0..pet.width) |x| { + const color = pet.pixel(kind, pose, x, y); + if (color == 0) continue; + const x0 = pose.x + @as(f32, @floatFromInt(x)) * pose.scale; + const y0 = pose.y + @as(f32, @floatFromInt(y)) * pose.scale; + const covered = for (cursors) |box| { + if (x0 < box.x1 and x0 + pose.scale > box.x0 and y0 < box.y1 and y0 + pose.scale > box.y0) break true; + } else false; + if (covered) continue; + builder.addRect(x0, y0, x0 + pose.scale, y0 + pose.scale, if (color == 2) eye else ink); + }; } -/// 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. -fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { - if (g.glyphs.get(key)) |s| return s; - const slot_w = g.cell_w * @as(u32, if (key.centered) config.GUTTER else key.span); - if (g.pen_x + slot_w > atlas_w) { - g.pen_x = 0; - g.pen_y += g.cell_h; - } - if (g.pen_y + g.cell_h > atlas_h) return null; // atlas full: fall back - const probe_raster = monoNs(); - defer if (frame_probe) |probe| { - probe.zone(.gui_raster, probe_raster); - probe.rastered +|= 1; +fn overlayRgb(rgb: [3]u8) OverlayColor { + return .{ + .r = @as(f32, @floatFromInt(rgb[0])) / 255.0, + .g = @as(f32, @floatFromInt(rgb[1])) / 255.0, + .b = @as(f32, @floatFromInt(rgb[2])) / 255.0, + .a = 1, }; - const s = Slot{ .u = g.pen_x, .v = g.pen_y }; - const out = g.atlas_stage.ptr + @as(usize, s.v) * atlas_w + s.u; - const face = if (key.face == 0) g.font else g.fallbacks[key.face - 1].?.face; - const px = if (key.role == .tagline) g.tagline_px else g.px; - const baseline = if (key.role == .tagline) g.tagline_baseline else g.ascent; - const cell_w = if (key.role == .tagline) g.tagline_width else g.cell_w; - const raster_w = if (key.centered) slot_w else cell_w * key.span; - const raster_h = if (key.role == .tagline) g.tagline_height else g.cell_h; - const bold = @intFromBool(key.decoration.bold); - if (key.rule) { - drawRule(out, atlas_w, raster_w, raster_h, ruleArms(key.glyph).?); - } else if (key.centered) { - _ = c.ui_font_raster_centered(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h)); - } else { - _ = c.ui_font_raster(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h), @intCast(cell_w * key.lead), @intCast(cell_w), baseline); - } - decorateLine(out, atlas_w, raster_w, raster_h, baseline, key.decoration); - if (key.centered) centerGlyphInk(out, raster_w, raster_h); - g.atlas_dirty_top = @min(g.atlas_dirty_top, s.v); - g.atlas_dirty_bottom = @max(g.atlas_dirty_bottom, s.v + raster_h); - g.glyphs.put(key, s) catch return null; - g.pen_x += slot_w; - return s; } -// Run once when a grip glyph enters the atlas, after decorations. Copy only -// visible ink so bearings, empty bitmap margins and bold all share one center. -fn centerGlyphInk(out: [*]u8, width: usize, height: usize) void { - const b = inkBounds(out[0 .. (height - 1) * atlas_w + width], atlas_w, width, height) orelse return; - const w = b.max_x - b.min_x + 1; - const h = b.max_y - b.min_y + 1; - const left = (width - w) / 2; - const top = (height - h) / 2; - var scratch: [atlas_w]u8 = undefined; - for (0..h) |step| { - const row = if (top > b.min_y) h - 1 - step else step; - const source = (b.min_y + row) * atlas_w + b.min_x; - const target = (top + row) * atlas_w; - @memcpy(scratch[0..w], out[source..][0..w]); - @memset(out[target..][0..width], 0); - @memcpy(out[target + left ..][0..w], scratch[0..w]); +/// G3: the focused cursor while it glides or blinks, its quad from the +/// window's caret (Caret, grid cells) in its cursor colour; a little less +/// than solid, so the glyphs it passes over stay legible. +fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { + const chrome = &surface.chrome; + if (g.cursor_quad_alpha <= 0.001) return; + const layout = fixedCellLayout(g); + const ride = caretRide(g, surface); + // Never off the grid, however a long jump bows. + var quad = g.caret.sample(now_ns); + for (&quad) |*point| point.* = .{ std.math.clamp(point[0], 0, @as(f32, @floatFromInt(surface.cols))), std.math.clamp(point[1], 0, @as(f32, @floatFromInt(surface.rows))) }; + if (ride != 0) { + // Carried past the body's edge with its line: clipped as the text is. + const mid = quad[0][1] - ride + 0.5; + const top: f32 = @floatFromInt(g.glide.body_y); + if (mid < top or mid > top + @as(f32, @floatFromInt(g.glide.body_h))) return; } - for (0..height) |row| { - if (row < top or row >= top + h) @memset(out[row * atlas_w ..][0..width], 0); + var px: [4][2]f32 = undefined; + var centre: [2]f32 = .{ 0, 0 }; + for (&px, 0..) |*point, i| { + point.* = .{ quad[i][0] * layout.w, (quad[i][1] - ride) * layout.h }; + centre[0] += point[0] / 4; + centre[1] += point[1] / 4; } -} - -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); - }; + // Its colour: the cursor the cells would draw nearest the quad. + var boxes: [max_cursors]CursorBox = undefined; + var rgb: [3]u8 = chrome.fg orelse fg_default; + var nearest: f32 = std.math.inf(f32); + for (boxes[0..cursorBoxes(g, surface, layout, builder.win_h, &boxes)]) |box| { + const dx = (box.x0 + box.x1) / 2 - centre[0]; + const dy = (box.y0 + box.y1) / 2 - centre[1]; + if (dx * dx + dy * dy < nearest) { + nearest = dx * dx + dy * dy; + rgb = box.rgb; } } - 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 })); + const color: OverlayColor = .{ .r = @as(f32, @floatFromInt(rgb[0])) / 255, .g = @as(f32, @floatFromInt(rgb[1])) / 255, .b = @as(f32, @floatFromInt(rgb[2])) / 255, .a = g.cursor_quad_alpha }; + builder.addTri(px[0][0], px[0][1], px[1][0], px[1][1], px[2][0], px[2][1], color); + builder.addTri(px[0][0], px[0][1], px[2][0], px[2][1], px[3][0], px[3][1], color); } -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 = .{}; +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; + const dst: [*]u8 = @ptrCast(ptr); + const src: [*]const u8 = @ptrCast(g.overlay_vertices.ptr); + @memcpy(dst[0..byte_len], src[0..byte_len]); + c.SDL_UnmapGPUTransferBuffer(g.device, g.overlay_vxfer); + const copy = c.SDL_BeginGPUCopyPass(cmd); + const src_loc = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.overlay_vxfer, .offset = 0 }; + const dst_region = c.SDL_GPUBufferRegion{ .buffer = g.overlay_vbuf, .offset = 0, .size = byte_len }; + c.SDL_UploadToGPUBuffer(copy, &src_loc, &dst_region, false); + c.SDL_EndGPUCopyPass(copy); + return true; +} - 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); +fn pushLayerOpacity(cmd: *c.SDL_GPUCommandBuffer, pass: ?*c.SDL_GPURenderPass, opacity: f32) void { + const uniforms = [4]f32{ opacity, 0, 0, 0 }; + c.SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms, @sizeOf(@TypeOf(uniforms))); + // The source alpha is geometric/image coverage, not window opacity. Its + // alpha contribution is multiplied by this constant separately, so a + // rail repainted over a gutter still has alpha p, not p + p*(1-p). + c.SDL_SetGPUBlendConstants(pass, .{ .r = opacity, .g = opacity, .b = opacity, .a = opacity }); } -// 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 -// decorates terminal spaces. Bold is not drawn here: the rasterizer emboldens -// the outline. -fn decorateLine(out: [*]u8, stride: usize, width: usize, height: usize, baseline: i32, decoration: GlyphDecoration) void { - if (width == 0 or height == 0) return; - // A line is a logical pixel thick, its dots and waves as long: the same - // weight at any density (dp). - const t: usize = @intFromFloat(dp(1)); - if (decoration.underline != .off) { - const base: usize = @intCast(@max(0, baseline)); - const row = @min(base + 1, height -| t); - for (0..width) |x| { - const top = switch (decoration.underline) { - .off => unreachable, - .single => row, - .double => { - const upper = @min(base + 1, height -| 3 * t); - for (0..t) |k| { - out[@min(upper + k, height - 1) * stride + x] = 255; - out[@min(upper + 2 * t + k, height - 1) * stride + x] = 255; - } - continue; - }, - .curly => row -| @as(usize, if (x % (4 * t) < 2 * t) t else 0), - .dotted => if (x % (3 * t) < t) row else continue, - .dashed => if (x % (6 * t) < 4 * t) row else continue, - }; - for (0..t) |k| out[@min(top + k, height - 1) * stride + x] = 255; - } +fn drawOverlayGpu(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, rp: ?*c.SDL_GPURenderPass, vertex_count: u32) void { + if (vertex_count == 0) return; + const pass = rp orelse return; + c.SDL_BindGPUGraphicsPipeline(pass, g.overlay_pipeline); + const binding = c.SDL_GPUBufferBinding{ .buffer = g.overlay_vbuf, .offset = 0 }; + c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1); + pushLayerOpacity(cmd, pass, backgroundOpacity(g.applied_window_opacity)); + c.SDL_DrawGPUPrimitives(pass, vertex_count, 1, 0, 0); +} + +const OverlayBuilder = struct { + vertices: []OverlayVertex, + len: usize = 0, + win_w: f32, + win_h: f32, + + fn addVertex(b: *OverlayBuilder, px: f32, py: f32, color: OverlayColor) void { + if (b.len >= b.vertices.len) return; + b.vertices[b.len] = .{ + .x = (px / b.win_w) * 2.0 - 1.0, + .y = 1.0 - (py / b.win_h) * 2.0, + .r = color.r, + .g = color.g, + .b = color.b, + .a = color.a, + }; + b.len += 1; } - if (decoration.strikethrough) { - const row = @min(height -| t, @as(usize, @intCast(@max(0, baseline))) * 2 / 3); - for (0..t) |k| @memset(out[@min(row + k, height - 1) * stride ..][0..width], 255); + + fn addTri(b: *OverlayBuilder, x0: f32, y0: f32, x1: f32, y1: f32, x2: f32, y2: f32, color: OverlayColor) void { + if (b.len + 3 > b.vertices.len) return; + b.addVertex(x0, y0, color); + b.addVertex(x1, y1, color); + b.addVertex(x2, y2, color); + } + + fn addRect(b: *OverlayBuilder, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, color: OverlayColor) void { + if (b.len + 6 > b.vertices.len) return; + const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, b.win_w); + const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, b.win_w); + const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, b.win_h); + const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, b.win_h); + if (x1 <= x0 or y1 <= y0) return; + b.addTri(x0, y0, x1, y0, x1, y1, color); + b.addTri(x0, y0, x1, y1, x0, y1, color); } +}; + +fn envU16(env: *std.process.Environ.Map, name: []const u8) ?u16 { + const raw = env.get(name) orelse return null; + return std.fmt.parseInt(u16, raw, 10) catch null; } -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); +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)); } -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); +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; } - const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; - try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank()); + return null; } -/// 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 -/// offset in the transfer buffer as in the stage, and the texture keeps the -/// rows outside it. -fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void { - const top = g.atlas_dirty_top; - const rows = g.atlas_dirty_bottom - top; - const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.atlas_xfer, false) orelse return; - const dst: [*]u8 = @ptrCast(ptr); - @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], g.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]); - c.SDL_UnmapGPUTransferBuffer(g.device, g.atlas_xfer); +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); + }; +} - const copy = c.SDL_BeginGPUCopyPass(cmd); - const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = g.atlas_xfer, .offset = top * atlas_w, .pixels_per_row = atlas_w, .rows_per_layer = rows }; - const dstregion = c.SDL_GPUTextureRegion{ .texture = g.atlas_tex, .mip_level = 0, .layer = 0, .x = 0, .y = top, .z = 0, .w = atlas_w, .h = rows, .d = 1 }; - c.SDL_UploadToGPUTexture(copy, &src, &dstregion, false); - c.SDL_EndGPUCopyPass(copy); - g.atlas_dirty_top = atlas_h; - g.atlas_dirty_bottom = 0; +/// 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; } -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); +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; } -/// 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). -fn growInstances(g: *Gui, buffer: *?*c.SDL_GPUBuffer, transfer: *?*c.SDL_GPUTransferBuffer, capacity: *u32, needed: u32, stride: u32) !void { - if (needed <= capacity.* and buffer.* != null and transfer.* != null) return; - var grown = @max(@as(u32, 1), capacity.*); - while (grown < needed) grown = std.math.mul(u32, grown, 2) catch return error.GpuCapacity; - const size = std.math.mul(u32, grown, stride) catch return error.GpuCapacity; - var vb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = size, .props = 0 }; - const next_buffer = c.SDL_CreateGPUBuffer(g.device, &vb_info) orelse return error.GpuCreate; - errdefer c.SDL_ReleaseGPUBuffer(g.device, next_buffer); - var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = size, .props = 0 }; - const next_transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate; - if (buffer.*) |old| c.SDL_ReleaseGPUBuffer(g.device, old); - if (transfer.*) |old| c.SDL_ReleaseGPUTransferBuffer(g.device, old); - buffer.* = next_buffer; - transfer.* = next_transfer; - capacity.* = grown; +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; } -/// One vertex buffer of a pipeline: `pitch` bytes an element, read per -/// vertex or per instance through `attrs`. -const VertexInput = struct { pitch: u32, rate: c.SDL_GPUVertexInputRate, attrs: []const c.SDL_GPUVertexAttribute }; +/// 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 cells' and the decor's instances (ui.vert.glsl). -const cell_input: VertexInput = .{ .pitch = @sizeOf(CellInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{ - .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "x0") }, - .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "u0") }, - .{ .location = 2, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "fr") }, - .{ .location = 3, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "br") }, - .{ .location = 4, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_UINT, .offset = @offsetOf(CellInstance, "effect") }, - .{ .location = 5, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "clip_x0") }, -} }; +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; +} -const overlay_input: VertexInput = .{ .pitch = @sizeOf(OverlayVertex), .rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .attrs = &.{ - .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, .offset = @offsetOf(OverlayVertex, "x") }, - .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(OverlayVertex, "r") }, -} }; +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 image_input: VertexInput = .{ .pitch = @sizeOf(ImageInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{ - .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "x0") }, - .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "u0") }, -} }; + 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 pipeline drawing triangles into `color_format`: `vert`, and `frag` -/// with its samplers and uniform buffers, over one vertex buffer of -/// `input` (none: the post chain's triangle over the whole frame). -pub fn makePipeline( - device: *c.SDL_GPUDevice, - color_format: c.SDL_GPUTextureFormat, - vert: []const u8, - frag: []const u8, - samplers: u32, - uniforms: u32, - input: ?VertexInput, - blend: c.SDL_GPUColorTargetBlendState, -) !*c.SDL_GPUGraphicsPipeline { - const vs = try makeShader(device, vert, c.SDL_GPU_SHADERSTAGE_VERTEX, 0, 0); - defer c.SDL_ReleaseGPUShader(device, vs); - const fs = try makeShader(device, frag, c.SDL_GPU_SHADERSTAGE_FRAGMENT, samplers, uniforms); - defer c.SDL_ReleaseGPUShader(device, fs); - var col_desc = c.SDL_GPUColorTargetDescription{ .format = color_format, .blend_state = blend }; - var vbuf_desc: c.SDL_GPUVertexBufferDescription = undefined; - var info = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo); - info.vertex_shader = vs; - info.fragment_shader = fs; - info.primitive_type = c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; - if (input) |in| { - vbuf_desc = .{ .slot = 0, .pitch = in.pitch, .input_rate = in.rate, .instance_step_rate = 0 }; - info.vertex_input_state = .{ - .vertex_buffer_descriptions = &vbuf_desc, - .num_vertex_buffers = 1, - .vertex_attributes = in.attrs.ptr, - .num_vertex_attributes = @intCast(in.attrs.len), - }; - } - info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL; - info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE; - info.multisample_state.sample_count = c.SDL_GPU_SAMPLECOUNT_1; - info.target_info = .{ .color_target_descriptions = &col_desc, .num_color_targets = 1 }; - return c.SDL_CreateGPUGraphicsPipeline(device, &info) orelse error.GpuCreate; + // 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); } -fn backgroundLayerBlend() c.SDL_GPUColorTargetBlendState { - var blend = std.mem.zeroes(c.SDL_GPUColorTargetBlendState); - blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_SRC_ALPHA; - blend.dst_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; - blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD; - blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR; - blend.dst_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; - blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD; - blend.enable_blend = true; - return blend; +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 "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 "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); -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; - info.code_size = code.len; - info.entrypoint = "main"; - info.format = c.SDL_GPU_SHADERFORMAT_SPIRV; - info.stage = stage; - info.num_samplers = n_samplers; - info.num_uniform_buffers = n_uniform_buffers; - return c.SDL_CreateGPUShader(device, &info) orelse error.GpuCreate; + 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], + ); } -/// A 2D texture of one level, one layer and one sample. -pub fn texture2d(device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, width: u32, height: u32) ?*c.SDL_GPUTexture { - var info = std.mem.zeroes(c.SDL_GPUTextureCreateInfo); - info.type = c.SDL_GPU_TEXTURETYPE_2D; - info.format = format; - info.usage = usage; - info.width = width; - info.height = height; - info.layer_count_or_depth = 1; - info.num_levels = 1; - info.sample_count = c.SDL_GPU_SAMPLECOUNT_1; - return c.SDL_CreateGPUTexture(device, &info); -} +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); -fn ensureCaptureTexture(g: *Gui, width: u32, height: u32) !void { - if (g.capture_tex != null and g.capture_tex_w == width and g.capture_tex_h == height) return; - const next = texture2d(g.device, g.swapchain_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, width, height) orelse return error.GpuCreate; - if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture); - g.capture_tex = next; - g.capture_tex_w = width; - g.capture_tex_h = height; + 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))); } -fn softTargetFormat(device: *c.SDL_GPUDevice) c.SDL_GPUTextureFormat { - const candidates = [_]c.SDL_GPUTextureFormat{ - c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, - c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, - }; - for (candidates) |format| { - if (c.SDL_GPUTextureSupportsFormat( - device, - format, - c.SDL_GPU_TEXTURETYPE_2D, - c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER, - )) return format; - } - return c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM; +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))); } -fn softPixelFormat(format: c.SDL_GPUTextureFormat) ?c.SDL_PixelFormat { - return switch (format) { - c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, - c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB, - => c.SDL_PIXELFORMAT_ARGB8888, - c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, - c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB, - => c.SDL_PIXELFORMAT_ABGR8888, - else => null, - }; +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); } -fn ensureSoftTexture(g: *Gui, width: u32, height: u32) !*c.SDL_Texture { - if (g.soft_texture) |texture| { - if (g.soft_tex_w == width and g.soft_tex_h == height) return texture; - c.SDL_DestroyTexture(texture); - g.soft_texture = null; - } - const renderer = g.soft_renderer orelse return error.GpuCreate; - const pixel_format = softPixelFormat(g.swapchain_format) orelse return error.UnsupportedCaptureFormat; - const next = c.SDL_CreateTexture( - renderer, - pixel_format, - c.SDL_TEXTUREACCESS_STREAMING, - @intCast(width), - @intCast(height), - ) orelse return error.GpuCreate; - _ = c.SDL_SetTextureScaleMode(next, c.SDL_SCALEMODE_NEAREST); - _ = c.SDL_SetTextureBlendMode(next, c.SDL_BLENDMODE_NONE); - g.soft_texture = next; - g.soft_tex_w = width; - g.soft_tex_h = height; - return next; +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)); } -/// The frame in `target`, `size` bytes, copied down into `capture_xfer` -/// (grown to it first) by `cmd`, which the caller submits and waits for. -/// With no buffer to be had the command buffer is submitted as it is. -fn downloadTarget(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32, size: u32) !*c.SDL_GPUTransferBuffer { - if (g.capture_xfer == null or g.capture_xfer_size < size) { - var info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = size, .props = 0 }; - const next = c.SDL_CreateGPUTransferBuffer(g.device, &info) orelse { - _ = c.SDL_SubmitGPUCommandBuffer(cmd); - return error.GpuCreate; +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 (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer); - g.capture_xfer = next; - g.capture_xfer_size = size; + if (!eof) try std.testing.io.sleep(.fromMilliseconds(1), .awake); } - const xfer = g.capture_xfer.?; - const copy = c.SDL_BeginGPUCopyPass(cmd); - const src = c.SDL_GPUTextureRegion{ .texture = target, .mip_level = 0, .layer = 0, .x = 0, .y = 0, .z = 0, .w = sw, .h = sh, .d = 1 }; - const dst = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = xfer, .offset = 0, .pixels_per_row = sw, .rows_per_layer = sh }; - c.SDL_DownloadFromGPUTexture(copy, &src, &dst); - c.SDL_EndGPUCopyPass(copy); - return xfer; + 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)); } -fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void { - const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format); - const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1); - if (size == 0 or bpp != 4) { - _ = c.SDL_SubmitGPUCommandBuffer(cmd); - return error.UnsupportedCaptureFormat; - } - const xfer = try downloadTarget(g, cmd, target, sw, sh, size); +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); +} - const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; - defer c.SDL_ReleaseGPUFence(g.device, fence); - var fences = [_]*c.SDL_GPUFence{fence}; - const probe_wait = monoNs(); - if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit; - if (frame_probe) |probe| probe.zone(.gui_wait, probe_wait); +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)); +} - const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap; - defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer); +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); +} - const texture = try ensureSoftTexture(g, sw, sh); - const renderer = g.soft_renderer orelse return error.GpuCreate; - const probe_upload = monoNs(); - defer if (frame_probe) |probe| probe.zone(.gui_upload, probe_upload); - if (!c.SDL_UpdateTexture(texture, null, mapped, @intCast(sw * bpp))) return error.GpuMap; - // PARDES_FRAMES_CAPTURE: every presented frame's pixels as they went - // out, and when, for a recording at the frames' own times. One write a - // frame; nothing else. - if (frame_capture_dir) |dir| captureSeries(dir, @as([*]const u8, @ptrCast(mapped))[0..size], sw, sh); - // The cell shader already produced premultiplied backgrounds with opaque - // foreground ink. Copy that alpha unchanged; never modulate the full frame. - _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE); - _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.surface_opacity) 0 else 255); - _ = c.SDL_RenderClear(renderer); - _ = c.SDL_RenderTexture(renderer, texture, null, null); - const probe_flip = monoNs(); - _ = c.SDL_RenderPresent(renderer); - if (frame_probe) |probe| probe.zone(.gui_flip, probe_flip); +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 backgroundOpacity(percent: u8) f32 { - std.debug.assert(percent <= 100); - return @as(f32, @floatFromInt(percent)) / 100; -} +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); -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))); + 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); } } -/// 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 - -/// start is the frame's CPU cost). Nothing is written without it. -var latency_fd: c_int = -1; -var frame_started_ns: u64 = 0; - -fn monoNs() u64 { - var ts: libc.timespec = undefined; - if (libc.clock_gettime(.MONOTONIC, &ts) != 0) return 0; - return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); -} - -fn latencyNote(comptime fmt: []const u8, args: anytype) void { - if (latency_fd < 0) return; - var buf: [64]u8 = undefined; - const line = std.fmt.bufPrint(&buf, fmt, args) catch return; - _ = libc.write(latency_fd, line.ptr, line.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)); } -/// Writes the frame to latest.ppm in the capture directory, and in a -/// series to frame-.ppm too. -fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void { - const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1); - if (size == 0) { - _ = c.SDL_SubmitGPUCommandBuffer(cmd); - return error.UnsupportedCaptureFormat; +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 => {}, + }; } - const xfer = try downloadTarget(g, cmd, target, sw, sh, size); - - const submit_ns = monoNs(); - const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; - defer c.SDL_ReleaseGPUFence(g.device, fence); - var fences = [_]*c.SDL_GPUFence{fence}; - if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit; - latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, monoNs(), submit_ns }); - - const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap; - defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer); - const pixels: [*]const u8 = @ptrCast(mapped); - try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, "latest"); - var name: [24]u8 = undefined; - // unreachable below: "frame-" and a u32 fit 24 - if (g.capture_series) try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable); - g.captured +%= 1; + 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()); } -/// A test window's state for a harness (test/process/window.zig), in the -/// capture directory's `status`: " ". -/// Idle is 1 once the frame last captured is the one that stays: nothing -/// owes a frame, nothing moves, nothing waits on a clock. A harness that -/// sees a step past the one it acted on, idle, has its frame, however slow -/// the machine is. -var test_status_step: u64 = 0; -fn writeTestStatus(g: *const Gui, core: *const pardes.Pardes, presented: bool) void { - test_status_step +%= 1; - if (g.capture_dir.len == 0) return; - const idle = presented and !core.needs_frame and !frontendMoving(g) and core.nextWake() == null and - !g.glide.moving() and g.scroll_lag == 0 and g.scroll_delta == 0 and g.scroll_notch == 0; - var line_buf: [64]u8 = undefined; - // What keeps it busy, after: owes a frame, moves, waits, not shown. - const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}{d}{d}{d}\n", .{ test_status_step, g.captured, @intFromBool(idle), @intFromBool(core.needs_frame), @intFromBool(frontendMoving(g)), @intFromBool(core.nextWake() != null), @intFromBool(!presented) }) catch unreachable; // seven numbers fit 64 - var tmp_buf: [4096]u8 = undefined; - var final_buf: [4096]u8 = undefined; - const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/status.tmp", .{g.capture_dir}, 0) catch return; - const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/status", .{g.capture_dir}, 0) catch return; - const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return; - _ = libc.write(fd, line.ptr, line.len); - _ = libc.close(fd); - _ = libc.rename(tmp_path, final_path); +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()); + } } -fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8) !void { - // A latency trace times frames, and an 8 MB file write per frame would - // stall the loop it is timing. - if (g.capture_dir.len == 0 or latency_fd >= 0) return; - const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format); - if (bpp != 4) return error.UnsupportedCaptureFormat; - const bgr = switch (g.swapchain_format) { - c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB => false, - c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB => true, - else => return error.UnsupportedCaptureFormat, - }; +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()); - var tmp_buf: [4096]u8 = undefined; - var final_buf: [4096]u8 = undefined; - const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.ppm.tmp", .{ g.capture_dir, name }, 0) catch return error.CapturePathTooLong; - const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.ppm", .{ g.capture_dir, name }, 0) catch return error.CapturePathTooLong; + 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 fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return error.CaptureWriteFailed; - defer _ = libc.close(fd); + 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); - var header: [64]u8 = undefined; - const hdr = std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch unreachable; // two u32s fit 64 - _ = host_io.writeFd(fd, hdr); + 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); - const row_rgb = try gpa.alloc(u8, @as(usize, width) * 3); - defer gpa.free(row_rgb); - for (0..height) |row| { - const src = pixels[row * width * 4 ..][0 .. @as(usize, width) * 4]; - for (0..width) |x| { - const si = x * 4; - const di = x * 3; - row_rgb[di + 0] = src[si + if (bgr) @as(usize, 2) else 0]; - row_rgb[di + 1] = src[si + 1]; - row_rgb[di + 2] = src[si + if (bgr) @as(usize, 0) else 2]; - } - _ = host_io.writeFd(fd, row_rgb); - } - if (libc.rename(tmp_path, final_path) != 0) return error.CaptureWriteFailed; + // 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); } -/// One flat, hard-edged rectangle of decor, in window pixels: clipped to the -/// window and dropped when empty, as the triangle overlay drew it. -fn addDecor(g: *Gui, gpa: std.mem.Allocator, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, rgb: [3]u8, alpha: f32, win_w: f32, win_h: f32) !void { - const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, win_w); - const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, win_w); - const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, win_h); - const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, win_h); - if (x1 <= x0 or y1 <= y0) return; - // decor.frag.glsl reads the colour from the ground and the coverage - // from the ink's red. - try g.decor.append(gpa, .{ - .x0 = (x0 / win_w) * 2.0 - 1.0, - .y0 = 1.0 - (y0 / win_h) * 2.0, - .x1 = (x1 / win_w) * 2.0 - 1.0, - .y1 = 1.0 - (y1 / win_h) * 2.0, - .u0 = 0, - .v0 = 0, - .u1 = 0, - .v1 = 0, - .fr = alpha, - .fg = 0, - .fb = 0, - .br = @as(f32, @floatFromInt(rgb[0])) / 255.0, - .bg = @as(f32, @floatFromInt(rgb[1])) / 255.0, - .bb = @as(f32, @floatFromInt(rgb[2])) / 255.0, - }); +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 body region in window pixels. -fn bodyPixels(region: pardes.Region, layout: CellLayout) [4]f32 { - return .{ - @as(f32, @floatFromInt(region.rect.x)) * layout.w, - @as(f32, @floatFromInt(region.rect.y)) * layout.h, - @as(f32, @floatFromInt(region.rect.x + region.rect.w)) * layout.w, - @as(f32, @floatFromInt(region.rect.y + region.rect.h)) * layout.h, - }; +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); } -/// The frame's decor, group by group (docs/render-pipeline.md), all of it -/// read from the regions and the palette: the page's rules and the panes' -/// rails, rules and grip marks with the page, notice rules with the -/// notices, bar cursors with the ink. -fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, groups: *Groups, layout: CellLayout, win_w: f32, win_h: f32, cursors_shown: bool) !void { - g.decor.clearRetainingCapacity(); - const chrome = &surface.chrome; - const regions = surface.regionList(); - for (groups.items[0..groups.len], 0..) |*group, index| { - group.decor_start = @intCast(g.decor.items.len); - defer group.decor_count = @as(u32, @intCast(g.decor.items.len)) - group.decor_start; - if (index == 0) { - // The grips' buttons before any rule: the rules over their rows - // cut them, and the band round them never covers a rule. - try gripDecor(g, gpa, regions, surface.cells, chrome, layout, surface.cols, surface.rows, win_w, win_h); - const top = for (regions) |region| { - if (region.kind == .workspace_tag) break region.rect.h; - } else 0; - // The workspace tag is ruled off from the tags right under it. - const tag_under = for (regions) |region| switch (region.kind) { - .grip, .tag, .column_grip, .column_tag => if (region.rect.y == top) break true, - else => {}, - } else false; - // As wide as the other rules, where the tagline leaves the room. - const height: u32 = @intFromFloat(@max(1, @min(rulePx(chrome), @as(f32, @floatFromInt((g.cell_h -| g.tagline_height) * 2))))); - if (top != 0 and top < surface.rows and tag_under and height != 0) { - const y0: f32 = @floatFromInt(top * g.cell_h - height / 2); - try addDecor(g, gpa, 0, y0, win_w, y0 + @as(f32, @floatFromInt(height)), chrome.topbar_rule, 1, win_w, win_h); - } - // The column bar is ruled off from the panes under it. - for (regions) |bar| { - if (bar.kind != .column_grip) continue; - const y = @as(f32, @floatFromInt(bar.rect.y + bar.rect.h)) * layout.h; - try addDecor(g, gpa, 0, y - rulePx(chrome), win_w, y, chrome.border, 1, win_w, win_h); - break; - } - // A tag on the last row runs on through the pixels under the grid. - const grid_bottom = @as(f32, @floatFromInt(surface.rows)) * layout.h; - const tag_last = for (regions) |region| switch (region.kind) { - .grip, .tag, .column_grip, .column_tag, .workspace_tag => if (region.rect.h != 0 and region.rect.y + region.rect.h == surface.rows) break true, - else => {}, - } else false; - if (grid_bottom < win_h and tag_last) try addDecor(g, gpa, 0, grid_bottom, win_w, win_h, chrome.tag_bg, 1, win_w, win_h); - try paneDecor(g, gpa, regions, surface.rail_ticks[0..surface.nrail_ticks], chrome, layout, surface.cols, surface.rows, win_w, win_h); - // A single spine runs down each column, through every tag and body. - for (regions) |column| { - if (column.kind != .column) continue; - const x = @as(f32, @floatFromInt(column.rect.x)) * layout.w; - const y0 = @as(f32, @floatFromInt(column.rect.y)) * layout.h; - const grid_y1 = @as(f32, @floatFromInt(surface.rows)) * layout.h; - const y1 = if (win_h - grid_y1 < layout.h) @max(grid_y1, win_h) else grid_y1; - // None at the window's edge: nothing to rule apart there. - if (column.rect.x == 0) continue; - if (y1 > y0) try addDecor(g, gpa, x, y0, x + rulePx(chrome), y1, chrome.border, 1, win_w, win_h); - } - } - // A notice chip is tagline hung over the body's top rows, so it is - // ruled off from the text beneath it the way a tag is: the same - // colour and thickness along its bottom, running to the window's - // edge when it does. - if (index == groups.notices) for (surface.tagLayers()) |*layer| { - if (layer.rows == 0 or layer.kind != .notice) continue; - const x0 = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; - const x1 = x0 + @as(f32, @floatFromInt(layer.viewport.w)) * layout.w; - const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; - const top = @as(f32, @floatFromInt(layer.viewport.y)) * layout.h; - const rule_y = top + layout.h; - try addDecor(g, gpa, x0, rule_y - dp(1), rule_x1, rule_y, chrome.border, 1, win_w, win_h); - }; - if (index == groups.ink and cursors_shown) try cursorDecor(g, gpa, surface, layout, win_w, win_h); - } -} +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); -/// Each pane's rule between its tag and body, and its scroll rail: a page -/// coloured gutter with a thin track and its thumb, running down through the -/// pixels past the last whole row. -fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ticks: []const pardes.RailTick, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { - const page = chrome.page orelse bg_default; - for (regions) |rail| { - if (rail.kind != .rail or rail.rect.h == 0) continue; - const tag = for (regions) |region| { - if (region.kind == .tag and region.owner == rail.owner) break region; - } else continue; - if (@as(u32, tag.rect.x) + tag.rect.w > cols or @as(u32, tag.rect.y) + tag.rect.h > rows or - @as(u32, rail.rect.y) + rail.rect.h > rows) continue; - const x0 = @as(f32, @floatFromInt(rail.rect.x)) * layout.w; - const x1 = @as(f32, @floatFromInt(tag.rect.x + tag.rect.w)) * layout.w; - // Like the band above it, the rule of a pane at the right edge runs - // on through the pixels past the last whole cell. Under a tag on - // top, over one below its body. - const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; - const tag_bottom = tag.rect.y > rail.rect.y; - const rule_y = @as(f32, @floatFromInt(if (tag_bottom) tag.rect.y else tag.rect.y + tag.rect.h)) * layout.h; - try addDecor(g, gpa, x0, if (tag_bottom) rule_y else rule_y - dp(1), rule_x1, if (tag_bottom) rule_y + dp(1) else rule_y, chrome.tag_rule orelse mixRgb(chrome.tag_bg, page), 1, win_w, win_h); - // Stacked panes are ruled apart as columns are, where one pane's - // body meets the next one's tag (acme's Border). - { - const pane_top = @min(tag.rect.y, rail.rect.y); - const stacked = for (regions) |other| { - if ((other.kind == .body or other.kind == .tag) and other.owner != rail.owner and other.rect.y + other.rect.h == pane_top and - other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; - } else false; - // Inside the tag band's slack, never over its glyphs: the top - // slack of a tag on top, the bottom slack of the one above when - // tags are at the bottom; a pixel at least. - const y = @as(f32, @floatFromInt(pane_top)) * layout.h; - const spare = g.cell_h -| g.tagline_height; - if (stacked and !tag_bottom) { - const room = taglineBandOffset(pane_top, win_h, g.cell_h, g.tagline_height); - try addDecor(g, gpa, x0, y, rule_x1, y + @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), chrome.border, 1, win_w, win_h); - } else if (stacked and pane_top > 0) { - const room = spare - taglineBandOffset(pane_top - 1, win_h, g.cell_h, g.tagline_height); - try addDecor(g, gpa, x0, y - @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), rule_x1, y, chrome.border, 1, win_w, win_h); - } - } + 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]); - const y0 = @as(f32, @floatFromInt(rail.rect.y)) * layout.h; - const body_end = rail.rect.y + rail.rect.h; - const body_y1 = @as(f32, @floatFromInt(body_end)) * layout.h; - const y1 = if (body_end == rows and win_h - body_y1 < layout.h) @max(body_y1, win_h) else body_y1; - // A theme's own track fills its width, the thumb one pixel short - // of it so the track edges it (acme's scrollbar); else a thin rail. - // acme's scrollbar: the track fills the scroll column, under the - // grip's button; the thumb is a pixel short of its right edge, so - // the track edges it. - const column = scrollColumn(g, chrome, rail.rect.x, layout); - try addDecor(g, gpa, x0, y0, x0 + layout.w, y1, page, 1, win_w, win_h); - try addDecor(g, gpa, column[0], y0, column[1], y1, chrome.scroll_track, 1, win_w, win_h); - if (rail.thumb_h != 0 and rail.thumb_span > 0) { - // In pixels, not rows, and with the picture while it glides - // or lags behind the core's rows (both in rows of the body). - const lag: f32 = if (g.glide.follow.offset != 0 and g.glide.pane == rail.owner) - g.glide.lagLines() - else if (g.scroll_pane != null and g.scroll_pane.? == rail.owner) g.scroll_lag else 0; - const track_px = body_y1 - y0; - const size = @min(track_px, @max(layout.h, rail.thumb_span * track_px)); - const at = rail.thumb_at + lag * rail.thumb_span / @as(f32, @floatFromInt(rail.rect.h)); - const thumb_y0 = y0 + std.math.clamp(at * track_px, 0, track_px - size); - const thumb_y1 = if (thumb_y0 + size >= body_y1 - 0.5) y1 else thumb_y0 + size; - try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); - } else if (rail.thumb_h != 0) { - const thumb_y0 = @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y)) * layout.h; - const thumb_y1 = if (rail.thumb_y + rail.thumb_h == rail.rect.h) y1 else @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y + rail.thumb_h)) * layout.h; - try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); - } - // A query's places' ticks over the track and thumb, where its matches - // are in the file (Places.addTicks); the current one last, on top. - const track_px = body_y1 - y0; - for (0..2) |pass| for (ticks) |tick| { - if (tick.owner != rail.owner or tick.current != (pass == 1)) continue; - const at = @as(f32, @floatFromInt(tick.at)) / @as(f32, @floatFromInt(pardes.panes.Places.tick_scale)); - const h = if (tick.current) dp(3) else dp(2); - const ty = y0 + std.math.clamp(at * track_px, 0, track_px - h); - try addDecor(g, gpa, column[0], ty, column[1], ty + h, if (tick.current) chrome.match_current else chrome.match_tick, 1, win_w, win_h); - }; - } + 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); } -/// Halfway between two colours. -const mixRgb = pardes.colors.mix; - -/// A rule's width: the theme's own, or one pixel. -fn rulePx(chrome: *const pardes.Chrome) f32 { - return dp(@floatFromInt(@max(1, chrome.rule_px))); +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)); } -/// The display's density (SDL's window display scale: 2 on a 2x screen), -/// by which every size given in logical pixels is drawn, as acme scales its -/// Border, ButtonBorder and Scrollgap (scalesize). Cells, glyphs and what is -/// measured in them are already the display's pixels and are not scaled. -/// One per process, as its window is. -var display_scale: f32 = 1; +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); +} -/// The window's display scale, or PARDES_TEST_SCALE (a harness forcing 2x); -/// a test window is 1x unless forced, whatever display it lands on, so its -/// captures are the same on any machine. -fn updateDisplayScale(window: *c.SDL_Window) void { - if (std.c.getenv("PARDES_TEST_SCALE")) |forced| { - display_scale = std.fmt.parseFloat(f32, std.mem.span(forced)) catch 1; - } else if (std.c.getenv("PARDES_TEST") != null) { - display_scale = 1; - } else { - const scale = c.SDL_GetWindowDisplayScale(window); - display_scale = if (scale > 0 and std.math.isFinite(scale)) scale else 1; +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; } - display_scale = std.math.clamp(display_scale, 1, 4); + 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); } -/// InactiveDim: the unfocused panes' text faded toward its ground by the -/// setting's percent, never below the pair's own contrast or 4.5, whichever -/// is lower. The window's alone, from the regions' focus: renderFrame -/// begins it each frame. ponytail: one window per process, as display_scale. -var dim: Dim = .{}; +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 Dim = struct { - amount: f32 = 0, - /// The pane with the keyboard, from its regions. - focused: u16 = pardes.Region.none, - /// The few ink and paper pairs a frame has, each faded once. - keys: [32]?[6]u8 = @splat(null), - values: [32][3]u8 = undefined, + 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); +} - fn begin(d: *Dim, percent: u8, regions: []const pardes.Region) void { - d.* = .{ .amount = @as(f32, @floatFromInt(@min(percent, 100))) / 100 }; - for (regions) |region| if (region.active and (region.kind == .grip or region.kind == .tag or region.kind == .body)) { - d.focused = region.owner; - break; - }; - if (d.focused == pardes.Region.none) d.amount = 0; - } +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); - /// Whether pane `owner`'s text fades this frame. - fn of(d: *const Dim, owner: u16) bool { - return d.amount > 0 and owner != d.focused; - } + 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 cell instance's ink faded toward its ground. - fn fade(d: *Dim, instance: *CellInstance) void { - const ink = d.faded(byteRgb(.{ instance.fr, instance.fg, instance.fb }), byteRgb(.{ instance.br, instance.bg, instance.bb })); - instance.fr = @as(f32, @floatFromInt(ink[0])) / 255.0; - instance.fg = @as(f32, @floatFromInt(ink[1])) / 255.0; - instance.fb = @as(f32, @floatFromInt(ink[2])) / 255.0; - } +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)); +} - fn faded(d: *Dim, ink: [3]u8, paper: [3]u8) [3]u8 { - const key = ink ++ paper; - const slot = (@as(usize, ink[0]) *% 31 +% @as(usize, ink[1]) *% 7 +% ink[2] +% @as(usize, paper[0]) *% 13 +% @as(usize, paper[1]) *% 3 +% paper[2]) % d.keys.len; - if (d.keys[slot]) |held| if (std.mem.eql(u8, &held, &key)) return d.values[slot]; - // Contrast falls as the ink nears its paper: the most of `amount` - // that keeps the pair at its own contrast or 4.5, whichever is lower. - const floor = @min(pardes.colors.contrast(ink, paper), 4.5); - var t = d.amount; - if (pardes.colors.contrast(blendLinear(ink, paper, t), paper) < floor) { - var lo: f32 = 0; - var hi: f32 = t; - for (0..8) |_| { - const mid = (lo + hi) / 2; - if (pardes.colors.contrast(blendLinear(ink, paper, mid), paper) >= floor) lo = mid else hi = mid; +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()); } - t = lo; + return out.items; } - d.keys[slot] = key; - d.values[slot] = blendLinear(ink, paper, t); - return d.values[slot]; - } + }.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); +} - fn byteRgb(rgb: [3]f32) [3]u8 { - var out: [3]u8 = undefined; - for (&out, rgb) |*o, v| o.* = @intFromFloat(@round(std.math.clamp(v, 0, 1) * 255)); - return out; +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'); } -}; - -/// `t` of the way from one colour to the other in linear light, so a -/// coloured ink does not muddy on its way to the paper. -fn blendLinear(from: [3]u8, to: [3]u8, t: f32) [3]u8 { - var out: [3]u8 = undefined; - for (&out, from, to) |*o, a, b| { - const l = pardes.colors.to_linear[a] * (1 - t) + pardes.colors.to_linear[b] * t; - o.* = encoded[@intFromFloat(@round(std.math.clamp(l, 0, 1) * (encoded.len - 1)))]; + _ = 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; } - return out; + try std.testing.expect(frames > 5); + try std.testing.expectEqual(@as(f32, 0), g.glide.follow.offset); + try std.testing.expect(!frontendMoving(&g)); } -/// Linear light back to an sRGB channel, in 4096 steps. -const encoded: [4096]u8 = blk: { - @setEvalBranchQuota(1_000_000); - var table: [4096]u8 = undefined; - for (&table, 0..) |*out, i| { - const l = @as(f64, @floatFromInt(i)) / 4095; - const v = if (l <= 0.0031308) l * 12.92 else 1.055 * std.math.pow(f64, l, 1.0 / 2.4) - 0.055; - out.* = @intFromFloat(@round(v * 255)); - } - break :blk table; -}; - -test "InactiveDim fades the unfocused panes' rows alone, never below the text's floor" { +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 pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + const core = try wheelRunFile(gpa); 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)); + 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); } -/// 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)); +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); + } + } } -/// The two short bars on each row of a grip with no mode glyph there, -/// centered in its anchor. -fn gripDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, cells: []const pardes.Cell, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { - if (g.tagline_height < 6 or g.tagline_width < 3) return; - for (regions) |grip| { - if (grip.kind != .grip and grip.kind != .column_grip) continue; - if (grip.rect.h == 0 or grip.rect.y >= rows) continue; - const button = gripButton(g, chrome, grip.rect.x, grip.rect.y, layout); - // Round the button, its first row is the tag's band: nothing of the - // cells under it shows there. - const band = if (grip.active) chrome.tag_focus_bg else chrome.tag_bg; - const left = @as(f32, @floatFromInt(grip.rect.x)) * layout.w; - const right = @as(f32, @floatFromInt(grip.rect.x + grip.rect.w)) * layout.w; - try addDecor(g, gpa, left, button[1], button[0], button[3], band, 1, win_w, win_h); - try addDecor(g, gpa, button[2], button[1], right, button[3], band, 1, win_w, win_h); - if (grip.kind != .grip) continue; - // acme's button ring, two pixels (ButtonBorder) inside the button: - // the focused one's in its own fill. An unfocused dirty one keeps a - // pixel of band inside its ring, so the four states differ in shape - // whatever a theme's colours (a focused dirty one is acme's - // modbutton, filled up to its ring). - { - // The rules drawn over the row (paneDecor, after this) cut into - // it: the ring runs inside them, from rule to rule. - const tag = for (regions) |part| { - if (part.kind == .tag and part.owner == grip.owner) break part; - } else grip; - const tag_bottom = for (regions) |part| { - if (part.kind == .rail and part.owner == grip.owner) break part.rect.y < tag.rect.y; - } else false; - const stacked = !tag_bottom and for (regions) |other| { - if ((other.kind == .body or other.kind == .tag) and other.owner != grip.owner and other.rect.y + other.rect.h == grip.rect.y and - other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; - } else false; - const top_rule: f32 = if (tag_bottom) dp(1) else if (stacked) @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(taglineBandOffset(grip.rect.y, win_h, g.cell_h, g.tagline_height))))) else 0; - const bottom_rule: f32 = if (!tag_bottom and grip.rect.h == 1) dp(1) else 0; - const x0 = button[0]; - const x1 = button[2]; - const y0 = button[1] + top_rule; - const y1 = button[3] - bottom_rule; - const ring = if (grip.active) chrome.grip_focus_ring else chrome.grip_border; - // acme's ButtonBorder: two logical pixels. - const b = dp(2); - try addDecor(g, gpa, x0, y0, x1, y0 + b, ring, 1, win_w, win_h); - try addDecor(g, gpa, x0, y1 - b, x1, y1, ring, 1, win_w, win_h); - try addDecor(g, gpa, x0, y0 + b, x0 + b, y1 - b, ring, 1, win_w, win_h); - try addDecor(g, gpa, x1 - b, y0 + b, x1, y1 - b, ring, 1, win_w, win_h); - if (grip.dirty and !grip.active) { - const gap = b + dp(1); - try addDecor(g, gpa, x0 + b, y0 + b, x1 - b, y0 + gap, band, 1, win_w, win_h); - try addDecor(g, gpa, x0 + b, y1 - gap, x1 - b, y1 - b, band, 1, win_w, win_h); - try addDecor(g, gpa, x0 + b, y0 + gap, x0 + gap, y1 - gap, band, 1, win_w, win_h); - try addDecor(g, gpa, x1 - gap, y0 + gap, x1 - b, y1 - gap, band, 1, win_w, win_h); - } +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()); } - // The marks are the first row's alone, where its cell is blank (no - // mode glyph), centered in the button, in its ink from the region's - // state. - const x = grip.rect.x; - const y = grip.rect.y; - if (x >= cols) continue; - const cell = &cells[@as(usize, y) * cols + x]; - if (cell.default or cell.printableAscii() != ' ') continue; - const rgb = inkOn(gripFill(chrome, grip.active, grip.dirty)); - const center_x = @floor((button[0] + button[2]) / 2); - const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; - const half_w = @max(dp(1), @min(dp(3), @floor((button[2] - button[0] - 2 * dp(3)) / 2))); - // The mode's two bars: a logical pixel thick, a pixel either side of - // the middle. - const bar = dp(1); - try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y - bar - dp(1)), @floor(center_x + half_w), @floor(center_y - dp(1)), rgb, 1, win_w, win_h); - try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y + dp(1)), @floor(center_x + half_w), @floor(center_y + dp(1) + bar), rgb, 1, win_w, win_h); + }.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 theme's own rules and scrollbar are drawn at its widths: acme's 2px black rules and 12px track" { +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(); - _ = 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; + 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); } - 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; + // 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(usize, 1), spines); - try std.testing.expect(tracks >= 2); + try std.testing.expectEqual(@as(f32, @floatFromInt(s.cursor.?.y)), caretRow(&g, s, now).?); } -test "the scrollbar thumb moves by the pixel and follows a glide" { +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 = 80, .rows = 24 }); + const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); + 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.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; + 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 }; } }; - 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); + 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 "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".*)))); +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); - 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); + 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 "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 "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 "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()); +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); - 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); - } + // 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 "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 }); +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(); - _ = try core.newShell(1, ""); + 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)); - 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; + 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); } - }; - 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); + for (s.tagLayers()) |layer| notices = notices or (layer.rows != 0 and layer.kind == .notice); } -} + try std.testing.expect(notices); -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); + // 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); } - // 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; + 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); } - try std.testing.expectEqual(@as(u32, 0), groups.items[groups.notices].decor_count); } -test "a body tells its first line" { +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 = 80, .rows = 24 }); + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 20 }); 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 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; } -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; - -/// Where the frame draws the focused caret, its top in grid rows: from its -/// own springs (the quad's, while it moves or while a glide moves the text) -/// or its cell; carried by the text's glide when its line rode it. The probe -/// records it and the glide tests hold its invariants. -fn caretRow(g: *const Gui, surface: *const pardes.Surface, now_ns: u64) ?f32 { - const cursor = surface.cursor orelse return null; - const quad = g.caret.placed and (g.caret.moving() or g.glide.follow.offset != 0); - return if (quad) g.caret.sample(now_ns)[0][1] - caretRide(g, surface) else @floatFromInt(cursor.y); +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); } -/// What the caret's ease sees in the frame about to be drawn (Caret.see): -/// the focused cursor's box in cells (its own cell's, or the layer's that -/// draws it), and the focused body's pane, first line and place. -fn seeCaret(g: *Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, now_ns: u64) void { - const box: ?Caret.Box = if (surface.cursor) |cursor| box: { - var boxes: [max_cursors]CursorBox = undefined; - const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; - if (all.len == 0) break :box null; - const cx = (@as(f32, @floatFromInt(cursor.x)) + 0.5) * layout.w; - const cy = (@as(f32, @floatFromInt(cursor.y)) + 0.5) * layout.h; - var best = all[0]; - var nearest = std.math.inf(f32); - for (all) |b| { - const dx = (b.x0 + b.x1) / 2 - cx; - const dy = (b.y0 + b.y1) / 2 - cy; - if (dx * dx + dy * dy < nearest) { - nearest = dx * dx + dy * dy; - best = b; - } - } - break :box .{ .x = best.x0 / layout.w, .y = best.y0 / layout.h, .w = (best.x1 - best.x0) / layout.w, .h = (best.y1 - best.y0) / layout.h }; - } else null; - for (surface.regionList()) |region| if (region.kind == .body and region.active) - return g.caret.see(box, region.owner, region.line, region.rect.x, region.rect.y, now_ns); - g.caret.see(box, pardes.Region.none, 0, 0, 0, now_ns); +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); + } } -/// The caret's ease (G3), the window's own: the focused cursor's quad on -/// critically damped springs at its box's corners, in grid cells, on the -/// window's clock, from the cursor the Surface shows. A jump glides, its -/// leading corners first, bowing a little on a long one; a step eases, and -/// a stream of them (typing, a held key) keeps up; a scroll or a pane's move -/// carries it with its text; a focus change glides from where it was drawn. -/// The quad is drawn only while it moves: at rest the cells draw the cursor. -const Caret = struct { - /// Top left, top right, bottom right, bottom left; x then y. - corners: [4][2]Spring = @splat(@splat(.{})), - target: Box = .{}, - from_centre: [2]f32 = .{ 0, 0 }, - placed: bool = false, - /// When the last step (a move of a cell or less) came. - step_ns: u64 = 0, - /// The focused body as the last frame showed it: its pane, its first - /// line and its top left, to tell a scroll and a pane's move from the - /// caret's own. - seen: struct { owner: u8 = pardes.Region.none, line: i32 = 0, x: u16 = 0, y: u16 = 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)); - /// The default flavour's spring, as fast again as the caret follows - /// input (it settles in 90-150 ms). - const omega: f32 = 34 * 2.4; - /// The trailing corners of a jump, a little behind the leading ones. - const follow: f32 = 0.85; - /// A step's spring, stiffer than a jump's. - const step_pace: f32 = 1.5; - /// A jump longer than this, in cells, bows, by this much of its length. - const arc_from: f32 = 8; - const arc: f32 = 0.04; - /// Steps this close are a stream: each lands. - const stream_ns: u64 = 150 * std.time.ns_per_ms; + // 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); +} - const Box = struct { x: f32 = 0, y: f32 = 0, w: f32 = 0, h: f32 = 0 }; +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]); - /// One axis on a critically damped spring, closed form: a new target - /// keeps the value and its speed; settled, it is its target. - const Spring = struct { - omega: f32 = omega, - target: f32 = 0, - from: f32 = 0, - velocity: f32 = 0, - from_ns: u64 = 0, - settled: bool = true, + // 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); - fn at(s: *const Spring, now_ns: u64) [2]f32 { - if (s.settled) return .{ s.target, 0 }; - const t: f32 = @floatCast(@as(f64, @floatFromInt(now_ns -| s.from_ns)) / std.time.ns_per_s); - const x0 = s.from - s.target; - const k = s.velocity + s.omega * x0; - const decay = @exp(-s.omega * t); - return .{ s.target + (x0 + k * t) * decay, (s.velocity - s.omega * t * k) * decay }; - } + // 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 value(s: *const Spring, now_ns: u64) f32 { - return s.at(now_ns)[0]; - } +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]); + } +} - fn retarget(s: *Spring, target: f32, now_ns: u64, w: f32) void { - if (target == s.target) return; - const state = s.at(now_ns); - s.* = .{ .omega = w, .target = target, .from = state[0], .velocity = state[1], .from_ns = now_ns, .settled = false }; +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 })); +} - /// Settles within half a percent of a cell, barely moving; true - /// while it still moves. - fn step(s: *Spring, now_ns: u64) bool { - if (s.settled) return false; - const state = s.at(now_ns); - if (@abs(state[0] - s.target) < 5e-3 and @abs(state[1]) < 5e-2) s.settled = true; - return !s.settled; - } - }; +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 = .{}; - fn cornersOf(box: Box) [4][2]f32 { - return .{ .{ box.x, box.y }, .{ box.x + box.w, box.y }, .{ box.x + box.w, box.y + box.h }, .{ box.x, box.y + box.h } }; + 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); +} - fn centre(box: Box) [2]f32 { - return .{ box.x + box.w / 2, box.y + box.h / 2 }; +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()); +} - /// Heads for `box`: eased, or landed at once (`land`: a scroll moved - /// the text under it, not the caret). - fn aim(caret: *Caret, box: Box, now_ns: u64, land_it: bool) void { - if (caret.placed and std.meta.eql(box, caret.target) and !(land_it and caret.moving())) return; - const to = cornersOf(box); - const from_c = if (caret.placed) caret.centreAt(now_ns) else centre(box); - const to_c = centre(box); - const dx = to_c[0] - from_c[0]; - const dy = to_c[1] - from_c[1]; - const jump = @abs(dx) > 1.01 or @abs(dy) > 1.01; - // A step is measured mark to mark, not from where an ease under way - // has got to (a held key's steps would read as jumps from there). - const last = centre(caret.target); - const one_step = caret.placed and @abs(to_c[0] - last[0]) <= 1.01 and @abs(to_c[1] - last[1]) <= 1.01; - const streaming = one_step and caret.step_ns != 0 and now_ns -| caret.step_ns < stream_ns; - if (one_step) caret.step_ns = now_ns; - const land = !caret.placed or land_it or streaming; - caret.from_centre = from_c; - caret.target = box; - caret.placed = true; - for (&caret.corners, to) |*corner, point| { - // Leading: the corner ahead of the move, on the side it goes. - const ahead = (point[0] - to_c[0]) * dx + (point[1] - to_c[1]) * dy; - const w = if (jump) omega * (if (ahead > 0) 1 else follow) else omega * step_pace; - for (corner, point) |*axis, v| { - if (land) axis.* = .{ .omega = w, .target = v, .from = v } else axis.retarget(v, now_ns, w); - } +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); +} - fn centreAt(caret: *const Caret, now_ns: u64) [2]f32 { - var sum: [2]f32 = .{ 0, 0 }; - for (caret.corners) |corner| for (&sum, corner) |*s, axis| { - s.* += axis.value(now_ns) / 4; - }; - return sum; - } - - /// The text under it moved by (dx, dy) cells: so does the quad. - fn shift(caret: *Caret, dx: f32, dy: f32) void { - for (&caret.corners) |*corner| for (corner, [2]f32{ dx, dy }) |*axis, d| { - axis.from += d; - axis.target += d; - }; - caret.from_centre = .{ caret.from_centre[0] + dx, caret.from_centre[1] + dy }; - caret.target.x += dx; - caret.target.y += dy; - } - - /// The quad at `now_ns`, bowed on a long jump. - fn sample(caret: *const Caret, now_ns: u64) [4][2]f32 { - var out: [4][2]f32 = undefined; - for (&out, caret.corners) |*point, corner| for (point, corner) |*v, axis| { - v.* = axis.value(now_ns); - }; - const to_c = centre(caret.target); - const dx = to_c[0] - caret.from_centre[0]; - const dy = to_c[1] - caret.from_centre[1]; - const length = @sqrt(dx * dx + dy * dy); - if (length < arc_from) return out; - const now_c = caret.centreAt(now_ns); - const left = @sqrt((to_c[0] - now_c[0]) * (to_c[0] - now_c[0]) + (to_c[1] - now_c[1]) * (to_c[1] - now_c[1])); - const travelled = std.math.clamp(1 - left / length, 0, 1); - const bow = arc * length * 4 * travelled * (1 - travelled); - for (&out) |*point| { - point[0] += -dy / length * bow; - point[1] += dx / length * bow; +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); } - return out; } +} - /// Steps the springs to `now_ns`; true while the quad still moves. - fn step(caret: *Caret, now_ns: u64) bool { - var any = false; - for (&caret.corners) |*corner| for (corner) |*axis| { - if (axis.step(now_ns)) any = true; - }; - return any; +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))); } +} - /// How far, in cells, the furthest corner still is from its mark. - fn remaining(caret: *const Caret, now_ns: u64) f32 { - var most: f32 = 0; - for (caret.corners) |corner| for (corner) |axis| { - most = @max(most, @abs(axis.value(now_ns) - axis.target)); - }; - return most; - } +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)); +} - fn moving(caret: *const Caret) bool { - for (caret.corners) |corner| for (corner) |axis| { - if (!axis.settled) return true; - }; - return false; +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); +} - /// The frame about to be drawn shows the focused cursor at `box` (grid - /// cells; null: none) in pane `owner`'s body, whose first line is - /// `line` and top left (x, y): carried with that body when it moved or - /// scrolled, eased to its box otherwise. - fn see(caret: *Caret, box: ?Box, owner: u8, line: i32, x: u16, y: u16, now_ns: u64) void { - const b = box orelse { - // Nowhere to land: a glide under way stops; the next cursor - // lands where it is. - caret.* = .{}; - return; - }; - var land = false; - const was = caret.seen; - if (was.owner == owner and owner != pardes.Region.none) { - // The pane moved in the layout: its caret moves with it. - caret.shift(@as(f32, @floatFromInt(x)) - @as(f32, @floatFromInt(was.x)), @as(f32, @floatFromInt(y)) - @as(f32, @floatFromInt(was.y))); - // Scrolled: the text moved, not the caret; it lands on its - // cell (the glide draws it with the text, caretRide). - land = line != was.line; +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; } - caret.seen = .{ .owner = owner, .line = line, .x = x, .y = y }; - caret.aim(b, now_ns, land); - _ = caret.step(now_ns); - } -}; + }; + 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 "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 "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); } -/// 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). -fn caretRide(g: *const Gui, surface: *const pardes.Surface) f32 { - const glide = &g.glide; - const cu = surface.cursor orelse return 0; - if (glide.follow.offset != 0) { - if (!glide.caret_rides) return 0; - const x0 = glide.rect.x + config.GUTTER; - if (cu.x < x0 or cu.x >= x0 + glide.bw() or cu.y < glide.body_y or cu.y >= glide.body_y + glide.body_h) return 0; - return glide.follow.offset; +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); } - // A fine wheel's or a touchpad's fraction (scroll_lag) holds the whole - // body off its cells, the caret's row with the rest, at rest too. - if (g.scroll_lag == 0 or g.scroll_pane == null) return 0; - const r = g.scroll_rect; - if (cu.x < r.x + config.GUTTER or cu.x >= r.x + r.w or cu.y < g.scroll_body_y or cu.y >= g.scroll_body_y + g.scroll_body_h) return 0; - 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; +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); } - 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; - // The focused one is drawn with its line where a wheel's fraction holds - // the text off its cells (a block is a cell of the shifted rows). - // The focused box is the one nearest its cell (a body layer's is lifted - // off the grid), as seeCaret finds it. - const ride = caretRide(g, surface) * layout.h; - const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; - var focused: usize = all.len; - if (surface.cursor) |cu| { - const cx = (@as(f32, @floatFromInt(cu.x)) + 0.5) * layout.w; - const cy = (@as(f32, @floatFromInt(cu.y)) + 0.5) * layout.h; - var nearest = std.math.inf(f32); - for (all, 0..) |b, i| { - const d = ((b.x0 + b.x1) / 2 - cx) * ((b.x0 + b.x1) / 2 - cx) + ((b.y0 + b.y1) / 2 - cy) * ((b.y0 + b.y1) / 2 - cy); - if (d < nearest) { - nearest = d; - focused = i; +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); } - for (all, 0..) |box, i| if (box.bar) { - const shift = if (i == focused) ride else 0; - try addDecor(g, gpa, box.x0, box.y0 - shift, box.x1, box.y1 - shift, box.rgb, 1, win_w, win_h); - }; } -/// The triangle overlay: the cursor's glide, over everything. -fn buildOverlay( - g: *Gui, - which: pardes.config.Runtime.Pet, - trail_on: bool, - surface: *const pardes.Surface, - now_ns: u64, - sw: u32, - sh: u32, -) u32 { - if (g.overlay_vertices.len == 0 or sw == 0 or sh == 0) return 0; - var builder = OverlayBuilder{ .vertices = g.overlay_vertices, .win_w = @floatFromInt(sw), .win_h = @floatFromInt(sh) }; - appendWorkspacePet(g, which, surface, &builder); - appendJumpTrail(g, trail_on, surface, now_ns, &builder); - appendCursorGlide(g, surface, now_ns, &builder); - return @intCast(builder.len); +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); } -/// A jump's trail (jump_trail.zig): the cells behind the cursor in its -/// body, on the page's own ground, drawn over toward the text's colour. -fn appendJumpTrail(g: *Gui, on: bool, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { - var at: [5]JumpTrail.Cell = undefined; - const lit = g.trail.see(if (surface.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); - if (lit.len == 0) return; - const cursor = surface.cursor.?; - const body = for (surface.regionList()) |region| { - if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and - cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; - } else return; - const page = surface.chrome.page orelse bg_default; - const w: f32 = @floatFromInt(g.cell_w); - const h: f32 = @floatFromInt(g.cell_h); - for (lit) |cell| { - if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue; - const under = &surface.cells[@as(usize, @intCast(cell.y)) * surface.cols + @as(usize, @intCast(cell.x))]; - // On the page's own ground alone: never a selection or a match. - const ground: [3]u8 = if (under.default) page else switch (under.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (!std.mem.eql(u8, &ground, &page)) continue; - var color = overlayRgb(surface.chrome.fg orelse fg_default); - color.a = cell.strength; - const x0 = @as(f32, @floatFromInt(cell.x)) * w; - const y0 = @as(f32, @floatFromInt(cell.y)) * h; - builder.addRect(x0, y0, x0 + w, y0 + h, color); - } +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" { @@ -8606,49 +8783,6 @@ test "a jump's trail is drawn behind the cursor in its body, and gone by 120 ms" 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. -fn appendWorkspacePet(g: *Gui, which: pardes.config.Runtime.Pet, surface: *const pardes.Surface, builder: *OverlayBuilder) void { - const kind: pet.Kind = @fromBackingInt(@backingInt(which)); - if (kind == .off or surface.rows == 0 or surface.cols == 0) { - g.pet_state = .{}; - return; - } - var occupied: usize = 0; - for (surface.cells[0..surface.cols], 0..) |*cell, i| { - if (cellCodepoint(cell) != ' ') occupied = i + 1; - } - const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); - const region = if (occupied >= surface.cols) null else pet.lane( - occupied, - @floatFromInt(g.tagline_width), - builder.win_w, - band_top, - @floatFromInt(g.tagline_height), - ); - // ponytail: it moves when the window draws; a wake of its own for an - // idle window if a still pet ever matters. - const pose = g.pet_state.sample(kind, c.SDL_GetTicks(), region) orelse return; - const ink = overlayRgb(surface.chrome.tag_fg); - const eye = overlayRgb(surface.chrome.tag_bg); - // Behind the cursor: the overlay is over the cells, so the pixels a - // cursor covers are left out. - var boxes: [max_cursors]CursorBox = undefined; - const cursors = boxes[0..cursorBoxes(g, surface, fixedCellLayout(g), builder.win_h, &boxes)]; - for (0..pet.height) |y| for (0..pet.width) |x| { - const color = pet.pixel(kind, pose, x, y); - if (color == 0) continue; - const x0 = pose.x + @as(f32, @floatFromInt(x)) * pose.scale; - const y0 = pose.y + @as(f32, @floatFromInt(y)) * pose.scale; - const covered = for (cursors) |box| { - if (x0 < box.x1 and x0 + pose.scale > box.x0 and y0 < box.y1 and y0 + pose.scale > box.y0) break true; - } else false; - if (covered) continue; - builder.addRect(x0, y0, x0 + pose.scale, y0 + pose.scale, if (color == 2) eye else ink); - }; -} - 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(.{}); @@ -8675,140 +8809,6 @@ test "a pet stays past the workspace tag's text, and off it is gone" { 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, - .g = @as(f32, @floatFromInt(rgb[1])) / 255.0, - .b = @as(f32, @floatFromInt(rgb[2])) / 255.0, - .a = 1, - }; -} - -/// G3: the focused cursor while it glides or blinks, its quad from the -/// window's caret (Caret, grid cells) in its cursor colour; a little less -/// than solid, so the glyphs it passes over stay legible. -fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { - const chrome = &surface.chrome; - if (g.cursor_quad_alpha <= 0.001) return; - const layout = fixedCellLayout(g); - const ride = caretRide(g, surface); - // Never off the grid, however a long jump bows. - var quad = g.caret.sample(now_ns); - for (&quad) |*point| point.* = .{ std.math.clamp(point[0], 0, @as(f32, @floatFromInt(surface.cols))), std.math.clamp(point[1], 0, @as(f32, @floatFromInt(surface.rows))) }; - if (ride != 0) { - // Carried past the body's edge with its line: clipped as the text is. - const mid = quad[0][1] - ride + 0.5; - const top: f32 = @floatFromInt(g.glide.body_y); - if (mid < top or mid > top + @as(f32, @floatFromInt(g.glide.body_h))) return; - } - var px: [4][2]f32 = undefined; - var centre: [2]f32 = .{ 0, 0 }; - for (&px, 0..) |*point, i| { - point.* = .{ quad[i][0] * layout.w, (quad[i][1] - ride) * layout.h }; - centre[0] += point[0] / 4; - centre[1] += point[1] / 4; - } - // Its colour: the cursor the cells would draw nearest the quad. - var boxes: [max_cursors]CursorBox = undefined; - var rgb: [3]u8 = chrome.fg orelse fg_default; - var nearest: f32 = std.math.inf(f32); - for (boxes[0..cursorBoxes(g, surface, layout, builder.win_h, &boxes)]) |box| { - const dx = (box.x0 + box.x1) / 2 - centre[0]; - const dy = (box.y0 + box.y1) / 2 - centre[1]; - if (dx * dx + dy * dy < nearest) { - nearest = dx * dx + dy * dy; - rgb = box.rgb; - } - } - const color: OverlayColor = .{ .r = @as(f32, @floatFromInt(rgb[0])) / 255, .g = @as(f32, @floatFromInt(rgb[1])) / 255, .b = @as(f32, @floatFromInt(rgb[2])) / 255, .a = g.cursor_quad_alpha }; - builder.addTri(px[0][0], px[0][1], px[1][0], px[1][1], px[2][0], px[2][1], color); - 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; - const dst: [*]u8 = @ptrCast(ptr); - const src: [*]const u8 = @ptrCast(g.overlay_vertices.ptr); - @memcpy(dst[0..byte_len], src[0..byte_len]); - c.SDL_UnmapGPUTransferBuffer(g.device, g.overlay_vxfer); - const copy = c.SDL_BeginGPUCopyPass(cmd); - const src_loc = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.overlay_vxfer, .offset = 0 }; - const dst_region = c.SDL_GPUBufferRegion{ .buffer = g.overlay_vbuf, .offset = 0, .size = byte_len }; - c.SDL_UploadToGPUBuffer(copy, &src_loc, &dst_region, false); - c.SDL_EndGPUCopyPass(copy); - return true; -} - -fn pushLayerOpacity(cmd: *c.SDL_GPUCommandBuffer, pass: ?*c.SDL_GPURenderPass, opacity: f32) void { - const uniforms = [4]f32{ opacity, 0, 0, 0 }; - c.SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms, @sizeOf(@TypeOf(uniforms))); - // The source alpha is geometric/image coverage, not window opacity. Its - // alpha contribution is multiplied by this constant separately, so a - // rail repainted over a gutter still has alpha p, not p + p*(1-p). - c.SDL_SetGPUBlendConstants(pass, .{ .r = opacity, .g = opacity, .b = opacity, .a = opacity }); -} - -fn drawOverlayGpu(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, rp: ?*c.SDL_GPURenderPass, vertex_count: u32) void { - if (vertex_count == 0) return; - const pass = rp orelse return; - c.SDL_BindGPUGraphicsPipeline(pass, g.overlay_pipeline); - const binding = c.SDL_GPUBufferBinding{ .buffer = g.overlay_vbuf, .offset = 0 }; - c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1); - pushLayerOpacity(cmd, pass, backgroundOpacity(g.applied_window_opacity)); - c.SDL_DrawGPUPrimitives(pass, vertex_count, 1, 0, 0); -} - -const OverlayBuilder = struct { - vertices: []OverlayVertex, - len: usize = 0, - win_w: f32, - win_h: f32, - - fn addVertex(b: *OverlayBuilder, px: f32, py: f32, color: OverlayColor) void { - if (b.len >= b.vertices.len) return; - b.vertices[b.len] = .{ - .x = (px / b.win_w) * 2.0 - 1.0, - .y = 1.0 - (py / b.win_h) * 2.0, - .r = color.r, - .g = color.g, - .b = color.b, - .a = color.a, - }; - b.len += 1; - } - - fn addTri(b: *OverlayBuilder, x0: f32, y0: f32, x1: f32, y1: f32, x2: f32, y2: f32, color: OverlayColor) void { - if (b.len + 3 > b.vertices.len) return; - b.addVertex(x0, y0, color); - b.addVertex(x1, y1, color); - b.addVertex(x2, y2, color); - } - - fn addRect(b: *OverlayBuilder, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, color: OverlayColor) void { - if (b.len + 6 > b.vertices.len) return; - const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, b.win_w); - const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, b.win_w); - const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, b.win_h); - const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, b.win_h); - if (x1 <= x0 or y1 <= y0) return; - b.addTri(x0, y0, x1, y0, x1, y1, color); - b.addTri(x0, y0, x1, y1, x0, y1, color); - } -}; - -fn envU16(env: *std.process.Environ.Map, name: []const u8) ?u16 { - const raw = env.get(name) orelse return null; - return std.fmt.parseInt(u16, raw, 10) catch null; -} - 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(.{}); -- cgit v1.3